/** * Gets string arg. * <p> * If number or date passed, will be coerced to string. Other types such as maps or lists * will throw TemplateModelException. */ public static String getStringArg(TemplateModel obj, String defaultValue, boolean useDefaultWhenEmpty, boolean nonEscaping) throws TemplateModelException { String result = null; if (obj instanceof TemplateScalarModel) { TemplateScalarModel s = (TemplateScalarModel) obj; result = LangFtlUtil.getAsString(s, nonEscaping); } else if (obj == null) { return defaultValue; } else if (obj instanceof TemplateNumberModel || obj instanceof TemplateDateModel) { // TODO: optimize this call result = LangFtlUtil.execStringBuiltIn(obj, FreeMarkerWorker.getCurrentEnvironment()).getAsString(); } else { throw new TemplateModelException("Expected string model or something coercible to string, but got a " + obj.getClass() + " instead"); } if (useDefaultWhenEmpty && result.isEmpty()) { return defaultValue; } return result; }
/** * Gets integer arg. * <p> * If string passed, will be parsed as integer. Other types such as maps or lists * will throw TemplateModelException. */ public static Integer getIntegerArg(TemplateModel obj, Integer defaultValue) throws TemplateModelException, NumberFormatException { if (obj instanceof TemplateNumberModel) { return ((TemplateNumberModel) obj).getAsNumber().intValue(); } else if (obj instanceof TemplateScalarModel) { TemplateScalarModel s = (TemplateScalarModel) obj; String strResult = LangFtlUtil.getAsString(s, true); if (strResult.isEmpty()) { return defaultValue; } else { return Integer.parseInt(strResult); } } else if (obj == null) { return defaultValue; } else { throw new TemplateModelException("Expected integer model or string representing of integer, but got a " + obj.getClass() + " instead"); } }
@Override public String formatToPlainText(TemplateNumberModel numberModel) throws UnformattableValueException, TemplateModelException { Number n = TemplateFormatUtil.getNonNullNumber(numberModel); try { String number = Integer.toHexString(NumberUtil.toIntExact(n)); if(number.length() == 1) if(NumberUtil.toIntExact(n) <= 9) number = "0"+number; else number = number + number; return number; } catch (ArithmeticException e) { throw new UnformattableValueException(n + " doesn't fit into an int"); } }
public static int getIntParam(final Environment env,Map params,String key,int def) throws TemplateException { final TemplateModel tv = (TemplateModel)params.get(key); if(tv == null) { return def; } if(!(tv instanceof TemplateNumberModel)) { throw new TemplateException( String.format("Expected a number model. '%s' is instead %s", key,tv.getClass().getName()) , env); } return ((TemplateNumberModel)tv).getAsNumber().intValue(); }
public static Long getLong(String name, Map<String, TemplateModel> params) throws TemplateException { TemplateModel model = params.get(name); if (model == null) { return null; } if (model instanceof TemplateScalarModel) { String s = ((TemplateScalarModel) model).getAsString(); if (StringUtils.isBlank(s)) { return null; } try { return Long.parseLong(s); } catch (NumberFormatException e) { throw new MustNumberException(name); } } else if (model instanceof TemplateNumberModel) { return ((TemplateNumberModel) model).getAsNumber().longValue(); } else { throw new MustNumberException(name); } }
public static Integer getInt(String name, Map<String, TemplateModel> params) throws TemplateException { TemplateModel model = params.get(name); if (model == null) { return null; } if (model instanceof TemplateScalarModel) { String s = ((TemplateScalarModel) model).getAsString(); if (StringUtils.isBlank(s)) { return null; } try { return Integer.parseInt(s); } catch (NumberFormatException e) { throw new MustNumberException(name); } } else if (model instanceof TemplateNumberModel) { return ((TemplateNumberModel) model).getAsNumber().intValue(); } else { throw new MustNumberException(name); } }
public static Boolean getBool(String name, Map<String, TemplateModel> params) throws TemplateException { TemplateModel model = params.get(name); if (model == null) { return null; } if (model instanceof TemplateBooleanModel) { return ((TemplateBooleanModel) model).getAsBoolean(); } else if (model instanceof TemplateNumberModel) { return !(((TemplateNumberModel) model).getAsNumber().intValue() == 0); } else if (model instanceof TemplateScalarModel) { String s = ((TemplateScalarModel) model).getAsString(); // 空串应该返回null还是true呢? if (!StringUtils.isBlank(s)) { return !(s.equals("0") || s.equalsIgnoreCase("false") || s .equalsIgnoreCase("f")); } else { return null; } } else { throw new MustBooleanException(name); } }
@SuppressWarnings("unchecked") public Object exec(List args) throws TemplateModelException { if (args == null || args.size() != 2) throw new TemplateModelException("Invalid number of arguements"); if (!(args.get(0) instanceof TemplateScalarModel)) throw new TemplateModelException("First argument not an instance of TemplateScalarModel"); if (!(args.get(1) instanceof BeanModel) && !(args.get(1) instanceof TemplateNumberModel) && !(args.get(1) instanceof TemplateScalarModel)) throw new TemplateModelException("Second argument not an instance of BeanModel nor TemplateNumberModel nor TemplateScalarModel"); Environment env = Environment.getCurrentEnvironment(); BeanModel req = (BeanModel)env.getVariable("request"); HttpServletRequest request = (HttpServletRequest) req.getWrappedObject(); String name = ((TemplateScalarModel) args.get(0)).getAsString(); Object value = null; if (args.get(1) instanceof TemplateScalarModel) value = ((TemplateScalarModel) args.get(1)).getAsString(); if (args.get(1) instanceof TemplateNumberModel) value = ((TemplateNumberModel) args.get(1)).getAsNumber(); if (args.get(1) instanceof BeanModel) value = ((BeanModel) args.get(1)).getWrappedObject(); request.setAttribute(name, value); return new SimpleScalar(""); }
/** * @see freemarker.template.TemplateMethodModel#exec(java.util.List) */ public Object exec(List args) throws TemplateModelException { Date result = null; if (args.size() == 2) { Object arg0 = args.get(0); Object arg1 = args.get(1); if (arg0 instanceof TemplateDateModel && arg1 instanceof TemplateNumberModel) { Date origionalDate = (Date)((TemplateDateModel)arg0).getAsDate(); Number number = ((TemplateNumberModel)arg1).getAsNumber(); long increment = number.longValue(); long modified = origionalDate.getTime() + increment; result = new Date(modified); } } return result; }
/** * 获取Integer类型的参数值 * * @return 参数值 */ public static Integer getIntegerParameter(String name, Map<String, TemplateModel> params) throws TemplateModelException { TemplateModel templateModel = params.get(name); if (templateModel == null) { return null; } if (templateModel instanceof TemplateScalarModel) { String value = ((TemplateScalarModel) templateModel).getAsString(); if (StringUtils.isEmpty(value)) { return null; } else { return Integer.parseInt(value); } } else if ((templateModel instanceof TemplateNumberModel)) { return ((TemplateNumberModel) templateModel).getAsNumber().intValue(); } else { throw new TemplateModelException("The \"" + name + "\" parameter " + "must be a integer."); } }
/** * @see freemarker.template.TemplateMethodModel#exec(java.util.List) */ public Object exec(List args) throws TemplateModelException { String result = null; if (args.size() == 2) { Object arg0 = args.get(0); Object arg1 = args.get(1); if (arg0 instanceof BeanModel && arg1 instanceof TemplateNumberModel) { Object wrapped = ((BeanModel)arg0).getWrappedObject(); if (wrapped instanceof TemplateContentData) { int bytes = ((TemplateNumberModel)arg1).getAsNumber().intValue(); try { result = ((TemplateContentData)wrapped).getContentAsText(bytes); } catch (ContentIOException e) { logger.warn("unable to getContentAsText", e); /* * Unable to extract content - return empty text instead. * Probably here through a transformation failure. * This method is called from FreeMarker so throwing the * exception causes problems. */ result = ""; } } } } return result != null ? result : ""; }
private Object convertToJava(Object paramVal) throws TemplateModelException { if( paramVal instanceof TemplateNumberModel ) { return ((TemplateNumberModel) paramVal).getAsNumber(); } return paramVal.toString(); }
@Test public void formattingCzech() throws TemplateValueFormatException, TemplateModelException { final BigDecimal n = new BigDecimal("0.0001"); final TemplateNumberFormat f = InterestNumberFormatFactory.INSTANCE.get("", Defaults.LOCALE, Environment.getCurrentEnvironment()); final TemplateNumberModel m = () -> n; final String result = f.formatToPlainText(m); Assertions.assertThat(result.trim()).isEqualTo("0,01" + (char) 160 + "%"); }
@Test public void formattingCzech2() throws TemplateValueFormatException, TemplateModelException { final BigDecimal n = new BigDecimal("0.0000"); final TemplateNumberFormat f = InterestNumberFormatFactory.INSTANCE.get("", Defaults.LOCALE, Environment.getCurrentEnvironment()); final TemplateNumberModel m = () -> n; final String result = f.formatToPlainText(m); Assertions.assertThat(result.trim()).isEqualTo("0" + (char) 160 + "%"); }
@Test public void formattingCzech3() throws TemplateValueFormatException, TemplateModelException { final BigDecimal n = new BigDecimal("0.001"); final TemplateNumberFormat f = InterestNumberFormatFactory.INSTANCE.get("", Defaults.LOCALE, Environment.getCurrentEnvironment()); final TemplateNumberModel m = () -> n; final String result = f.formatToPlainText(m); Assertions.assertThat(result.trim()).isEqualTo("0,1" + (char) 160 + "%"); }
@Test public void formattingEnglish() throws TemplateValueFormatException, TemplateModelException { final BigDecimal n = new BigDecimal("0.0001"); final TemplateNumberFormat f = InterestNumberFormatFactory.INSTANCE.get("", Locale.ENGLISH, Environment.getCurrentEnvironment()); final TemplateNumberModel m = () -> n; final Object result = f.formatToPlainText(m); Assertions.assertThat(result).isEqualTo("0.01%"); }
@Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { SimpleScalar name = (SimpleScalar) params.get("name"); if (params.containsKey("value")) { Object valueObject = params.get("value"); Object value; if (valueObject == null) { value = null; } else if (valueObject instanceof WrapperTemplateModel) { value = ((WrapperTemplateModel) valueObject).getWrappedObject(); } else if (valueObject instanceof TemplateScalarModel) { value = ((TemplateScalarModel) valueObject).getAsString(); } else if (valueObject instanceof TemplateNumberModel) { value = ((TemplateNumberModel) valueObject).getAsNumber(); } else if (valueObject instanceof TemplateDateModel) { value = ((TemplateDateModel) valueObject).getAsDate(); } else if (valueObject instanceof TemplateBooleanModel) { value = ((TemplateBooleanModel) valueObject).getAsBoolean(); } else { throw new UnsupportedOperationException( String.format("Type %s is not supported yet in this context.", valueObject.getClass().getSimpleName())); } TemplateModel generatedParamsObject = env.getGlobalVariables().get(FreeMarkerSqlSource.GENERATED_PARAMS_KEY); List generatedParams; if (generatedParamsObject instanceof DefaultListAdapter) { generatedParams = (List) ((DefaultListAdapter) generatedParamsObject).getWrappedObject(); } else { generatedParams = ((GeneratedParamsTemplateModel) generatedParamsObject).getGeneratedParams(); } String generatedParamName = "_p" + generatedParams.size(); env.getOut().write(String.format("#{%s}", generatedParamName)); generatedParams.add(value); } else { env.getOut().write(String.format("#{%s}", name)); } }
public static int getParameterByInt(Map<?, ?> params, String name, int def){ TemplateModel attr = getParameter(params, name, false); if(attr!=null){ try { if(TemplateNumberModel.class.isInstance(attr)){ return ((TemplateNumberModel)attr).getAsNumber().intValue(); }else{ return Integer.parseInt(attr.toString()); } } catch (Exception e) { return def; } } return def; }
private long getStartTime(Environment env) throws TemplateModelException { TemplateModel startTime = env.getGlobalVariable(START_TIME); if (startTime == null) { log.warn("Variable '{}' not found in GlobalVariable", START_TIME); return -1; } if (startTime instanceof TemplateNumberModel) { return ((TemplateNumberModel) startTime).getAsNumber().longValue(); } else { throw new MustNumberException(START_TIME); } }
public static String getString(String name, Map<String, TemplateModel> params) throws TemplateException { TemplateModel model = params.get(name); if (model == null) { return null; } if (model instanceof TemplateScalarModel) { return ((TemplateScalarModel) model).getAsString(); } else if ((model instanceof TemplateNumberModel)) { return ((TemplateNumberModel) model).getAsNumber().toString(); } else { throw new MustStringException(name); } }
/** * 标签中获得页码 * * @param env * @return * @throws TemplateException */ public static int getPageNo(Environment env) throws TemplateException { TemplateModel pageNo = env.getGlobalVariable(PAGE_NO); if (pageNo instanceof TemplateNumberModel) { return ((TemplateNumberModel) pageNo).getAsNumber().intValue(); } else { throw new TemplateModelException("'" + PAGE_NO + "' not found in DataModel."); } }
/** * 获取String类型的参数值 * * @return 参数值 */ public static String getStringParameter(String name, Map<String, TemplateModel> params) throws TemplateModelException { TemplateModel templateModel = params.get(name); if (templateModel == null) { return null; } if (templateModel instanceof TemplateScalarModel) { return ((TemplateScalarModel) templateModel).getAsString(); } else if ((templateModel instanceof TemplateNumberModel)) { return ((TemplateNumberModel) templateModel).getAsNumber().toString(); } else { throw new TemplateModelException("The \"" + name + "\" parameter " + "must be a string."); } }
@Override public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException { if (arguments.size() != 1) { throw new TemplateModelException("Wrong arguments, expected single millisSinceEpoch"); } TemplateNumberModel tnm = (TemplateNumberModel) arguments.get(0); if (tnm == null) { return null; } Long millisSinceEpoch = tnm.getAsNumber().longValue(); DateTime date = new DateTime(millisSinceEpoch, TZ); return date.toString(DATE_PATTERN); }
@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()); }
/** * @see freemarker.template.TemplateMethodModel#exec(java.util.List) */ public Object exec(List args) throws TemplateModelException { String result = ""; int argSize = args.size(); if (argSize != 0) { String id = ""; Object arg0 = args.get(0); if (arg0 instanceof TemplateScalarModel) { id = ((TemplateScalarModel)arg0).getAsString(); } if (id != null) { if (argSize == 1) { // shortcut for no additional msg params result = I18NUtil.getMessage(id); } else { Object[] params = new Object[argSize - 1]; for (int i = 0; i < argSize-1; i++) { // ignore first passed-in arg which is the msg id Object arg = args.get(i + 1); if (arg instanceof TemplateScalarModel) { params[i] = ((TemplateScalarModel)arg).getAsString(); } else if (arg instanceof TemplateNumberModel) { params[i] = ((TemplateNumberModel)arg).getAsNumber(); } else if (arg instanceof TemplateDateModel) { params[i] = ((TemplateDateModel)arg).getAsDate(); } else { params[i] = ""; } } result = I18NUtil.getMessage(id, params); } } } return result; }
@Override public String formatToPlainText(final TemplateNumberModel numberModel) throws UnformattableValueException, TemplateModelException { return format.format(TemplateFormatUtil.getNonNullNumber(numberModel)); }