Search in sources :

Example 46 with TemplateModel

use of freemarker.template.TemplateModel in project PublicCMS-preview by sanluan.

the class MethodController method method.

/**
 * 接口指令统一分发
 *
 * @param name
 * @param appToken
 * @param request
 * @param response
 * @return result
 */
@RequestMapping("method/{name}")
public Object method(@PathVariable String name, String appToken, HttpServletRequest request, HttpServletResponse response) {
    BaseMethod method = methodMap.get(name);
    if (null != method) {
        try {
            if (method.needAppToken()) {
                SysAppToken token = appTokenService.getEntity(appToken);
                if (null == token) {
                    return NEED_APP_TOKEN_MAP;
                }
                SysApp app = appService.getEntity(token.getAppId());
                if (null == app) {
                    return NEED_APP_TOKEN_MAP;
                }
            }
            Map<String, Object> map = new HashMap<>();
            String[] paramters = request.getParameterValues("paramters");
            if (CommonUtils.notEmpty(paramters) && paramters.length >= method.minParamtersNumber()) {
                List<TemplateModel> list = new ArrayList<>();
                for (String paramter : paramters) {
                    list.add(getObjectWrapper().wrap(paramter));
                }
                map.put("result", method.exec(list));
                return map;
            } else if (CommonUtils.empty(paramters) && 0 == method.minParamtersNumber()) {
                map.put("result", method.exec(null));
                return map;
            } else {
                map.put(ERROR, "paramtersError");
                return map;
            }
        } catch (TemplateModelException e) {
            log.error(e.getMessage(), e);
            Map<String, String> map = new HashMap<>();
            map.put(ERROR, ApiController.EXCEPTION);
            return map;
        }
    } else {
        return ApiController.NOT_FOUND_MAP;
    }
}
Also used : TemplateModelException(freemarker.template.TemplateModelException) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) TemplateModel(freemarker.template.TemplateModel) SysApp(com.publiccms.entities.sys.SysApp) BaseMethod(com.publiccms.common.base.BaseMethod) SysAppToken(com.publiccms.entities.sys.SysAppToken) HashMap(java.util.HashMap) Map(java.util.Map) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 47 with TemplateModel

use of freemarker.template.TemplateModel in project ninja by ninjaframework.

the class TemplateEngineFreemarkerI18nMethodTest method testThatKeyWithPlaceholderReturnsDefaultKeyWhenKeyCannotBeFound.

@Test
public void testThatKeyWithPlaceholderReturnsDefaultKeyWhenKeyCannotBeFound() throws Exception {
    Optional<Result> resultOptional = Optional.of(result);
    List args = new ArrayList();
    args.add(new SimpleScalar("my.message.key"));
    args.add(new SimpleScalar("1000"));
    Mockito.when(messages.get(Matchers.eq("my.message.key"), Matchers.eq(context), Matchers.eq(resultOptional), Matchers.any(Object.class))).thenReturn(Optional.<String>empty());
    TemplateModel returnValue = templateEngineFreemarkerI18nMethod.exec(args);
    assertThat(((SimpleScalar) returnValue).getAsString(), CoreMatchers.equalTo("my.message.key"));
    // There must have been logged something because we did not find
    // the value for the key...
    Mockito.verify(mockAppender).doAppend(Matchers.anyObject());
}
Also used : ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) TemplateModel(freemarker.template.TemplateModel) SimpleScalar(freemarker.template.SimpleScalar) Result(ninja.Result) Test(org.junit.Test)

Example 48 with TemplateModel

use of freemarker.template.TemplateModel in project ninja by ninjaframework.

the class TemplateEngineFreemarkerI18nMethodTest method testThatSingleKeyWithValueWorks.

@Test
public void testThatSingleKeyWithValueWorks() throws Exception {
    Optional<Result> resultOptional = Optional.of(result);
    Mockito.when(messages.get("my.message.key", context, resultOptional)).thenReturn(Optional.of("This simulates the translated message!"));
    List args = new ArrayList();
    args.add(new SimpleScalar("my.message.key"));
    TemplateModel returnValue = templateEngineFreemarkerI18nMethod.exec(args);
    assertThat(((SimpleScalar) returnValue).getAsString(), CoreMatchers.equalTo("This simulates the translated message!"));
    Mockito.verify(mockAppender, Mockito.never()).doAppend(Matchers.anyObject());
}
Also used : ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) TemplateModel(freemarker.template.TemplateModel) SimpleScalar(freemarker.template.SimpleScalar) Result(ninja.Result) Test(org.junit.Test)

Example 49 with TemplateModel

use of freemarker.template.TemplateModel in project pcgen by PCGen.

the class OutputDB method buildDataModel.

/**
	 * Builds the PlayerCharacter data model for the given CharID.
	 * 
	 * @param id
	 *            The CharID for which the data model should be built
	 * @return A Map of the data model for the PlayerCharacter identified by the
	 *         given CharID
	 */
public static Map<String, Object> buildDataModel(CharID id) {
    Map<String, Object> input = new HashMap<>();
    for (Object k1 : outModels.getKeySet()) {
        for (Object k2 : outModels.getSecondaryKeySet(k1)) {
            ModelFactory modelFactory = outModels.get(k1, k2);
            TemplateModel model = modelFactory.generate(id);
            String k1String = k1.toString();
            if ("".equals(k2.toString())) {
                input.put(k1String, model);
            } else {
                ensureMap(input, k1String);
                @SuppressWarnings("unchecked") Map<Object, Object> m = (Map<Object, Object>) input.get(k1String);
                m.put(k2.toString(), model);
            }
        }
    }
    return input;
}
Also used : HashMap(java.util.HashMap) ModelFactory(pcgen.output.base.ModelFactory) ModeModelFactory(pcgen.output.base.ModeModelFactory) ItemModelFactory(pcgen.output.factory.ItemModelFactory) SetModelFactory(pcgen.output.factory.SetModelFactory) TemplateModel(freemarker.template.TemplateModel) HashMap(java.util.HashMap) Map(java.util.Map) CaseInsensitiveMap(pcgen.base.util.CaseInsensitiveMap) DoubleKeyMap(pcgen.base.util.DoubleKeyMap)

Example 50 with TemplateModel

use of freemarker.template.TemplateModel in project pcgen by PCGen.

the class LoopDirective method execute.

@SuppressWarnings("rawtypes")
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
    // Check if no parameters were given:
    int fromVal = 0;
    Integer toVal = null;
    int step = 1;
    for (Object entryObj : params.entrySet()) {
        Map.Entry entry = (Entry) entryObj;
        String paramName = (String) entry.getKey();
        TemplateModel paramValue = (TemplateModel) entry.getValue();
        switch(paramName) {
            case "from":
                if (!(paramValue instanceof TemplateNumberModel)) {
                    throw new TemplateModelException("The \"" + paramName + "\" parameter " + "must be a number.");
                }
                fromVal = ((TemplateNumberModel) paramValue).getAsNumber().intValue();
                break;
            case "to":
                if (!(paramValue instanceof TemplateNumberModel)) {
                    throw new TemplateModelException("The \"" + paramName + "\" parameter " + "must be a number.");
                }
                toVal = ((TemplateNumberModel) paramValue).getAsNumber().intValue();
                break;
            case "step":
                if (!(paramValue instanceof TemplateNumberModel)) {
                    throw new TemplateModelException("The \"" + paramName + "\" parameter " + "must be a number.");
                }
                step = ((TemplateNumberModel) paramValue).getAsNumber().intValue();
                if (step == 0) {
                    throw new TemplateModelException("The \"" + paramName + "\" parameter must not be 0.");
                }
                break;
        }
    }
    if (toVal == null) {
        throw new TemplateModelException("The \"to\" parameter must be provided.");
    }
    if (body == null) {
        throw new TemplateModelException("This directive must have content.");
    }
    if (step > 0) {
        for (int i = fromVal; i <= toVal; i += step) {
            // Set the loop variable, if there is one:
            if (loopVars.length > 0) {
                loopVars[0] = new SimpleNumber(i);
            }
            if (loopVars.length > 1) {
                loopVars[1] = i + step <= toVal ? TemplateBooleanModel.TRUE : TemplateBooleanModel.FALSE;
            }
            // Executes the nested body (same as <#nested> in FTL). In this
            // case we don't provide a special writer as the parameter:
            body.render(env.getOut());
        }
    } else {
        for (int i = fromVal; i >= toVal; i += step) {
            // Set the loop variable, if there is one:
            if (loopVars.length > 0) {
                loopVars[0] = new SimpleNumber(i);
            }
            if (loopVars.length > 1) {
                loopVars[1] = i + step >= toVal ? TemplateBooleanModel.TRUE : TemplateBooleanModel.FALSE;
            }
            // Executes the nested body (same as <#nested> in FTL). In this
            // case we don't provide a special writer as the parameter:
            body.render(env.getOut());
        }
    }
}
Also used : Entry(java.util.Map.Entry) TemplateModelException(freemarker.template.TemplateModelException) Entry(java.util.Map.Entry) SimpleNumber(freemarker.template.SimpleNumber) TemplateNumberModel(freemarker.template.TemplateNumberModel) TemplateModel(freemarker.template.TemplateModel) Map(java.util.Map)

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