Java 类freemarker.template.SimpleScalar 实例源码

项目:Equella    文件:ButtonListDirective.java   
@Override
@SuppressWarnings("nls")
protected TagRenderer createTagRenderer(HtmlMutableListState state, Environment env, Map<?, ?> params,
    TemplateDirectiveBody body, TemplateModel[] loopVars) throws TemplateModelException
{
    String tag = "div";
    if( params.containsKey("tag") )
    {
        tag = ((SimpleScalar) params.get("tag")).getAsString();
    }

    boolean hideDisabledOptions = false;
    if( params.containsKey("hideDisabledOptions") )
    {
        hideDisabledOptions = ((TemplateBooleanModel) params.get("hideDisabledOptions")).getAsBoolean();
    }

    return new ButtonListTagRenderer(tag, (HtmlListState) state, env, body, loopVars, hideDisabledOptions);
}
项目:requirementsascode    文件:UserPartOfStep.java   
@SuppressWarnings("rawtypes")
@Override
public Object exec(List arguments) throws TemplateModelException {
  if (arguments.size() != 1) {
    throw new TemplateModelException("Wrong number of arguments. Must be 1.");
  }

  String userPartOfStep = "";
  Step step = getStepFromFreemarker(arguments.get(0));
  if (hasUser(step)) {
    String userActorName = getUserActor(step).getName();
    String wordsOfUserEventClassName = getLowerCaseWordsOfClassName(step.getUserEventClass());
    userPartOfStep = userActorName + " " + wordsOfUserEventClassName + USER_POSTFIX;
  }

  return new SimpleScalar(userPartOfStep);
}
项目:requirementsascode    文件:ReactWhileOfStep.java   
@SuppressWarnings("rawtypes")
@Override
public Object exec(List arguments) throws TemplateModelException {
  if (arguments.size() != 1) {
    throw new TemplateModelException("Wrong number of arguments. Must be 1.");
  }

  Step step = getStep(arguments.get(0));

  String reactWhile = "";
  if (step.getPredicate() instanceof ReactWhile) {
    ReactWhile reactWhilePredicate = (ReactWhile) step.getPredicate();
    reactWhile = REACT_WHILE_PREFIX
        + getLowerCaseWordsOfClassName(getReactWhileConditionClass(reactWhilePredicate)) + REACT_WHILE_POSTFIX;
  }

  return new SimpleScalar(reactWhile);
}
项目:scipio-erp    文件:FreeMarkerWorker.java   
/**
* Gets BeanModel from FreeMarker context and returns the object that it wraps.
* @param varName the name of the variable in the FreeMarker context.
* @param env the FreeMarker Environment
*/
public static <T> T getWrappedObject(String varName, Environment env) {
    Object obj = null;
    try {
        obj = env.getVariable(varName);
        if (obj != null) {
            if (obj == TemplateModel.NOTHING) {
                obj = null;
            } else if (obj instanceof BeanModel) {
                BeanModel bean = (BeanModel) obj;
                obj = bean.getWrappedObject();
            } else if (obj instanceof SimpleScalar) {
                obj = obj.toString();
            }
        }
    } catch (TemplateModelException e) {
        Debug.logInfo(e.getMessage(), module);
    }
    return UtilGenerics.<T>cast(obj);
}
项目:scipio-erp    文件:OfbizCurrencyTransform.java   
@SuppressWarnings("unchecked")
private static BigDecimal getAmount(Map args, String key) {
    if (args.containsKey(key)) {
        Object o = args.get(key);

        // handle nulls better
        if (o == null) {
            o = 0.00;
        }
        if (Debug.verboseOn()) Debug.logVerbose("Amount Object : " + o.getClass().getName(), module);

        if (o instanceof SimpleScalar) {
            SimpleScalar s = (SimpleScalar) o;
            // SCIPIO: This needs to bypass auto-escaping
            //return new BigDecimal(s.getAsString());
            try {
                return new BigDecimal(LangFtlUtil.getAsStringNonEscaping(s));
            } catch (TemplateModelException e) {
                Debug.logError(e, "Template Exception", module);
            }
        }
        return new BigDecimal(o.toString());
    }
    return BigDecimal.ZERO;
}
项目:scipio-erp    文件:RequestStackMethod.java   
@SuppressWarnings("unchecked")
protected Object execPush(List args, boolean setLast) throws TemplateModelException {
    if (args == null || args.size() != 2) {
        throw new TemplateModelException("Invalid number of arguments (expected: 2)");
    }
    TemplateModel nameModel = (TemplateModel) args.get(0);
    if (!(nameModel instanceof TemplateScalarModel)) {
        throw new TemplateModelException("First argument not an instance of TemplateScalarModel (string)");
    }
    TemplateModel valueModel = (TemplateModel) args.get(1);

    Environment env = CommonFtlUtil.getCurrentEnvironment();
    ContextFtlUtil.pushRequestStack(LangFtlUtil.getAsStringNonEscaping(((TemplateScalarModel) nameModel)), valueModel, setLast, env);

    return new SimpleScalar("");
}
项目:my-paper    文件:AbbreviateMethod.java   
@SuppressWarnings("rawtypes")
public Object exec(List arguments) throws TemplateModelException {
    if (arguments != null && !arguments.isEmpty() && arguments.get(0) != null && StringUtils.isNotEmpty(arguments.get(0).toString())) {
        Integer width = null;
        String ellipsis = null;
        if (arguments.size() == 2) {
            if (arguments.get(1) != null) {
                width = Integer.valueOf(arguments.get(1).toString());
            }
        } else if (arguments.size() > 2) {
            if (arguments.get(1) != null) {
                width = Integer.valueOf(arguments.get(1).toString());
            }
            if (arguments.get(2) != null) {
                ellipsis = arguments.get(2).toString();
            }
        }
        return new SimpleScalar(abbreviate(arguments.get(0).toString(), width, ellipsis));
    }
    return null;
}
项目:geeCommerce-Java-Shop-Software-and-PIM    文件:FetchRetailStoresDirective.java   
@SuppressWarnings("rawtypes")
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
    throws TemplateException, IOException {
    SimpleScalar pVar = (SimpleScalar) params.get("var");

    List<RetailStore> retailStoreList = retailStores.enabledRetailStores();

    if (pVar != null) {
        // Sets the result into the current template as if using <#assign
        // name=model>.
        env.setVariable(pVar.getAsString(), DefaultObjectWrapper.getDefaultInstance().wrap(retailStoreList));
    } else {
        // Sets the result into the current template as if using <#assign
        // name=model>.
        env.setVariable("retailStores", DefaultObjectWrapper.getDefaultInstance().wrap(retailStoreList));
    }
}
项目:aspectran    文件:AbstractTrimDirectiveModel.java   
/**
 * Transform simple sequence as string list.
 *
 * @param sequence the sequence
 * @param paramName the param name
 * @return the list
 * @throws TemplateModelException the template model exception
 */
private List<String> transformSimpleSequenceAsStringList(SimpleSequence sequence, String paramName)
        throws TemplateModelException {
    List<String> list = new ArrayList<>();
    int size = sequence.size();

    for (int i = 0; i < size; i++) {
        TemplateModel model = sequence.get(i);

        if (!(model instanceof SimpleScalar)) {
            throw new IllegalArgumentException(paramName + "'s item must be string");
        }

        list.add(((SimpleScalar)model).getAsString());
    }

    return list;
}
项目:goja    文件:ExtendsDirective.java   
@SuppressWarnings("rawtypes")
@Override
public void execute(Environment env, Map params,
                    TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
    String name = DirectiveKit.getRequiredParam(params, "name");
    params.remove("name");

    if (!name.endsWith(".ftl")) {
        name = name + ".ftl";
    }
    String encoding = DirectiveKit.getParam(params, "encoding", StringPool.UTF_8);
    String includeTemplateName = TemplateCache.getFullTemplatePath(env, getTemplatePath(env), name);
    Configuration configuration = env.getConfiguration();
    final Template template = configuration.getTemplate(includeTemplateName, env.getLocale(), encoding, true);
    for (Object key : params.keySet()) {
        TemplateModel paramModule = new SimpleScalar(params.get(key).toString());
        env.setVariable(key.toString(), paramModule);
    }
    env.include(template);
}
项目:mangooio    文件:RouteMethod.java   
@Override
public TemplateModel exec(List arguments) throws TemplateModelException {
    String url;
    if (arguments.size() >= MIN_ARGUMENTS) {
        String controller = ((SimpleScalar) arguments.get(0)).getAsString();
        Route route = Router.getReverseRoute(controller);
        if (route != null) {
            url = route.getUrl();
            Matcher matcher = PARAMETER_PATTERN.matcher(url);
            int i = 1;
            while (matcher.find()) {
                String argument = ((SimpleScalar) arguments.get(i)).getAsString();
                url = StringUtils.replace(url, "{" + matcher.group(1) + "}", argument);
                i++;
            }
        } else {
            throw new TemplateModelException("Reverse route for " + controller + " could not be found!");
        }
    } else {
        throw new TemplateModelException("Missing at least one argument (ControllerClass:ControllerMethod) for reverse routing!");
    }

    return new SimpleScalar(url);
}
项目:jspresso-ce    文件:CompactString.java   
/**
 * Compacts an input string.
 * <p>
 * {@inheritDoc}
 */
@Override
public TemplateModel exec(List arguments)
    throws TemplateModelException {
  try {
    String toCompact = ((TemplateScalarModel) arguments.get(0)).getAsString();
    if (toCompact == null || toCompact.length() == 0) {
      return new SimpleScalar("");
    }
    StringBuilder result = new StringBuilder();
    result.append(Character.toUpperCase(toCompact.charAt(0)));
    for (int i = 1; i < toCompact.length(); i++) {
      char prev = toCompact.charAt(i - 1);
      char curr = toCompact.charAt(i);
      if ((Character.isUpperCase(curr) && Character.isLowerCase(prev))
          || prev == UNDERSCORE) {
        result.append(Character.toUpperCase(curr));
      }
    }
    return new SimpleScalar(result.toString());
  } catch (Exception ex) {
    throw new TemplateModelException("Could execute compactString method.",
        ex);
  }
}
项目:jspresso-ce    文件:GenerateSqlName.java   
/**
 * Infer a SQL column name from a property name. By default: - use camel
 * parser to separate words with "_" - check for sql reserved key words
 * {@inheritDoc}
 */
@SuppressWarnings("rawtypes")
@Override
public TemplateModel exec(List arguments) throws TemplateModelException {

  String root = arguments.get(0).toString();
  String suffix = null;
  if (arguments.size() > 1 && arguments.get(1) != null) {
    suffix = arguments.get(1).toString();
  }

  String sqlColumnName = new SqlHelper(formatter, keyWordProvider).transformToSql(root, suffix);
  try {
    return new SimpleScalar(sqlColumnName);
  } catch (Exception ex) {
    throw new TemplateModelException("Could not infer SQL column name.", ex);
  }
}
项目:elpi    文件:FreeMarkerWorker.java   
/**
* Gets BeanModel from FreeMarker context and returns the object that it wraps.
* @param varName the name of the variable in the FreeMarker context.
* @param env the FreeMarker Environment
*/
public static <T> T getWrappedObject(String varName, Environment env) {
    Object obj = null;
    try {
        obj = env.getVariable(varName);
        if (obj != null) {
            if (obj == TemplateModel.NOTHING) {
                obj = null;
            } else if (obj instanceof BeanModel) {
                BeanModel bean = (BeanModel) obj;
                obj = bean.getWrappedObject();
            } else if (obj instanceof SimpleScalar) {
                obj = obj.toString();
            }
        }
    } catch (TemplateModelException e) {
        Debug.logInfo(e.getMessage(), module);
    }
    return UtilGenerics.<T>cast(obj);
}
项目:elpi    文件:OfbizCurrencyTransform.java   
@SuppressWarnings("unchecked")
private static BigDecimal getAmount(Map args, String key) {
    if (args.containsKey(key)) {
        Object o = args.get(key);

        // handle nulls better
        if (o == null) {
            o = 0.00;
        }
        if (Debug.verboseOn()) Debug.logVerbose("Amount Object : " + o.getClass().getName(), module);

        if (o instanceof SimpleScalar) {
            SimpleScalar s = (SimpleScalar) o;
            return new BigDecimal(s.getAsString());
        }
        return new BigDecimal(o.toString());
    }
    return BigDecimal.ZERO;
}
项目:elpi    文件:SetRequestAttributeMethod.java   
@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("");
}
项目:elpi    文件:JpCacheIncludeTransform.java   
public long getExpireTime(Map args) {
    Object o = args.get("expireTime");
    Debug.logInfo("ExpireTime Object - " + o, module);
    long expireTime = 0;
    if (o != null) {
        if (o instanceof SimpleScalar) {
            SimpleScalar s = (SimpleScalar) o;
            String ets = s.getAsString();
            Debug.logInfo("ExpireTime String - " + ets, module);
            try {
                expireTime = Long.parseLong(ets);
            } catch (Exception e) {
                Debug.logError(e, module);
            }
        }
    }
    return expireTime;
}
项目:siddhi    文件:FormatDescriptionMethod.java   
@Override
public Object exec(List args) throws TemplateModelException {
    if (args.size() != 1) {
        throw new TemplateModelException("There should be a single argument of type string " +
                "passed to format description method");
    }

    SimpleScalar arg1 = (SimpleScalar) args.get(0);
    String inputString = arg1.getAsString();

    // Replacing spaces that should not be considered in text wrapping with non breaking spaces
    inputString = replaceLeadingSpaces(inputString);

    inputString = inputString.replaceAll("<", "&lt;");
    inputString = inputString.replaceAll(">", "&gt;");

    // Replacing new line characters
    inputString = replaceNewLines(inputString);

    inputString = inputString.replaceAll("\t", "&nbsp;&nbsp;&nbsp;&nbsp;");
    inputString = inputString.replaceAll("```([^```]*)```", "<pre>$1</pre>");
    inputString = inputString.replaceAll("`([^`]*)`", "<code>$1</code>");

    return inputString;
}
项目:o3erp    文件:FreeMarkerWorker.java   
/**
* Gets BeanModel from FreeMarker context and returns the object that it wraps.
* @param varName the name of the variable in the FreeMarker context.
* @param env the FreeMarker Environment
*/
public static <T> T getWrappedObject(String varName, Environment env) {
    Object obj = null;
    try {
        obj = env.getVariable(varName);
        if (obj != null) {
            if (obj == TemplateModel.NOTHING) {
                obj = null;
            } else if (obj instanceof BeanModel) {
                BeanModel bean = (BeanModel) obj;
                obj = bean.getWrappedObject();
            } else if (obj instanceof SimpleScalar) {
                obj = obj.toString();
            }
        }
    } catch (TemplateModelException e) {
        Debug.logInfo(e.getMessage(), module);
    }
    return UtilGenerics.<T>cast(obj);
}
项目:o3erp    文件:OfbizCurrencyTransform.java   
@SuppressWarnings("unchecked")
private static BigDecimal getAmount(Map args, String key) {
    if (args.containsKey(key)) {
        Object o = args.get(key);

        // handle nulls better
        if (o == null) {
            o = 0.00;
        }
        if (Debug.verboseOn()) Debug.logVerbose("Amount Object : " + o.getClass().getName(), module);

        if (o instanceof SimpleScalar) {
            SimpleScalar s = (SimpleScalar) o;
            return new BigDecimal(s.getAsString());
        }
        return new BigDecimal(o.toString());
    }
    return BigDecimal.ZERO;
}
项目:o3erp    文件:SetRequestAttributeMethod.java   
@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("");
}
项目:o3erp    文件:JpCacheIncludeTransform.java   
public long getExpireTime(Map args) {
    Object o = args.get("expireTime");
    Debug.logInfo("ExpireTime Object - " + o, module);
    long expireTime = 0;
    if (o != null) {
        if (o instanceof SimpleScalar) {
            SimpleScalar s = (SimpleScalar) o;
            String ets = s.getAsString();
            Debug.logInfo("ExpireTime String - " + ets, module);
            try {
                expireTime = Long.parseLong(ets);
            } catch (Exception e) {
                Debug.logError(e, module);
            }
        }
    }
    return expireTime;
}
项目:pippo    文件:ClasspathResourceMethod.java   
@Override
public TemplateModel exec(List args) throws TemplateModelException {
    if (urlPattern.get() == null) {
        String pattern = router.uriPatternFor(resourceHandlerClass);
        if (pattern == null) {
            throw new PippoRuntimeException("You must register a route for {}",
                    resourceHandlerClass.getSimpleName());
        }

        urlPattern.set(pattern);
    }

    String path = args.get(0).toString();
    Map<String, Object> parameters = new HashMap<>();
    parameters.put(ClasspathResourceHandler.PATH_PARAMETER, path);
    String url = router.uriFor(urlPattern.get(), parameters);
    return new SimpleScalar(url);
}
项目:appleframework    文件:DatetimeDirective.java   
@SuppressWarnings({ "rawtypes" })
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {      
    DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    DateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    SimpleScalar source = (SimpleScalar)params.get("source");
    String dateTimeStr = source.toString();
    int dateTimeLength = dateTimeStr.length();
    if(dateTimeLength >= 14) {
        dateTimeStr = dateTimeStr.substring(0, 14);
    }
    Date date = null;
    try {
        date = dateFormat.parse(dateTimeStr);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    setLocalVariable(VARIABLE_NAME, dateFormat2.format(date), env, body);
}
项目:easydao    文件:LocalisedMessages.java   
@Override
public Object exec(List arguments) throws TemplateModelException {

    if (arguments.size() < 1) {
        throw new TemplateModelException("Wrong number of arguments");
    }
    String key = ((SimpleScalar) arguments.get(0)).getAsString();
    if (key == null || key.isEmpty()) {
        throw new TemplateModelException("Invalid key value '" + key + "'");
    }

    Object[] argsAll = arguments.toArray();
    Object[] args = Arrays.copyOfRange(argsAll, 1, argsAll.length);

    return this.getMessage(key, args);
}
项目:hazelcast-simulator    文件:ConfigFileTemplate.java   
@Override
public Object exec(List list) throws TemplateModelException {
    if (list.size() == 0) {
        return registry.getAgents();
    } else if (list.size() == 1) {
        Object arg = list.get(0);
        if (!(arg instanceof SimpleScalar)) {
            throw new TemplateModelException("Wrong type of the first parameter."
                    + " It should be SimpleScalar . Found: " + arg.getClass());
        }

        Map<String, String> tags = TagUtils.parseTags(((SimpleScalar) arg).getAsString());
        List<AgentData> result = new ArrayList<AgentData>();
        for (AgentData agent : registry.getAgents()) {
            if (TagUtils.matches(tags, agent.getTags())) {
                result.add(agent);
            }
        }
        return result;
    } else {
        throw new TemplateModelException("Wrong number of arguments for method agents()."
                + " Method has zero a 1 String argument, found " + list.size());
    }
}
项目:windup    文件:RenderLinkDirective.java   
private LayoutType resolveLayoutType(Map params) throws TemplateException
{
    LayoutType layoutType = LayoutType.HORIZONTAL;
    SimpleScalar layoutModel = (SimpleScalar) params.get("layout");
    if (layoutModel != null)
    {
        String lt = layoutModel.getAsString();
        try
        {
            layoutType = LayoutType.valueOf(lt.toUpperCase());
        }
        catch (IllegalArgumentException e)
        {
            throw new TemplateException("Layout: " + lt + " is not supported.", e, null);
        }
    }
    return layoutType;
}
项目:windup    文件:FindSourceFilesByClassNameMethod.java   
@Override
public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException
{
    if (arguments.size() != 1)
    {
        throw new TemplateModelException("Error, method expects one argument (String)");
    }
    SimpleScalar arg = (SimpleScalar) arguments.get(0);
    String qualifedClassName = arg.getAsString();
    JavaClassModel classModel = javaClassService.getByName(qualifedClassName);
    List<AbstractJavaSourceModel> results = new ArrayList<>();
    if (classModel instanceof AmbiguousJavaClassModel)
    {
        AmbiguousJavaClassModel ambiguousJavaClassModel = (AmbiguousJavaClassModel) classModel;
        for (JavaClassModel referencedClass : ambiguousJavaClassModel.getReferences())
        {
            addSourceFilesToResult(results, referencedClass);
        }
    }
    else
    {
        addSourceFilesToResult(results, classModel);
    }
    return results;
}
项目:redpipe    文件:RouterFunction.java   
@Override
public Object exec(List arguments) throws TemplateModelException {
    if(arguments == null || arguments.size() < 1)
        throw new TemplateModelException("Syntax: route('Class.method', arg1, arg2…)");
    Object arg0 = arguments.get(0);
    if(arg0 instanceof SimpleScalar != true)
        throw new TemplateModelException("Syntax: route('Class.method', arg1, arg2…)");
    String arg1 = ((SimpleScalar)arg0).getAsString();
    int dot = arg1.indexOf('.');
    if(dot == -1)
        throw new TemplateModelException("Syntax: route('Class.method', arg1, arg2…)");
    String klass = arg1.substring(0, dot);
    String method = arg1.substring(dot+1);

    for (Class resource : AppGlobals.get().getDeployment().getActualResourceClasses()) {
        dot = resource.getName().lastIndexOf('.');
        String shortName = dot == -1 ? resource.getName() : resource.getName().substring(dot+1);
        if(shortName.equals(klass)) {
            for (Method m : resource.getMethods()) {
                // FIXME: overloading?
                if(m.getName().equals(method)
                        && Modifier.isPublic(m.getModifiers())) {
                    UriInfo uriInfo = ResteasyProviderFactory.getContextData(UriInfo.class);
                    UriBuilder builder = uriInfo.getBaseUriBuilder().path(resource);
                    if(m.isAnnotationPresent(Path.class))
                        builder.path(m);
                    Object[] params = arguments.subList(1, arguments.size()).toArray();
                    return builder.build(params).toString();
                }
            }
            throw new TemplateModelException("Could not find method named "+method+" in resource class "+resource.getName());
        }
    }
    throw new TemplateModelException("Could not find resource class named "+klass);
}
项目:Equella    文件:RowMethod.java   
@SuppressWarnings("unchecked")
@Override
public Object exec(List list) throws TemplateModelException
{
    try
    {
        int cols = getInt(list.get(0));
        int current = getInt(list.get(1));
        int total = getInt(list.get(2));
        String nested = ((SimpleScalar) list.get(3)).getAsString();
        boolean last = (current == total - 1);
        int colspan = 1; // implement this if you need it...

        StringBuilder results = new StringBuilder();
        if( current % cols == 0 )
        {
            results.append("<tr>"); //$NON-NLS-1$
        }
        results.append(nested);
        int columnsDone = (current + colspan) % cols;
        if( last && columnsDone != 0 )
        {
            results.append("<td colspan=\""); //$NON-NLS-1$
            results.append(cols - columnsDone);
            results.append("\">&nbsp;</td>"); //$NON-NLS-1$
        }
        if( last || (current + colspan) % cols == 0 )
        {
            results.append("</tr>"); //$NON-NLS-1$
        }
        return results.toString();
    }
    catch( Exception e )
    {
        throw new TemplateModelException(e);
    }
}
项目:Equella    文件:UserFormatMethod.java   
@SuppressWarnings("unchecked")
@Override
public Object exec(List args) throws TemplateModelException
{
    UserBean user = null;
    Object userModel = args.get(0);
    if( userModel instanceof AdapterTemplateModel )
    {
        Object wrapped = ((AdapterTemplateModel) userModel).getAdaptedObject(Object.class);
        if( wrapped instanceof UserBean )
        {
            user = (UserBean) wrapped;
        }
    }
    if( user == null && userModel instanceof TemplateScalarModel )
    {
        String userId = ((TemplateScalarModel) userModel).getAsString();
        if( userId.equals("$LoggedInUser") ) //$NON-NLS-1$
        {
            user = CurrentUser.getDetails();
        }
        else
        {
            user = userService.getInformationForUser(userId);
        }
    }
    String format = Format.DEFAULT_USER_BEAN_FORMAT;
    if( args.size() > 1 )
    {
        Object formatModel = args.get(1);
        if( formatModel instanceof TemplateScalarModel )
        {
            format = ((TemplateScalarModel) formatModel).getAsString();
        }
    }

    return new SimpleScalar(Utils.ent(Format.format(user, format)));
}
项目:requirementsascode    文件:SystemPartOfStep.java   
@SuppressWarnings("rawtypes")
@Override
public Object exec(List arguments) throws TemplateModelException {
  if (arguments.size() != 1) {
    throw new TemplateModelException("Wrong number of arguments. Must be 1.");
  }

  Step step = getStepFromFreemarker(arguments.get(0));

  String systemPartOfStep = getSystemPartOfStep(step);

  return new SimpleScalar(systemPartOfStep);
}
项目:requirementsascode    文件:ActorPartOfStep.java   
@SuppressWarnings("rawtypes")
@Override
public Object exec(List arguments) throws TemplateModelException {
  if (arguments.size() != 1) {
    throw new TemplateModelException("Wrong number of arguments. Must be 1.");
  }

  Step step = getStepFromFreemarker(arguments.get(0));
  String actors = getJoinedActors(step, ACTOR_SEPARATOR);

  return new SimpleScalar(actors);
}
项目:requirementsascode    文件:FlowPredicate.java   
@SuppressWarnings("rawtypes")
@Override
public Object exec(List arguments) throws TemplateModelException {
  if (arguments.size() != 1) {
    throw new TemplateModelException("Wrong number of arguments. Must be 1.");
  }

  Flow flow = getFlowFromFreemarker(arguments.get(0));

  String flowPredicate = getFlowPredicate(flow);

  return new SimpleScalar(flowPredicate);
}
项目:scipio-erp    文件:FreeMarkerWorker.java   
@SuppressWarnings("unchecked")
public static <T> T unwrap(Object o) {
    Object returnObj = null;

    if (o == TemplateModel.NOTHING) {
        returnObj = null;
    } else if (o instanceof SimpleScalar) {
        returnObj = o.toString();
    } else if (o instanceof BeanModel) {
        returnObj = ((BeanModel) o).getWrappedObject();
    }

    return (T) returnObj;
}
项目:scipio-erp    文件:SetRequestAttributeMethod.java   
@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");
    // SCIPIO: This is too limiting...
    //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 = FreeMarkerWorker.getCurrentEnvironment();
    BeanModel req = (BeanModel)env.getVariable("request");
    HttpServletRequest request = (HttpServletRequest) req.getWrappedObject();

    // SCIPIO: name should not be escaped
    //String name = ((TemplateScalarModel) args.get(0)).getAsString();
    String name = LangFtlUtil.getAsStringNonEscaping(((TemplateScalarModel) args.get(0)));
    Object valueModel = args.get(1);
    Object value = null;
    // SCIPIO: Let DeepUnwrap handle this...
    //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();
    // SCIPIO: NOTE: Unlike this above, this call will avoid the auto-escaping as implemented by Ofbiz (sensitive to DeepUnwrap implementation)
    value = LangFtlUtil.unwrapAlwaysUnlessNull(valueModel);

    request.setAttribute(name, value);
    return new SimpleScalar("");
}
项目:scipio-erp    文件:SetGlobalContextFieldMethod.java   
@SuppressWarnings("unchecked")
@Override
public Object exec(List args) throws TemplateModelException {
    if (args == null || args.size() != 2)
        throw new TemplateModelException("Invalid number of arguments");
    if (!(args.get(0) instanceof TemplateScalarModel))
        throw new TemplateModelException("First argument not an instance of TemplateScalarModel");
    // SCIPIO: This is too limiting
    //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 = FreeMarkerWorker.getCurrentEnvironment();
    BeanModel globalContextModel = (BeanModel) env.getVariable("globalContext");
    Map<String, Object> globalContext = (Map<String, Object>) globalContextModel.getWrappedObject();

    String name = LangFtlUtil.getAsStringNonEscaping(((TemplateScalarModel) args.get(0)));
    Object valueModel = args.get(1);
    Object value = null;
    // SCIPIO: Let DeepUnwrap handle this...
    //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();
    // SCIPIO: NOTE: Unlike this above, this call will avoid the auto-escaping as implemented by Ofbiz (sensitive to DeepUnwrap implementation)
    value = LangFtlUtil.unwrapAlwaysUnlessNull(valueModel);

    globalContext.put(name, value);
    return new SimpleScalar("");
}
项目:scipio-erp    文件:MultiVarMethod.java   
@Override
protected Object execTyped(List<TemplateModel> args) throws TemplateModelException {
    TemplateHashModelEx varMapsModel = (TemplateHashModelEx) args.get(0);
    CommonVarMaps<Map<String, Object>> varMaps = CommonVarMaps.getRawMaps(varMapsModel);
    Environment env = FreeMarkerWorker.getCurrentEnvironment();
    setVars(varMaps, env);
    return new SimpleScalar("");
}
项目:scipio-erp    文件:MultiVarMethod.java   
@Override
protected Object execTyped(List<TemplateModel> args) throws TemplateModelException {
    TemplateHashModelEx varListsModel = (TemplateHashModelEx) args.get(0);
    CommonVarMaps<Collection<String>> varLists = CommonVarMaps.getRawSequences(varListsModel);
    Environment env = FreeMarkerWorker.getCurrentEnvironment();
    clearVars(varLists, env);
    return new SimpleScalar("");
}
项目:scipio-erp    文件:ArgMapMethod.java   
@SuppressWarnings("unchecked")
protected Object execMergeArgMapsToLocals(List methodArgs, boolean recordArgNames) throws TemplateModelException {
    Environment env = CommonFtlUtil.getCurrentEnvironment();

    SimpleHash resArgs = (SimpleHash) execMergeArgMaps(methodArgs, recordArgNames, env);

    LangFtlUtil.localsPutAll(resArgs, env);
    env.setLocalVariable("args", resArgs);

    return new SimpleScalar(""); 
}