public static Iterator<?> toIterator(TemplateContext ctx, Object o) { if (o == null) { return IteratorUtils.NULL_ITERATOR; } if (o instanceof Iterator<?>) { return (Iterator<?>) o; } if (o instanceof Iterable<?>) { return ((Iterable<?>) o).iterator(); } if (o instanceof Map<?, ?>) { return IteratorUtils.toIterator((Map<?, ?>) o); } if (isString(ctx, o)) { return IteratorUtils.toIterator(toString(ctx, o)); } if (isArray(ctx, o)) { return IteratorUtils.toIteratorArray(o); } if (o instanceof Enumeration<?>) { return Iterators.forEnumeration((Enumeration<?>) o); } ctx.warn("Cannot iterate over object of type " + o.getClass()); return IteratorUtils.NULL_ITERATOR; }
/** 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; }