/** * @see freemarker.template.TemplateMethodModel#exec(java.util.List) */ public Object exec(List args) throws TemplateModelException { Object result = null; if (args.size() == 1) { Object arg0 = args.get(0); if (arg0 instanceof TemplateDateModel) { result = ISO8601DateFormat.format(((TemplateDateModel)arg0).getAsDate()); } else if (arg0 instanceof TemplateScalarModel) { result = ISO8601DateFormat.parse(((TemplateScalarModel)arg0).getAsString()); } } return result != null ? result : ""; }
@Override public Object exec(List arguments) throws TemplateModelException { // You can use it as a function to prevent the time-ago ness return new TemplateDateModel() { @Override public Date getAsDate() throws TemplateModelException { return date; } @Override public int getDateType() { return TemplateDateModel.DATETIME; } }; }
/** * 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; }
public static Date getDate(String name, Map<String, TemplateModel> params) throws TemplateException { TemplateModel model = params.get(name); if (model == null) { return null; } if (model instanceof TemplateDateModel) { return ((TemplateDateModel) model).getAsDate(); } else if (model instanceof TemplateScalarModel) { DateTypeEditor editor = new DateTypeEditor(); editor.setAsText(((TemplateScalarModel) model).getAsString()); return (Date) editor.getValue(); } else { throw new MustDateException(name); } }
/** * @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; }
/** * 获取Date类型的参数值 * * @return 参数值 */ public static Date getDateParameter(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; } try { String[] pattern = new String[]{"yyyy-MM","yyyyMM","yyyy/MM", "yyyyMMdd","yyyy-MM-dd","yyyy/MM/dd", "yyyyMMddHHmmss", "yyyy-MM-dd HH:mm:ss", "yyyy/MM/dd HH:mm:ss"}; return DateUtils.parseDate(value, pattern); } catch (ParseException e) { e.printStackTrace(); return null; } } else if ((templateModel instanceof TemplateDateModel)) { return ((TemplateDateModel) templateModel).getAsDate(); } else { throw new TemplateModelException("The \"" + name + "\" parameter " + "must be a date."); } }
public LDPathMethod(RDFBackend<Node> backend) { this.ldpath = new LDPath<Node>(backend); this.backend = backend; // register custom freemarker transformers for the parser so we get the results immediately in the freemarker model ldpath.registerTransformer(Constants.NS_XSD + "string", new TemplateScalarTransformer<Node>()); ldpath.registerTransformer(Constants.NS_XSD + "decimal", new TemplateLongTransformer<Node>()); ldpath.registerTransformer(Constants.NS_XSD + "integer", new TemplateIntegerTransformer<Node>()); ldpath.registerTransformer(Constants.NS_XSD + "long", new TemplateLongTransformer<Node>()); ldpath.registerTransformer(Constants.NS_XSD + "short", new TemplateIntegerTransformer<Node>()); ldpath.registerTransformer(Constants.NS_XSD + "double", new TemplateDoubleTransformer<Node>()); ldpath.registerTransformer(Constants.NS_XSD + "float", new TemplateFloatTransformer<Node>()); ldpath.registerTransformer(Constants.NS_XSD + "dateTime", new TemplateDateTransformer<Node>(TemplateDateModel.DATETIME)); ldpath.registerTransformer(Constants.NS_XSD + "date", new TemplateDateTransformer<Node>(TemplateDateModel.DATE)); ldpath.registerTransformer(Constants.NS_XSD + "time", new TemplateDateTransformer<Node>(TemplateDateModel.TIME)); ldpath.registerTransformer(Constants.NS_XSD + "boolean", new TemplateBooleanTransformer<Node>()); ldpath.registerTransformer(Constants.NS_XSD + "anyURI", new TemplateScalarTransformer<Node>()); }
@Override public String formatToPlainText(TemplateDateModel dateModel) throws UnformattableValueException, TemplateModelException { Date date = TemplateFormatUtil.getNonNullDate(dateModel); SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss z"); return DATE_FORMAT.format(date); }
@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)); } }
/** * Transform the KiWiNode node into the datatype T. In case the node cannot be transformed to * the respective datatype, throws an IllegalArgumentException that needs to be caught by the class * carrying out the transformation. * * * * @param nodeRDFBackend * @param node * @param configuration * @return */ @Override public TemplateDateModel transform(final RDFBackend<Node> nodeRDFBackend, final Node node, final Map<String, String> configuration) throws IllegalArgumentException { return new TemplateDateModel() { @Override public Date getAsDate() throws TemplateModelException { return delegate.transform(nodeRDFBackend, node, configuration); } @Override public int getDateType() { return type; } }; }
@Override public Object exec(List arguments) throws TemplateModelException { Object argRaw = arguments.get(0); if (argRaw instanceof TemplateDateModel) { Date date = ((TemplateDateModel) argRaw).getAsDate(); return format(date); } else { LOG.warn("Single date required as input: {}", argRaw); return null; } }
/** * @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; }
@SuppressWarnings("unchecked") @Override public Object exec(List args) throws TemplateModelException { if (args == null || args.size() < 1 || args.size() > 5) throw new TemplateModelException("Invalid number of arguments"); if (!(args.get(0) instanceof TemplateDateModel)) throw new TemplateModelException("First argument is not a Date object/model"); TemplateDateModel dateModel = ((TemplateDateModel) args.get(0)); String dateTimeFormat = (args.size() > 1) ? LangFtlUtil.getAsStringNonEscaping(((TemplateScalarModel) args.get(1))) : null; TemplateModel specLocaleModel = (args.size() > 2) ? ((TemplateModel) args.get(2)) : null; TemplateModel specTimeZoneModel = (args.size() > 3) ? ((TemplateModel) args.get(3)) : null; String dateType = (args.size() > 4) ? LangFtlUtil.getAsStringNonEscaping(((TemplateScalarModel) args.get(4))) : null; Environment env = CommonFtlUtil.getCurrentEnvironment(); Date date = dateModel.getAsDate(); if (dateTimeFormat != null && dateTimeFormat.isEmpty()) { dateTimeFormat = null; } // NOTE: 2016-10-12: CANNOT pass null locale or timeZone because it causes crash. // warn when missing. Locale locale; if (specLocaleModel == null || specLocaleModel instanceof TemplateBooleanModel) { if (specLocaleModel == null || ((TemplateBooleanModel) specLocaleModel).getAsBoolean()) { locale = LangFtlUtil.getLocale(TransformUtil.getFtlContextGlobalVar("locale", env)); if (locale == null) { locale = Locale.getDefault(); Debug.logWarning("Scipio: formatDate(Time): locale empty (from context); using system default", module); } } else { locale = Locale.getDefault(); Debug.logWarning("Scipio: formatDate(Time): locale false (from caller); using system default", module); } } else { locale = LangFtlUtil.getLocale(specLocaleModel); if (locale == null) { locale = Locale.getDefault(); Debug.logWarning("Scipio: formatDate(Time): locale empty (from caller); using system default", module); } } TimeZone timeZone; if (specTimeZoneModel == null || specTimeZoneModel instanceof TemplateBooleanModel) { if (specTimeZoneModel == null || ((TemplateBooleanModel) specTimeZoneModel).getAsBoolean()) { timeZone = LangFtlUtil.getTimeZone(TransformUtil.getFtlContextGlobalVar("timeZone", env)); if (timeZone == null) { timeZone = TimeZone.getDefault(); Debug.logWarning("Scipio: formatDate(Time): timeZone empty (from context); using system default", module); } } else { timeZone = TimeZone.getDefault(); Debug.logWarning("Scipio: formatDate(Time): timeZone false (from caller); using system default", module); } } else { timeZone = LangFtlUtil.getTimeZone(specTimeZoneModel); if (timeZone == null) { timeZone = TimeZone.getDefault(); Debug.logWarning("Scipio: formatDate(Time): timeZone empty (from caller); using" + " system default", module); } } Object res; if (dateType == null || dateType.isEmpty() || "date".equals(dateType)) { // "date" is default res = UtilFormatOut.formatDate(date, dateTimeFormat, locale, timeZone); } else if ("time".equals(dateType)) { res = UtilFormatOut.formatTime(date, dateTimeFormat, locale, timeZone); } else { res = UtilFormatOut.formatDateTime(date, dateTimeFormat, locale, timeZone); } return res; }
/** * Returns a "private" copy (not in the global cache) for the given format. */ private DateFormat getJavaDateFormat(int dateType, String nameOrPattern, Locale locale, TimeZone timeZone) throws UnknownDateTypeFormattingUnsupportedException, InvalidFormatParametersException { // Get DateFormat from global cache: CacheKey cacheKey = new CacheKey(dateType, nameOrPattern, locale, timeZone); DateFormat jFormat; jFormat = GLOBAL_FORMAT_CACHE.get(cacheKey); if (jFormat == null) { // Add format to global format cache. StringTokenizer tok = new StringTokenizer(nameOrPattern, "_"); int tok1Style = tok.hasMoreTokens() ? parseDateStyleToken(tok.nextToken()) : DateFormat.DEFAULT; if (tok1Style != -1) { switch (dateType) { case TemplateDateModel.UNKNOWN: { throw new UnknownDateTypeFormattingUnsupportedException(); } case TemplateDateModel.TIME: { jFormat = DateFormat.getTimeInstance(tok1Style, cacheKey.locale); break; } case TemplateDateModel.DATE: { jFormat = DateFormat.getDateInstance(tok1Style, cacheKey.locale); break; } case TemplateDateModel.DATETIME: { int tok2Style = tok.hasMoreTokens() ? parseDateStyleToken(tok.nextToken()) : tok1Style; if (tok2Style != -1) { jFormat = DateFormat.getDateTimeInstance(tok1Style, tok2Style, cacheKey.locale); } break; } } } if (jFormat == null) { try { jFormat = new SimpleDateFormat(nameOrPattern, cacheKey.locale); } catch (IllegalArgumentException e) { final String msg = e.getMessage(); throw new InvalidFormatParametersException( msg != null ? msg : "Invalid SimpleDateFormat pattern", e); } } jFormat.setTimeZone(cacheKey.timeZone); if (GLOBAL_FORMAT_CACHE.size() >= LEAK_ALERT_NUMBER_FORMAT_CACHE_SIZE) { boolean triggered = false; synchronized (JavaTemplateDateFormatFactory.class) { if (GLOBAL_FORMAT_CACHE.size() >= LEAK_ALERT_NUMBER_FORMAT_CACHE_SIZE) { triggered = true; GLOBAL_FORMAT_CACHE.clear(); } } if (triggered) { log.warn("Global Java DateFormat cache has exceeded " + LEAK_ALERT_NUMBER_FORMAT_CACHE_SIZE + " entries => cache flushed. " + "Typical cause: Some template generates high variety of format pattern strings."); } } DateFormat prevJFormat = GLOBAL_FORMAT_CACHE.putIfAbsent(cacheKey, jFormat); if (prevJFormat != null) { jFormat = prevJFormat; } } // if cache miss return (DateFormat) jFormat.clone(); // For thread safety }
/** * Modify by WangXiaoJin */ @Override public String formatToPlainText(TemplateDateModel dateModel) throws TemplateModelException { return dateModel.getAsDate() == NullDate.INSTANCE ? Symbol.EMPTY : javaDateFormat.format(TemplateFormatUtil.getNonNullDate(dateModel)); }
public Object exec(List args) throws TemplateModelException { if (args.size() == 2) { Object arg0 = args.get(0); Object arg1 = args.get(1); Date startDate = null; Date endDate = null; if (arg0 instanceof TemplateDateModel) { startDate = (Date) ((TemplateDateModel) arg0).getAsDate(); } else if (arg0 instanceof TemplateScalarModel) { String startDateString = ((TemplateScalarModel) arg0).getAsString(); startDate = ISO8601DateFormat.parse(startDateString); } else { throw new TemplateModelException("Invalid date entry"); } if (arg1 instanceof TemplateDateModel) { endDate = (Date) ((TemplateDateModel) arg0).getAsDate(); } else if (arg1 instanceof TemplateScalarModel) { String valueString = ((TemplateScalarModel) arg1).getAsString(); try { Duration duration = new Duration(valueString); endDate = Duration.add(startDate, duration); } catch (Exception e) { endDate = ISO8601DateFormat.parse(valueString); } } else { throw new TemplateModelException("Invalid date entry"); } if (startDate.compareTo(endDate) > 0) { Date temp = startDate; startDate = endDate; endDate = temp; } StringBuilder builder = new StringBuilder(); builder.append("["); builder.append(DefaultTypeConverter.INSTANCE.convert(String.class, startDate)); builder.append(" TO "); builder.append(DefaultTypeConverter.INSTANCE.convert(String.class, endDate)); builder.append("]"); return builder.toString(); } else { throw new TemplateModelException("Invalid date entry"); } }
@Override public Object exec( @SuppressWarnings( "rawtypes" ) List arguments ) throws TemplateModelException { int argsSize = arguments.size( ); if ( argsSize < 1 ) { throw new TemplateModelException( "Must be called with at least one argument (the message key)" ); } String key = ( (TemplateScalarModel) arguments.get( 0 ) ).getAsString( ); Locale locale = Environment.getCurrentEnvironment( ).getLocale( ); if ( argsSize == 1 ) { // no arguments, the message is not a MessageFormat return getPattern( key, locale ); } Object [ ] args = new Object [ argsSize - 1]; for ( int i = 1; i < argsSize; i++ ) { TemplateModel arg = (TemplateModel) arguments.get( i ); if ( arg instanceof TemplateScalarModel ) { args [i - 1] = ( (TemplateScalarModel) arg ).getAsString( ); } else if ( arg instanceof TemplateNumberModel ) { args [i - 1] = ( (TemplateNumberModel) arg ).getAsNumber( ); } else if ( arg instanceof TemplateDateModel ) { args [i - 1] = ( (TemplateDateModel) arg ).getAsDate( ); } else { throw new TemplateModelException( "Unsupported argument type : " + arg ); } } return new MessageFormat( getPattern( key, locale ), locale ).format( args, new StringBuffer( ), null ).toString( ); }