public static boolean toBoolean(TemplateContext ctx, Object o) { if (o == null) { return false; } if (o instanceof Boolean) { return (Boolean) o; } if (o instanceof Number) { double d = ((Number) o).doubleValue(); return !Double.isNaN(d) && d != 0; } if (o instanceof Collection<?>) { return !((Collection<?>) o).isEmpty(); } if (o instanceof Map<?, ?>) { return !((Map<?, ?>) o).isEmpty(); } if (Types.isString(ctx, o)) { return !StringUtils.isEmpty(Types.toString(ctx, o)); } return true; }
/** Coerces the object to the indicated type. */ public static Object coerce(TemplateContext ctx, Class<?> type, final Object o) { Object arg; if (o != null && type == o.getClass()) { arg = o; } else if (type == String.class) { arg = Types.toString(ctx, o); } else if (type == int.class || type == Integer.class) { arg = Types.toInteger(ctx, o); } else if (type == long.class || type == Long.class) { arg = Types.toLong(ctx, o); } else if (type == float.class || type == Float.class || type == double.class || type == Double.class) { arg = Types.toDouble(ctx, o); } else if (type == boolean.class || type == Boolean.class) { arg = Types.toBoolean(ctx, o); } else if (type == Iterator.class) { arg = Types.toIterator(ctx, o); } else { if (o == null) { arg = null; } else { final Converter<Object, Object> converter = ctx.getConverter(o.getClass(), type); if (converter == null) { arg = o; } else { try { arg = converter.convert(o); } catch (ConverterException e) { ctx.warn("Conversion error", e); return null; } } } } return arg; }