Search in sources :

Example 56 with TemplateModel

use of freemarker.template.TemplateModel in project wombat by PLOS.

the class ReplaceParametersDirectiveTest method testReplaceParameters.

@Test
public void testReplaceParameters() throws Exception {
    Map<String, String[]> parameters = new HashMap<>();
    parameters.put("foo", new String[] { "fooValue" });
    parameters.put("multiValuedParam", new String[] { "value1", "value2" });
    parameters.put("emptyParam", new String[] { "" });
    parameters.put("paramToReplace", new String[] { "oldValue" });
    Multimap<String, TemplateModel> replacements = ImmutableMultimap.of("paramToReplace", new SimpleScalar("newValue"));
    Multimap<String, String> actual = ReplaceParametersDirective.replaceParameters(new SimpleHash(parameters), replacements);
    ImmutableSetMultimap.Builder<String, String> expected = ImmutableSetMultimap.builder();
    expected.put("foo", "fooValue").putAll("multiValuedParam", "value1", "value2").put("emptyParam", "").put("paramToReplace", "newValue");
    assertEquals(actual, expected.build());
}
Also used : HashMap(java.util.HashMap) ImmutableSetMultimap(com.google.common.collect.ImmutableSetMultimap) SimpleHash(freemarker.template.SimpleHash) TemplateModel(freemarker.template.TemplateModel) SimpleScalar(freemarker.template.SimpleScalar) Test(org.testng.annotations.Test)

Example 57 with TemplateModel

use of freemarker.template.TemplateModel in project wombat by PLOS.

the class ReplaceParametersDirective method execute.

public void execute(Environment environment, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
    if (!params.keySet().equals(EXPECTED_KEYS)) {
        throw new TemplateException("ReplaceParametersDirective requires keys: " + EXPECTED_KEYS, environment);
    }
    // I have no idea why freemarker feels the need to invent their own collection classes...
    SimpleHash parameterMap = (SimpleHash) params.get(PARAMETER_MAP_KEY);
    Multimap<String, TemplateModel> replacements = TemplateModelUtil.getAsMultimap((TemplateModel) params.get(REPLACEMENTS_KEY));
    Multimap<String, String> outputParams = replaceParameters(parameterMap, replacements);
    List<NameValuePair> paramList = new ArrayList<>(outputParams.size());
    for (String key : outputParams.keySet()) {
        for (String value : outputParams.get(key)) {
            paramList.add(new BasicNameValuePair(key, value));
        }
    }
    environment.getOut().write(URLEncodedUtils.format(paramList, "UTF-8"));
}
Also used : BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) TemplateException(freemarker.template.TemplateException) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) SimpleHash(freemarker.template.SimpleHash) ArrayList(java.util.ArrayList) TemplateModel(freemarker.template.TemplateModel)

Example 58 with TemplateModel

use of freemarker.template.TemplateModel in project nutzboot by nutzam.

the class FreemarkerView method jspTaglibs.

protected void jspTaglibs(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response, Map<String, Object> model, ObjectWrapper wrapper) {
    synchronized (servletContext) {
        ServletContextHashModel servletContextModel = (ServletContextHashModel) servletContext.getAttribute(ATTR_APPLICATION_MODEL);
        if (Lang.isEmpty(servletContextModel)) {
            GenericServlet servlet = JspSupportServlet.jspSupportServlet;
            if (!Lang.isEmpty(servlet)) {
                servletContextModel = new ServletContextHashModel(servlet, wrapper);
                servletContext.setAttribute(ATTR_APPLICATION_MODEL, servletContextModel);
                TaglibFactory taglibs = new TaglibFactory(servletContext);
                servletContext.setAttribute(ATTR_JSP_TAGLIBS_MODEL, taglibs);
            }
        }
        model.put(KEY_APPLICATION, servletContextModel);
        TemplateModel tempModel = (TemplateModel) servletContext.getAttribute(ATTR_JSP_TAGLIBS_MODEL);
        model.put(KEY_JSP_TAGLIBS, tempModel);
    }
    HttpSession session = request.getSession(false);
    if (!Lang.isEmpty(session)) {
        model.put(KEY_SESSION_MODEL, new HttpSessionHashModel(session, wrapper));
    }
    HttpRequestHashModel requestModel = (HttpRequestHashModel) request.getAttribute(ATTR_REQUEST_MODEL);
    if (Lang.isEmpty(requestModel) || !Lang.equals(requestModel.getRequest(), request)) {
        requestModel = new HttpRequestHashModel(request, response, wrapper);
        request.setAttribute(ATTR_REQUEST_MODEL, requestModel);
    }
    model.put(KEY_REQUEST_MODEL, requestModel);
    HttpRequestParametersHashModel reqParametersModel = (HttpRequestParametersHashModel) request.getAttribute(ATTR_REQUEST_PARAMETERS_MODEL);
    if (Lang.isEmpty(reqParametersModel) || !Lang.equals(requestModel.getRequest(), request)) {
        reqParametersModel = new HttpRequestParametersHashModel(request);
        request.setAttribute(ATTR_REQUEST_PARAMETERS_MODEL, reqParametersModel);
    }
    model.put(KEY_REQUEST_PARAMETER_MODEL, reqParametersModel);
    Throwable exception = (Throwable) request.getAttribute("javax.servlet.error.exception");
    if (Lang.isEmpty(exception)) {
        exception = (Throwable) request.getAttribute("javax.servlet.error.JspException");
    }
    if (!Lang.isEmpty(exception)) {
        model.put(KEY_EXCEPTION, exception);
    }
}
Also used : HttpRequestHashModel(freemarker.ext.servlet.HttpRequestHashModel) GenericServlet(javax.servlet.GenericServlet) HttpSessionHashModel(freemarker.ext.servlet.HttpSessionHashModel) HttpSession(javax.servlet.http.HttpSession) ServletContextHashModel(freemarker.ext.servlet.ServletContextHashModel) TaglibFactory(freemarker.ext.jsp.TaglibFactory) TemplateModel(freemarker.template.TemplateModel) HttpRequestParametersHashModel(freemarker.ext.servlet.HttpRequestParametersHashModel)

Example 59 with TemplateModel

use of freemarker.template.TemplateModel in project freemarker by apache.

the class Environment method setMacroContextLocalsFromArguments.

/**
 * Sets the local variables corresponding to the macro call arguments in the macro context.
 */
private void setMacroContextLocalsFromArguments(final Macro.Context macroCtx, final Macro macro, final Map namedArgs, final List positionalArgs) throws TemplateException, _MiscTemplateException {
    String catchAllParamName = macro.getCatchAll();
    if (namedArgs != null) {
        final SimpleHash catchAllParamValue;
        if (catchAllParamName != null) {
            catchAllParamValue = new SimpleHash((ObjectWrapper) null);
            macroCtx.setLocalVar(catchAllParamName, catchAllParamValue);
        } else {
            catchAllParamValue = null;
        }
        for (Iterator it = namedArgs.entrySet().iterator(); it.hasNext(); ) {
            final Map.Entry argNameAndValExp = (Map.Entry) it.next();
            final String argName = (String) argNameAndValExp.getKey();
            final boolean isArgNameDeclared = macro.hasArgNamed(argName);
            if (isArgNameDeclared || catchAllParamName != null) {
                Expression argValueExp = (Expression) argNameAndValExp.getValue();
                TemplateModel argValue = argValueExp.eval(this);
                if (isArgNameDeclared) {
                    macroCtx.setLocalVar(argName, argValue);
                } else {
                    catchAllParamValue.put(argName, argValue);
                }
            } else {
                throw new _MiscTemplateException(this, (macro.isFunction() ? "Function " : "Macro "), new _DelayedJQuote(macro.getName()), " has no parameter with name ", new _DelayedJQuote(argName), ".");
            }
        }
    } else if (positionalArgs != null) {
        final SimpleSequence catchAllParamValue;
        if (catchAllParamName != null) {
            catchAllParamValue = new SimpleSequence((ObjectWrapper) null);
            macroCtx.setLocalVar(catchAllParamName, catchAllParamValue);
        } else {
            catchAllParamValue = null;
        }
        String[] argNames = macro.getArgumentNamesInternal();
        final int argsCnt = positionalArgs.size();
        if (argNames.length < argsCnt && catchAllParamName == null) {
            throw new _MiscTemplateException(this, (macro.isFunction() ? "Function " : "Macro "), new _DelayedJQuote(macro.getName()), " only accepts ", new _DelayedToString(argNames.length), " parameters, but got ", new _DelayedToString(argsCnt), ".");
        }
        for (int i = 0; i < argsCnt; i++) {
            Expression argValueExp = (Expression) positionalArgs.get(i);
            TemplateModel argValue = argValueExp.eval(this);
            try {
                if (i < argNames.length) {
                    String argName = argNames[i];
                    macroCtx.setLocalVar(argName, argValue);
                } else {
                    catchAllParamValue.add(argValue);
                }
            } catch (RuntimeException re) {
                throw new _MiscTemplateException(re, this);
            }
        }
    }
}
Also used : TemplateModel(freemarker.template.TemplateModel) SimpleSequence(freemarker.template.SimpleSequence) SimpleHash(freemarker.template.SimpleHash) Iterator(java.util.Iterator) TemplateModelIterator(freemarker.template.TemplateModelIterator) ObjectWrapper(freemarker.template.ObjectWrapper) Map(java.util.Map) IdentityHashMap(java.util.IdentityHashMap) HashMap(java.util.HashMap)

Example 60 with TemplateModel

use of freemarker.template.TemplateModel in project freemarker by apache.

the class Environment method getNodeProcessor.

TemplateModel getNodeProcessor(TemplateNodeModel node) throws TemplateException {
    String nodeName = node.getNodeName();
    if (nodeName == null) {
        throw new _MiscTemplateException(this, "Node name is null.");
    }
    TemplateModel result = getNodeProcessor(nodeName, node.getNodeNamespace(), 0);
    if (result == null) {
        String type = node.getNodeType();
        /* DD: Original version: */
        if (type == null) {
            type = "default";
        }
        result = getNodeProcessor("@" + type, null, 0);
    /*
             * DD: Jonathan's non-BC version and IMHO otherwise wrong version: if (type != null) { result =
             * getNodeProcessor("@" + type, null, 0); } if (result == null) { result = getNodeProcessor("@default",
             * null, 0); }
             */
    }
    return result;
}
Also used : TemplateModel(freemarker.template.TemplateModel)

Aggregations

TemplateModel (freemarker.template.TemplateModel)108 TemplateModelException (freemarker.template.TemplateModelException)26 Map (java.util.Map)23 TemplateScalarModel (freemarker.template.TemplateScalarModel)18 Test (org.junit.Test)17 ArrayList (java.util.ArrayList)15 TemplateException (freemarker.template.TemplateException)13 HashMap (java.util.HashMap)13 SimpleScalar (freemarker.template.SimpleScalar)11 IOException (java.io.IOException)11 List (java.util.List)11 Template (freemarker.template.Template)9 TemplateSequenceModel (freemarker.template.TemplateSequenceModel)8 TemplateTransformModel (freemarker.template.TemplateTransformModel)8 SimpleHash (freemarker.template.SimpleHash)7 SimpleSequence (freemarker.template.SimpleSequence)7 Writer (java.io.Writer)7 Iterator (java.util.Iterator)7 Environment (freemarker.core.Environment)6 TemplateHashModel (freemarker.template.TemplateHashModel)6