freemarker.template.TemplateModelException Java Examples

The following examples show how to use freemarker.template.TemplateModelException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SortProjectsByPathMethod.java    From windup with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException
{
    ExecutionStatistics.get().begin(NAME);
    if (arguments.size() != 1)
    {
        throw new TemplateModelException("Error, method expects one argument (Iterable<ProjectModel>)");
    }

    @SuppressWarnings("unchecked")
    Iterable<ProjectModel> projectModelIterable = FreeMarkerUtil.freemarkerWrapperToIterable(arguments.get(0));
    List<ProjectModel> projectModelList = new ArrayList<>();
    for (ProjectModel pm : projectModelIterable)
    {
        projectModelList.add(pm);
    }
    Collections.sort(projectModelList, new ProjectModelByRootFileComparator());
    ExecutionStatistics.get().end(NAME);
    return projectModelList;
}
 
Example #2
Source File: FormatRule.java    From windup with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException
{
    ExecutionStatistics.get().begin(NAME);
    if (arguments.size() != 1)
    {
        throw new TemplateModelException("Error, method expects one argument (Rule)");
    }
    StringModel stringModelArg = (StringModel) arguments.get(0);
    Rule rule = (Rule) stringModelArg.getWrappedObject();

    String result = RuleUtils.ruleToRuleContentsString(rule, 0);

    ExecutionStatistics.get().end(NAME);
    return result;
}
 
Example #3
Source File: GetEffortDescriptionForPoints.java    From windup with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Object exec(List arguments) throws TemplateModelException
{
    ExecutionStatistics.get().begin(NAME);
    if (arguments.size() < 1)
    {
        throw new TemplateModelException("Error, method expects one or two arguments (Integer, [verbosity:String])");
    }
    SimpleNumber simpleNumber = (SimpleNumber) arguments.get(0);
    int effort = simpleNumber.getAsNumber().intValue();

    Verbosity verbosity = Verbosity.SHORT;
    if (arguments.size() > 1)
    {
        final TemplateScalarModel verbosityModel = (TemplateScalarModel) arguments.get(1);
        String verbosityString = verbosityModel.getAsString();
        verbosity = Verbosity.valueOf(verbosityString.toUpperCase());
    }

    String result = EffortReportService.getEffortLevelDescription(verbosity, effort);

    ExecutionStatistics.get().end(NAME);
    return result;
}
 
Example #4
Source File: MultiVarMethod.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
public static void setVars(CommonVarMaps<Map<String, Object>> maps, CommonVarMaps<Boolean> skipSet, Environment env) throws TemplateModelException {
    if (maps.ctxVars != null && !maps.ctxVars.isEmpty() && !skipSet.ctxVars) {
        Map<String, Object> context = ContextFtlUtil.getContext(env);
        context.putAll(maps.ctxVars);
    }

    if (maps.globalCtxVars != null && !maps.globalCtxVars.isEmpty() && !skipSet.globalCtxVars) {
        Map<String, Object> globalContext = ContextFtlUtil.getGlobalContext(env);
        globalContext.putAll(maps.globalCtxVars);
    }

    if (maps.reqAttribs != null && !maps.reqAttribs.isEmpty() && !skipSet.reqAttribs) {
        HttpServletRequest request = ContextFtlUtil.getRequest(env);
        for(Map.Entry<String, Object> entry : maps.reqAttribs.entrySet()) {
            request.setAttribute(entry.getKey(), entry.getValue());
        }
    }
}
 
Example #5
Source File: FormatDescriptionMethod.java    From siddhi with Apache License 2.0 6 votes vote down vote up
@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("```([^```]*)```",
            "</p><pre>$1</pre><p style=\"word-wrap: break-word;margin: 0;\">");
    inputString = inputString.replaceAll("`([^`]*)`", "<code>$1</code>");

    return "<p style=\"word-wrap: break-word;margin: 0;\">" + inputString + "</p>";
}
 
Example #6
Source File: PrincipalTag.java    From mblog with GNU General Public License v3.0 6 votes vote down vote up
String getPrincipalProperty(Object principal, String property) throws TemplateModelException {
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(principal.getClass());

        // Loop through the properties to get the string value of the specified property
        for (PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) {
            if (propertyDescriptor.getName().equals(property)) {
                Object value = propertyDescriptor.getReadMethod().invoke(principal, (Object[]) null);

                return String.valueOf(value);
            }
        }

        // property not found, throw
        throw new TemplateModelException("Property [" + property + "] not found in principal of type [" + principal.getClass().getName() + "]");
    } catch (Exception ex) {
        throw new TemplateModelException("Error reading property [" + property + "] from principal of type [" + principal.getClass().getName() + "]", ex);
    }
}
 
Example #7
Source File: GetNumberOfLibrariesMethod.java    From windup with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException
{
    ExecutionStatistics.get().begin(NAME);

    // Function arguments
    ProjectModel projectModel = null;

    // The project. May *not* be null. All input applications should be passed into this method individually
    if (arguments.size() >= 1) {
        StringModel projectArg = (StringModel) arguments.get(0);
        projectModel = (ProjectModel) projectArg.getWrappedObject();
    }

    if (projectModel == null) {
        String errorMessage = "GetNumberOfLibrariesMethod: No project present to count libraries";
        throw new WindupException(errorMessage);
    }

    Integer result = countLibrariesInModel(this.graphContext, projectModel);

    ExecutionStatistics.get().end(NAME);
    return result;
}
 
Example #8
Source File: ContextFtlUtil.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the FullWebappInfo cache from request or context and pre-caches the
 * "current" webapp info, which can be retrieved using
 * {@link org.ofbiz.webapp.FullWebappInfo.Cache#getCurrentWebappInfo()}.
 */
public static FullWebappInfo.Cache getWebappInfoCacheAndCurrent(Environment env, HttpServletRequest request, RenderEnvType renderEnvType) throws TemplateModelException, IllegalArgumentException {
    FullWebappInfo.Cache cache;
    if (request != null) {
        cache = FullWebappInfo.Cache.fromRequest(request);
        FullWebappInfo.fromRequest(request, cache);
    } else {
        Map<String, Object> context = getContext(env);
        if (context == null) {
            // TODO?: don't bother with env.getVariable, this will always be here...
            Debug.logWarning("getCurrentWebappInfo: 'context' variable not"
                    + " found in Freemarker environment; cannot determine current website or cache webapp info", module);
            return FullWebappInfo.Cache.newCache(getDelegator(env));
        }
        cache = FullWebappInfo.Cache.fromContext(context, renderEnvType);
        FullWebappInfo.fromContext(context, renderEnvType, cache);
        return cache;
    }
    return cache;
}
 
Example #9
Source File: FindSourceFilesByClassNameMethod.java    From windup with Eclipse Public License 1.0 6 votes vote down vote up
@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;
}
 
Example #10
Source File: GetTechnologyTagsForFile.java    From windup with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException
{
    ExecutionStatistics.get().begin(NAME);
    if (arguments.size() != 1)
    {
        throw new TemplateModelException("Error, method expects one argument (" + FileModel.class.getSimpleName() + ")");
    }
    StringModel stringModelArg = (StringModel) arguments.get(0);
    FileModel fileModel = (FileModel) stringModelArg.getWrappedObject();
    Iterable<TechnologyTagModel> result = new TechnologyTagService(this.context).findTechnologyTagsForFile(fileModel);
    ExecutionStatistics.get().end(NAME);
    return result;
}
 
Example #11
Source File: ContextFtlUtil.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
static void pushRequestStack(String name, Object value, boolean setLast, Environment env) throws TemplateModelException {
    HttpServletRequest request = getRequest(env);
    Map<String, Object> context = null;
    if (request == null) {
        context = getContext(env);
    }
    pushRequestStack(name, value, setLast, request, context, env);
}
 
Example #12
Source File: MultiVarMethod.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static CommonVarMaps<Map<String, Object>> getRawMaps(Map<String, TemplateModel> varMaps) throws TemplateModelException {
    return new CommonVarMaps<>(
            (Map<String, Object>) LangFtlUtil.unwrap(varMaps.get("ctxVars")),
            (Map<String, Object>) LangFtlUtil.unwrap(varMaps.get("globalCtxVars")),
            (Map<String, Object>) LangFtlUtil.unwrap(varMaps.get("reqAttribs")));
}
 
Example #13
Source File: FreemarkerWebServiceDisplayer.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
public Object exec(List arguments) throws TemplateModelException {
	String className = (String) arguments.get(0);
	try {
		Class<?> clazz = this.getClass().getClassLoader().loadClass(className);
		WSDoc annotation = clazz.getAnnotation(WSDoc.class);
		if (annotation != null) {
			return annotation.description();
		} else
			return "";
	} catch (Throwable t) {
		return "";
	}
}
 
Example #14
Source File: FreemarkerConfigAwareListener.java    From halo with GNU General Public License v3.0 5 votes vote down vote up
private void loadOptionsConfig() throws TemplateModelException {

        final String blogBaseUrl = optionService.getBlogBaseUrl();
        final String context = optionService.isEnabledAbsolutePath() ? blogBaseUrl + "/" : "/";

        configuration.setSharedVariable("options", optionService.listOptions());
        configuration.setSharedVariable("context", context);
        configuration.setSharedVariable("version", HaloConst.HALO_VERSION);

        configuration.setSharedVariable("globalAbsolutePathEnabled", optionService.isEnabledAbsolutePath());
        configuration.setSharedVariable("blog_title", optionService.getBlogTitle());
        configuration.setSharedVariable("blog_url", blogBaseUrl);
        configuration.setSharedVariable("blog_logo", optionService.getByPropertyOrDefault(BlogProperties.BLOG_LOGO, String.class, BlogProperties.BLOG_LOGO.defaultValue()));
        configuration.setSharedVariable("seo_keywords", optionService.getByPropertyOrDefault(SeoProperties.KEYWORDS, String.class, SeoProperties.KEYWORDS.defaultValue()));
        configuration.setSharedVariable("seo_description", optionService.getByPropertyOrDefault(SeoProperties.DESCRIPTION, String.class, SeoProperties.DESCRIPTION.defaultValue()));

        configuration.setSharedVariable("rss_url", blogBaseUrl + "/rss.xml");
        configuration.setSharedVariable("atom_url", blogBaseUrl + "/atom.xml");
        configuration.setSharedVariable("sitemap_xml_url", blogBaseUrl + "/sitemap.xml");
        configuration.setSharedVariable("sitemap_html_url", blogBaseUrl + "/sitemap.html");
        configuration.setSharedVariable("links_url", context + optionService.getLinksPrefix());
        configuration.setSharedVariable("photos_url", context + optionService.getPhotosPrefix());
        configuration.setSharedVariable("journals_url", context + optionService.getJournalsPrefix());
        configuration.setSharedVariable("archives_url", context + optionService.getArchivesPrefix());
        configuration.setSharedVariable("categories_url", context + optionService.getCategoriesPrefix());
        configuration.setSharedVariable("tags_url", context + optionService.getTagsPrefix());

        log.debug("Loaded options");
    }
 
Example #15
Source File: GetTagModelByNameMethod.java    From windup with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException
{
    if (arguments.size() != 1)
        throw new TemplateModelException("Expected one String argument - the name of the tag.");

    SimpleScalar stringModel = (SimpleScalar) arguments.get(0);
    String tagName = stringModel.getAsString();

    return new TagGraphService(graphContext).getTagByName(tagName);
}
 
Example #16
Source File: LangFtlUtil.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/**
 * To string set.
 * <p>
 * WARN: bypasses auto-escaping, caller handles.
 * (e.g. the object wrapper used to rewrap the result).
 */
public static Set<String> toStringSet(TemplateSequenceModel seqModel) throws TemplateModelException {
    Set<String> set = new HashSet<String>();
    for(int i=0; i < seqModel.size(); i++) {
        set.add(getAsStringNonEscaping((TemplateScalarModel) seqModel.get(i)));
    }
    return set;
}
 
Example #17
Source File: WrapTag.java    From javalite with Apache License 2.0 5 votes vote down vote up
private SimpleHash getHash(Environment env) throws TemplateModelException {
    Set names = env.getKnownVariableNames();
    SimpleHash simpleHash = new SimpleHash();
    for(Object name: names){
        simpleHash.put(name.toString(),env.getVariable(name.toString()));
    }
    return simpleHash;
}
 
Example #18
Source File: ContextFtlUtil.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public static void pushRequestStack(String name, Object value, Environment env) throws TemplateModelException {
    HttpServletRequest request = getRequest(env);
    Map<String, Object> context = null;
    if (request == null) {
        context = getContext(env);
    }
    pushRequestStack(name, value, false, request, context, env);
}
 
Example #19
Source File: OrderedPairModel.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public TemplateModel get(int index) throws TemplateModelException
{
	if (index == 0)
	{
		return SimpleWrapperLibrary.wrap(point.getPreciseX());
	}
	else if (index == 1)
	{
		return SimpleWrapperLibrary.wrap(point.getPreciseY());
	}
	return null;
}
 
Example #20
Source File: DescriptionActor.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public TemplateModel process(CharID id, PObject d) throws TemplateModelException
{
	List<Description> theBenefits = d.getListFor(listKey);
	if (theBenefits == null)
	{
		return FacetLibrary.getFacet(ObjectWrapperFacet.class).wrap(id, Constants.EMPTY_STRING);
	}
	PlayerCharacterTrackingFacet charStore = SpringHelper.getBean(PlayerCharacterTrackingFacet.class);
	PlayerCharacter aPC = charStore.getPC(id);
	final StringBuilder buf = new StringBuilder(250);
	boolean needSpace = false;
	for (final Description desc : theBenefits)
	{
		final String str = desc.getDescription(aPC, Collections.singletonList(d));
		if (!str.isEmpty())
		{
			if (needSpace)
			{
				buf.append(' ');
			}
			buf.append(str);
			needSpace = true;
		}
	}
	return FacetLibrary.getFacet(ObjectWrapperFacet.class).wrap(id, buf.toString());
}
 
Example #21
Source File: VisibleToModel.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException
{
	if (arguments.size() != 1)
	{
		throw new TemplateModelException("Expected 1 argument but found: " + arguments.size());
	}
	View v = View.getViewFromName(((SimpleScalar) arguments.get(0)).getAsString());
	return visibility.isVisibleTo(v);
}
 
Example #22
Source File: TitleCaseModel.java    From opoopress with Apache License 2.0 5 votes vote down vote up
@Override
    public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException {
        if (arguments == null || arguments.isEmpty()) {
            return "";
        }
        String str = (String) arguments.get(0);
//		return WordUtils.capitalizeFully(str);
        return titlecase ? toTitleCase(str) : str;
    }
 
Example #23
Source File: RequestStackMethod.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
protected Object execRead(@SuppressWarnings("rawtypes") List args, boolean pop) throws TemplateModelException {
    if (args == null || args.size() != 1) {
        throw new TemplateModelException("Invalid number of arguments (expected: 1)");
    }
    TemplateModel nameModel = (TemplateModel) args.get(0);
    if (!(nameModel instanceof TemplateScalarModel)) {
        throw new TemplateModelException("First argument not an instance of TemplateScalarModel (string)");
    }

    Environment env = CommonFtlUtil.getCurrentEnvironment();
    Object res = ContextFtlUtil.readRequestStack(LangFtlUtil.getAsStringNonEscaping(((TemplateScalarModel) nameModel)), pop, env);

    ObjectWrapper objectWrapper = GetRequestVarMethod.getResultObjectWrapper(env);
    return LangFtlUtil.wrap(res, objectWrapper);
}
 
Example #24
Source File: MissingValueHashWrapper.java    From connect-utils with Apache License 2.0 5 votes vote down vote up
@Override
public TemplateModel get(String s) throws TemplateModelException {
  Object value = values.get(s);

  if (null == value) {
    return TemplateModel.NOTHING;
  } else {
    return wrap(value);
  }
}
 
Example #25
Source File: CodeControlModel.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public TemplateModel get(String key) throws TemplateModelException
{
	String result = control.get(ObjectKey.getKeyFor(String.class, "*" + key));
	if (result == null)
	{
		return null;
	}
	return SimpleWrapperLibrary.wrap(result);
}
 
Example #26
Source File: OffsetDateTimeAdapter.java    From freemarker-java-8 with Apache License 2.0 5 votes vote down vote up
@Override
public TemplateModel getForType(String s) throws TemplateModelException {
    if (METHOD_FORMAT.equals(s)) {
        return new OffsetDateTimeFormatter(getObject());
    }
    throw new TemplateModelException(METHOD_UNKNOWN_MSG + s);
}
 
Example #27
Source File: ContextFtlUtil.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/**
 * Removes the whole request vars map.
 */
public static void removeRequestVars(HttpServletRequest request,
        Map<String, Object> context, Environment env) throws TemplateModelException {
    if (request != null) {
        request.removeAttribute(ContextFtlUtil.REQUEST_VAR_MAP_NAME_REQATTRIBS);
    }
    Map<String, Object> globalContext = getGlobalContext(context, env);
    if (globalContext != null) {
        globalContext.remove(ContextFtlUtil.REQUEST_VAR_MAP_NAME_GLOBALCONTEXT);
    }
    if (env != null) {
        env.setGlobalVariable(ContextFtlUtil.REQUEST_VAR_MAP_NAME_FTLGLOBALS, null);
    }
}
 
Example #28
Source File: MapKeysMethod.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
@Override
public Object exec(@SuppressWarnings("rawtypes") List args) throws TemplateModelException {
    if (args == null || args.size() != 1) {
        throw new TemplateModelException("Invalid number of arguments (expected: 1)");
    }
    TemplateModel object = (TemplateModel) args.get(0);

    // 2016-04-20: We must wrap the keys with non-escaping wrapper, otherwise keying
    // into map using values will not work for escaped values
    return LangFtlUtil.wrapNonEscaping(LangFtlUtil.getMapKeys(object));
}
 
Example #29
Source File: SetRequestVarMethod.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
@Override
public Object exec(@SuppressWarnings("rawtypes") List args) throws TemplateModelException {
    if (args == null || args.size() < 2 || args.size() > 3) {
        throw new TemplateModelException("Invalid number of arguments (expected: 2-3)");
    }
    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);

    Boolean unwrap = null;
    if (args.size() >= 3) {
        TemplateModel modeModel = (TemplateModel) args.get(2);
        if (modeModel != null) {
            String mode = LangFtlUtil.getAsStringNonEscaping(((TemplateScalarModel) modeModel));
            if ("u".equals(mode)) {
                unwrap = Boolean.TRUE;
            }
            else if ("w".equals(mode)) {
                unwrap = Boolean.FALSE;
            }
        }
    }

    Environment env = CommonFtlUtil.getCurrentEnvironment();
    Object value = valueModel;
    if (unwrap == Boolean.TRUE) {
        value = LangFtlUtil.unwrapPermissive(valueModel);
    }
    ContextFtlUtil.setRequestVar(LangFtlUtil.getAsStringNonEscaping(((TemplateScalarModel) nameModel)), value, env);

    return new SimpleScalar("");
}
 
Example #30
Source File: CNAbilitySelectionModel.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Acts as a hash for producing the contents of this model.
 * 
 * Four items are supported: category, nature, ability and selection.
 */
@Override
public TemplateModel get(String key) throws TemplateModelException
{
	Object towrap;
	if ("pool".equals(key))
	{
		towrap = cnas.getCNAbility().getAbilityCategory();
	}
	else if ("category".equals(key))
	{
		Category<Ability> cat = cnas.getCNAbility().getAbilityCategory();
		Category<Ability> parent = cat.getParentCategory();
		towrap = (parent == null) ? cat : parent;
	}
	else if ("nature".equals(key))
	{
		towrap = cnas.getCNAbility().getNature();
	}
	else if ("ability".equals(key))
	{
		towrap = cnas.getCNAbility().getAbility();
	}
	else if ("selection".equals(key))
	{
		towrap = cnas.getSelection();
	}
	else
	{
		throw new TemplateModelException("CNAbilitySelection did not have output of type " + key);
	}
	return WRAPPER_FACET.wrap(id, towrap);
}