protected Map getComplexParams(Map params) { HashMap map = new HashMap(params.size()); for (Iterator iterator = params.entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); Object value = entry.getValue(); if (value != null && complexType(value)) { if (value instanceof freemarker.ext.beans.BeanModel) { map.put(entry.getKey(), ((freemarker.ext.beans.BeanModel) value).getWrappedObject()); } else if (value instanceof SimpleNumber) { map.put(entry.getKey(), ((SimpleNumber) value).getAsNumber()); } else if (value instanceof SimpleSequence) { try { map.put(entry.getKey(), ((SimpleSequence) value).toList()); } catch (TemplateModelException e) { if (LOG.isErrorEnabled()) { LOG.error("There was a problem converting a SimpleSequence to a list", e); } } } } } return map; }
@SuppressWarnings("rawtypes") @Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { try { SimpleNumber pFor = (SimpleNumber) params.get("for"); Number forMillis = null; if (pFor != null) { forMillis = pFor.getAsNumber(); try { Thread.sleep(forMillis.longValue()); } catch (InterruptedException e) { e.printStackTrace(); } } } catch (Throwable t) { t.printStackTrace(); } }
@Override public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException { testAtLeastOneArgument(arguments); String value = readValue(arguments.get(0)); MessageFormat formatter = new MessageFormat(value, bundle.getLocale()); if (arguments.size() == 1) { value = formatter.format(new Object[] {}); } else { List<Object> parameters = new ArrayList<>(); for (Object obj : arguments.subList(1, arguments.size())) { if (obj instanceof SimpleNumber) { parameters.add(((SimpleNumber) obj).getAsNumber()); } else if (obj instanceof SimpleDate) { parameters.add(((SimpleDate) obj).getAsDate()); } else { parameters.add(obj.toString()); } } value = formatter.format(parameters.toArray(), new StringBuffer(), null).toString(); } return value; }
@Override @SuppressWarnings("unchecked") public Object exec(List list) throws TemplateModelException { if (list.size() != 2) { throw new TemplateModelException("Wrong number of arguments for method isAssignableFrom()." + " Method has two required parameters: [Class, SimpleNumber]. Found: " + list.size()); } Object arg1 = ((WrapperTemplateModel) list.get(0)).getWrappedObject(); if (!(arg1 instanceof Method)) { throw new TemplateModelException("Wrong type of the first parameter." + " It should be Method. Found: " + arg1.getClass()); } Object arg2 = list.get(1); if (!(arg2 instanceof SimpleNumber)) { throw new TemplateModelException("Wrong type of the second parameter." + " It should be SimpleNumber. Found: " + arg2.getClass()); } return timeStepModel.hasStartNanosAnnotation((Method) arg1, ((SimpleNumber) arg2).getAsNumber().intValue() - 1); }
@Override public Object exec(List arguments) throws TemplateModelException { ExecutionStatistics.get().begin(NAME); if (arguments.size() < 1) { throw new TemplateModelException("Error, method expects one or two arguments (Integer, [verbosity:String])"); } SimpleNumber simpleNumber = (SimpleNumber) arguments.get(0); int effort = simpleNumber.getAsNumber().intValue(); Verbosity verbosity = Verbosity.SHORT; if (arguments.size() > 1) { final TemplateScalarModel verbosityModel = (TemplateScalarModel) arguments.get(1); String verbosityString = verbosityModel.getAsString(); verbosity = Verbosity.valueOf(verbosityString.toUpperCase()); } String result = EffortReportService.getEffortLevelDescription(verbosity, effort); ExecutionStatistics.get().end(NAME); return result; }
@Override public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException { if (arguments.size() != 1) { throw new TemplateModelException("Error, method expects one argument (int)"); } SimpleNumber freemarkerArg = (SimpleNumber) arguments.get(0); int effortPoints = freemarkerArg.getAsNumber().intValue(); if (effortPoints == 0) return "info"; else if (effortPoints < 8) return "warning"; else if (effortPoints < 14) return "severe"; else return "critical"; }
@Override public TemplateModel get(String s) throws TemplateModelException { if (METHOD_DAYS.equalsIgnoreCase(s)) { return new SimpleNumber(getObject().getDays()); } else if (METHOD_MONTHS.equalsIgnoreCase(s)) { return new SimpleNumber(getObject().getMonths()); } else if (METHOD_YEARS.equalsIgnoreCase(s)) { return new SimpleNumber(getObject().getYears()); } throw new TemplateModelException(METHOD_UNKNOWN_MSG + s); }
@Override public TemplateModel get(String s) throws TemplateModelException { if (METHOD_NANO.equalsIgnoreCase(s)) { return new SimpleNumber(getObject().getNano()); } else if (METHOD_SECONDS.equalsIgnoreCase(s)) { return new SimpleNumber(getObject().getSeconds()); } throw new TemplateModelException(METHOD_UNKNOWN_MSG + s); }
@SuppressWarnings("unchecked") public Object exec(List arguments) throws TemplateModelException { TemplateModel model = (TemplateModel) arguments.get(0); if (model instanceof SimpleNumber) { SimpleNumber number = (SimpleNumber) model; return "" + number; } else if (model instanceof BeanModel) { BeanModel arg0 = (BeanModel) model; Cost cost = (Cost) arg0.getAdaptedObject(Cost.class); return "Cost: " + costModel.computeOverall(cost) + " [" + cost + "]"; } else { throw new IllegalStateException(); } }
@SuppressWarnings("unchecked") public Object exec(List arguments) throws TemplateModelException { TemplateModel model = (TemplateModel) arguments.get(0); if (model instanceof SimpleNumber) { SimpleNumber number = (SimpleNumber) model; return number; } else if (model instanceof BeanModel) { BeanModel arg0 = (BeanModel) model; Cost cost = (Cost) arg0.getAdaptedObject(Cost.class); return costModel.computeOverall(cost); } else { throw new IllegalStateException(); } }
public static Integer getInt(Map params, String paramName){ SimpleNumber valueModel=(SimpleNumber)params.get(paramName); if (valueModel!=null){ int value=valueModel.getAsNumber().intValue(); return value; } return null; }
public static Long getLong(Map params, String paramName){ SimpleNumber valueModel=(SimpleNumber)params.get(paramName); if (valueModel!=null){ Long value=valueModel.getAsNumber().longValue(); return value; } return null; }
public static BigDecimal getBigDecimal(Map params, String paramName){ SimpleNumber valueModel=(SimpleNumber)params.get(paramName); if (valueModel!=null){ if (valueModel.getAsNumber() instanceof BigDecimal){ return (BigDecimal)valueModel.getAsNumber(); } return new BigDecimal(valueModel.getAsNumber().doubleValue()); } return null; }
@SuppressWarnings("unchecked") public String getStringArg(Map args, String key) { Object o = args.get(key); if (o instanceof SimpleScalar) { return ((SimpleScalar) o).getAsString(); } else if (o instanceof StringModel) { return ((StringModel) o).getAsString(); } else if (o instanceof SimpleNumber) { return ((SimpleNumber) o).getAsNumber().toString(); } else if (o instanceof NumberModel) { return ((NumberModel) o).getAsNumber().toString(); } return null; }
@Override public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException { testExactlyOneArgument(arguments); Object arg = arguments.get(0); testArgumentIsNumber(arg); long millis = ((SimpleNumber) arg).getAsNumber().longValue(); long hrs = TimeUnit.MILLISECONDS.toHours(millis); long min = TimeUnit.MILLISECONDS.toMinutes(millis) % MINUTES_PER_HOUR; long sec = TimeUnit.MILLISECONDS.toSeconds(millis) % SECONDS_PER_MINUTES; return String.format("%02d:%02d:%02d", hrs, min, sec); }
protected void testArgumentIsNumber(Object arg) throws TemplateModelException { if (!(arg instanceof SimpleNumber)) { String message = "Argument (%s) must be a number."; message = String.format(message, arg); throw new TemplateModelException(message); } }
@Test public void testParamTranslation() throws TemplateModelException, ParseException { ResourceBundle bundle = new SimpleBundle("foo", "bar {0} {1} {2}"); FreemarkerMessageMethod method = new FreemarkerMessageMethod(bundle); SimpleNumber simpleNumber = new SimpleNumber(1234567); Date date = new Date(new SimpleDateFormat("yyyy-MM-dd hh:mm").parse("2014-03-14 13:11").getTime()); SimpleDate simpleDate = new SimpleDate(date); assertEquals("bar baz 1,234,567 3/14/14 1:11 PM", method.exec(Arrays.asList("foo", "baz", simpleNumber, simpleDate))); }
@Test public void testDurationFormat() throws TemplateModelException { long hours = 1 * 60 * 60 * 1000; long minutes = 2 * 60 * 1000; long seconds = 3 * 1000; SimpleNumber duration = new SimpleNumber(hours + minutes + seconds); assertEquals("01:02:03", new FreemarkerDurationMethod().exec(Arrays.asList(duration)).toString()); }
@Override public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException { if (arguments.size() < 2) throw new TemplateModelException(NAME + ": Expected 2 arguments, count and maximum count."); if (!(arguments.get(0) instanceof TemplateNumberModel)) throw new TemplateModelException(NAME + ": Both arguments must be numbers, but the first was " + arguments.get(0).getClass().getName()); if (!(arguments.get(1) instanceof TemplateNumberModel)) throw new TemplateModelException(NAME + ": Both arguments must be numbers, but the second was " + arguments.get(1).getClass().getName()); int count = ((TemplateNumberModel) arguments.get(0)).getAsNumber().intValue(); if (count < 1) return new SimpleNumber(0); int maximum = ((TemplateNumberModel) arguments.get(1)).getAsNumber().intValue(); if (maximum < 0) throw new TemplateModelException(NAME + "Maximum must be at least 0, " + maximum); if (count > maximum) { LOG.severe("Count " + count + " is larger than maximum " + maximum + ". Using the maximum as count."); count = maximum; } double ratio = ((double)count) / ((double)maximum + QUITE_A_LOT_FACTOR); // <0..1> // Map it to scale 1..1000. double ratio2 = 1.0d + ratio * (998d * (1-FLATTENER)); double log10 = Math.log10(ratio2) / 3D; // 0..2.999 => 0..0.999 //LOG.info(String.format("count: %d, max: %d, ratio %f, ratio2 %f, log10 %f", count, maximum, ratio, ratio2, log10)); return new NumberModel(Double.valueOf(log10), new DefaultObjectWrapper()); }
private int getInt(Object val) { return ((SimpleNumber) val).getAsNumber().intValue(); }
protected boolean complexType(Object value) { return value instanceof freemarker.ext.beans.BeanModel || value instanceof SimpleNumber || value instanceof SimpleSequence; }
@SuppressWarnings({ "rawtypes", "deprecation" }) @Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { if (log.isTraceEnabled()) { log.trace(params); } SimpleNumber width = (SimpleNumber) params.get("width"); SimpleNumber height = (SimpleNumber) params.get("height"); SimpleScalar uri = (SimpleScalar) params.get("uri"); SimpleScalar var = (SimpleScalar) params.get("var"); BeanModel pSource = (BeanModel) params.get("src"); TemplateBooleanModel pParent = (TemplateBooleanModel) params.get("parent"); if (pSource != null && uri != null) throw new IllegalArgumentException("The parameters 'src' and 'uri' cannot be set at the same time."); if (pSource == null && uri == null) throw new IllegalArgumentException("You must provide either a 'src' or 'uri' parameter."); Product product = null; String uriStr = null; boolean fallbackToParent = false; if (pParent != null) { fallbackToParent = pParent.getAsBoolean(); } if (pSource != null) { if (!(pSource instanceof BeanModel)) throw new IllegalArgumentException("The parameter 'src' must be of type BeanModel (Product)"); Object beanModel = ((BeanModel) pSource).getWrappedObject(); if (beanModel instanceof Product) { product = (Product) beanModel; if (product.getMainImage() != null) { uriStr = product.getMainImage().getPath(); } if (uriStr == null && product.isVariant() && fallbackToParent) { Product parent = product.getParent(); if (parent != null && parent.getMainImage() != null) { uriStr = parent.getMainImage().getPath(); } } } else { throw new IllegalArgumentException("The source-object must be of type Product"); } } if (uri != null || uriStr != null) { if (uri != null) { uriStr = uri.getAsString(); } String varStr = null; if (var != null) varStr = var.getAsString(); if (!Str.isEmpty(uriStr)) { String mediaAssetURL = catalogMediaHelper.toMediaAssetURL(uriStr, width == null ? null : width.getAsNumber().intValue(), height == null ? null : height.getAsNumber().intValue()); if (varStr != null) { env.setVariable(varStr, DefaultObjectWrapper.getDefaultInstance().wrap(mediaAssetURL)); } else { env.getOut().write(mediaAssetURL); } } } }
@Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { TemplateModel pItem = (TemplateModel) params.get("item"); SimpleScalar pVar = (SimpleScalar) params.get("var"); App app = App.get(); List<NavigationItem> navItems = app.registryGet(NavigationConstant.NAV_ITEMS); List<Id> navItemIds = app.registryGet(NavigationConstant.NAV_ITEM_IDS); boolean isActive = false; String var = null; if (pVar != null) var = pVar.getAsString(); if (pItem != null && navItems != null) { Object navItem = null; if (pItem instanceof SimpleScalar) { navItem = ((SimpleScalar) pItem).getAsString(); } else if (pItem instanceof SimpleNumber) { navItem = Id.valueOf(((SimpleNumber) pItem).getAsNumber()); } else if (pItem instanceof StringModel) { navItem = ((StringModel) pItem).getWrappedObject(); } else { navItem = DeepUnwrap.unwrap(pItem); } if (navItem instanceof String) { for (NavigationItem navigationItem : navItems) { if ((navigationItem.getLabel() != null && Str.trimEqualsIgnoreCase((String) navItem, navigationItem.getLabel().str())) || Str.trimEqualsIgnoreCase((String) navItem, navigationItem.getDisplayURI())) { isActive = true; break; } } } else if (navItem instanceof Id) { isActive = navItemIds.contains(navItem); } else if (navItem instanceof NavigationItem) { isActive = navItemIds.contains(((NavigationItem) navItem).getId()); } } if (isActive && Str.isEmpty(var)) { body.render(env.getOut()); } else { env.setVariable(var, DefaultObjectWrapper.getDefaultInstance().wrap(isActive)); } }
@SuppressWarnings("rawtypes") @Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { if (log.isTraceEnabled()) { log.trace(params); } SimpleScalar pType = (SimpleScalar) params.get("type"); TemplateModel pId = (TemplateModel) params.get("id"); SimpleScalar pVar = (SimpleScalar) params.get("var"); String type = null; String varName = null; if (pType != null) type = pType.getAsString(); if (pVar != null) varName = pVar.getAsString(); if (pId != null && !Str.isEmpty(type)) { Object beanModel = null; if (pId instanceof SimpleScalar) beanModel = ((SimpleScalar) pId).getAsString(); if (pId instanceof SimpleNumber) beanModel = ((SimpleNumber) pId).getAsNumber(); else if (pId instanceof StringModel) beanModel = ((StringModel) pId).getAsString(); else if (pId instanceof NumberModel) beanModel = ((NumberModel) pId).getAsNumber(); else if (pId instanceof BeanModel) beanModel = ((BeanModel) pId).getWrappedObject(); Id id = Id.valueOf(beanModel); Class<? extends Model> modelClass = Models.findBy(type); if (modelClass != null) { Object obj = restService.get(modelClass, id); if (obj != null) env.setVariable(Str.isEmpty(varName) ? modelClass.getSimpleName() : varName, DefaultObjectWrapper.getDefaultInstance().wrap(obj)); } } }
@SuppressWarnings("rawtypes") private static void check(String s, int max, String expected) throws TemplateModelException { FmTruncateStringMethod method = new FmTruncateStringMethod(); List list = Arrays.asList(new SimpleScalar(s), new SimpleNumber(max)); assertEquals(expected, ((SimpleScalar)method.exec(list)).getAsString()); }
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { // --------------------------------------------------------------------- // 处理参数 int countParam = 0; boolean countParamSet = false; boolean hrParam = false; Iterator paramIter = params.entrySet().iterator(); while (paramIter.hasNext()) { Map.Entry ent = (Map.Entry) paramIter.next(); String paramName = (String) ent.getKey(); TemplateModel paramValue = (TemplateModel) ent.getValue(); if (paramName.equals(PARAM_NAME_COUNT)) { if (!(paramValue instanceof TemplateNumberModel)) { throw new TemplateModelException("The \"" + PARAM_NAME_HR + "\" parameter " + "must be a number."); } countParam = ((TemplateNumberModel) paramValue).getAsNumber() .intValue(); countParamSet = true; if (countParam < 0) { throw new TemplateModelException("The \"" + PARAM_NAME_HR + "\" parameter " + "can't be negative."); } } else if (paramName.equals(PARAM_NAME_HR)) { if (!(paramValue instanceof TemplateBooleanModel)) { throw new TemplateModelException("The \"" + PARAM_NAME_HR + "\" parameter " + "must be a boolean."); } hrParam = ((TemplateBooleanModel) paramValue).getAsBoolean(); } else { throw new TemplateModelException("Unsupported parameter: " + paramName); } } if (!countParamSet) { throw new TemplateModelException("The required \"" + PARAM_NAME_COUNT + "\" paramter" + "is missing."); } if (loopVars.length > 1) { throw new TemplateModelException( "At most one loop variable is allowed."); } // Yeah, it was long and boring... // --------------------------------------------------------------------- // 真正开始处理输出内容 Writer out = env.getOut(); if (body != null) { for (int i = 0; i < countParam; i++) { // 输出 <hr> 如果 参数hr 设置为true if (hrParam && i != 0) { out.write("<hr>"); } // 设置循环变量 if (loopVars.length > 0) { loopVars[0] = new SimpleNumber(i + 1); } // 执行标签内容(same as <#nested> in FTL). body.render(env.getOut()); } } }
@SuppressWarnings("rawtypes") @Override public TemplateModel wrap(Object obj) throws TemplateModelException { if (obj == null) { return super.wrap(null); } if (obj instanceof TemplateModel) { return (TemplateModel) obj; } if (obj instanceof String) { return new SimpleScalar((String) obj); } if (obj instanceof Number) { return new SimpleNumber((Number) obj); } if (obj instanceof java.util.Date) { if(obj instanceof java.sql.Date) { return new SimpleDate((java.sql.Date) obj); } if(obj instanceof java.sql.Time) { return new SimpleDate((java.sql.Time) obj); } if(obj instanceof java.sql.Timestamp) { return new SimpleDate((java.sql.Timestamp) obj); } return new SimpleDate((java.util.Date) obj, getDefaultDateType()); } if (obj.getClass().isArray()) { obj = convertArray(obj); } if (obj instanceof Collection) { return new SimpleSequence((Collection) obj, this); } if (obj instanceof Boolean) { return obj.equals(Boolean.TRUE) ? TemplateBooleanModel.TRUE : TemplateBooleanModel.FALSE; } if (obj instanceof Iterator) { return new SimpleCollection((Iterator) obj, this); } return handleUnknownType(obj); }
@Test public void testArgumentIsNumberSuccess() throws TemplateModelException { new SimpleFreemarkerMethod().testArgumentIsNumber(new SimpleNumber(42)); }