freemarker.template.SimpleHash Java Examples

The following examples show how to use freemarker.template.SimpleHash. 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: LangFtlUtil.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
/**
 * Combines two maps with the given operator into a new hash.
 */
public static TemplateHashModelEx combineMaps(TemplateHashModelEx first, TemplateHashModelEx second, SetOperations ops,
        ObjectWrapper objectWrapper) throws TemplateModelException {
    SimpleHash res = new SimpleHash(objectWrapper);
    if (ops == null || ops == SetOperations.UNION) {
        // this is less efficient than freemarker + operator, but provides the "alternative" implementation, so have choice
        addToSimpleMap(res, first);
        addToSimpleMap(res, second);
    }
    else if (ops == SetOperations.INTERSECT) {
        Set<String> intersectKeys = toStringSet(second.keys());
        intersectKeys.retainAll(toStringSet(first.keys()));
        addToSimpleMap(res, second, intersectKeys);
    }
    else if (ops == SetOperations.DIFFERENCE) {
        Set<String> diffKeys = toStringSet(first.keys());
        diffKeys.removeAll(toStringSet(second.keys()));
        addToSimpleMap(res, first, diffKeys);
    }
    else {
        throw new TemplateModelException("Unsupported combineMaps operation");
    }
    return res;
}
 
Example #2
Source File: WrapTag.java    From javalite with Apache License 2.0 6 votes vote down vote up
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
    if(!params.containsKey("with")) {
        throw new RuntimeException("\"with\" param was not provided");
    }

    String withArgument = params.get("with").toString();

    StringWriter innerContent = new StringWriter();
    body.render(innerContent);        

    SimpleHash envValues = getHash(env);
    envValues.putAll(params);
    envValues.put("page_content", innerContent.toString());
    for(Object key : params.keySet()) {
        if(key.toString().equals("with")) {
            continue;
        } else {
            envValues.put(key.toString(), params.get(key));
        }
    }

    String path = getTemplatePath(env.getTemplate().getName(), withArgument);
    Template template = env.getConfiguration().getTemplate(path + ".ftl");
    template.process(envValues, env.getOut());
}
 
Example #3
Source File: LangFtlUtil.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
/**
 * Adapts a map to a TemplateHashModelEx using an appropriate simple adapter, normally
 * DefaultMapAdapter (or SimpleMapModel for BeansWrapper compatibility).
 * <p>
 * The ObjectWrapper is expected to implement at least ObjectWrapperWithAPISupport.
 * <p>
 * WARN: If impossible, it will duplicate the map using SimpleHash; but because this may result
 * in loss of ordering, a log warning will be printed.
 */
public static TemplateHashModelEx makeSimpleMapAdapter(Map<?, ?> map, ObjectWrapper objectWrapper, boolean permissive) throws TemplateModelException {
    // COMPATIBILITY MODE: check if exactly BeansWrapper, or a class that we know extends it WITHOUT extending DefaultObjectWrapper
    if (objectWrapper instanceof ScipioBeansWrapper || BeansWrapper.class.equals(objectWrapper.getClass())) {
        return new SimpleMapModel(map, (BeansWrapper) objectWrapper);
    } else if (objectWrapper instanceof ObjectWrapperWithAPISupport) {
        return DefaultMapAdapter.adapt(map, (ObjectWrapperWithAPISupport) objectWrapper);
    } else {
        if (permissive) {
            Debug.logWarning("Scipio: adaptSimpleMap: Unsupported Freemarker object wrapper (expected to implement ObjectWrapperWithAPISupport or BeansWrapper); forced to adapt map"
                    + " using SimpleHash; this could cause loss of map insertion ordering; please switch renderer setup to a different ObjectWrapper", module);
            return new SimpleHash(map, objectWrapper);
        } else {
            throw new TemplateModelException("Tried to wrap a Map using an adapter class,"
                    + " but our ObjectWrapper does not implement ObjectWrapperWithAPISupport or BeansWrapper"
                    + "; please switch renderer setup to a different ObjectWrapper");
        }
    }
}
 
Example #4
Source File: RenderComponentDirective.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
protected SimpleHash getFullModel(SiteItem component, Map<String, Object> templateModel,
                                  Map<String, Object> additionalModel) throws TemplateException {
    SimpleHash model = modelFactory.getObject();
    model.put(KEY_MODEL, component);
    model.put(KEY_CONTENT_MODEL, component);

    if (MapUtils.isNotEmpty(templateModel)) {
        model.putAll(templateModel);
    }
    if (MapUtils.isNotEmpty(additionalModel)) {
        model.putAll(additionalModel);
    }

    return model;
}
 
Example #5
Source File: NanoWSClientModule.java    From mwsc with MIT License 5 votes vote down vote up
@Override
public Set<FileInfo> generate(WSCodeGenModel cgModel, CGConfig config)
		throws WscModuleException {
	// freemarker datamodel
	SimpleHash fmModel = this.getFreemarkerModel();
	
	// container for target codes
	Set<FileInfo> targetFileSet = new HashSet<FileInfo>();
	
	info("Generating the Nano web serivce client classes...");
	
	fmModel.put("group", config.picoServiceGroup);
	fmModel.put("config", config);
	
	// generate endpoint interface
	for (SEIInfo interfaceInfo : cgModel.getServiceEndpointInterfaces()) {
		fmModel.put("imports", this.getInterfaceImports(interfaceInfo));
		fmModel.put("endpointInterface", interfaceInfo);

		String relativePath = ClassNameUtil.packageNameToPath(interfaceInfo.getPackageName());
		relativePath += File.separator + "client";
		FileInfo eiSoapClient = this.generateFile(soapClientTemplate, fmModel, interfaceInfo.getName() + "_SOAPClient", "java", relativePath);
		targetFileSet.add(eiSoapClient);
		FileInfo eiXmlClient = this.generateFile(xmlClientTemplate, fmModel, interfaceInfo.getName() + "_XMLClient", "java", relativePath);
		targetFileSet.add(eiXmlClient);
	}
	
	return targetFileSet;
}
 
Example #6
Source File: AbstractFreemarkerTemplateConfigurer.java    From onetwo with Apache License 2.0 5 votes vote down vote up
/****
	 * must be invoke after contruction
	 */
	public void initialize() {
		if(isInitialized())
			return ;
		
		TemplateLoader loader = getTempateLoader();
		Assert.notNull(loader);
		try {
			this.configuration = new Configuration(Configuration.VERSION_2_3_0);
			this.configuration.setObjectWrapper(getBeansWrapper());
			this.configuration.setOutputEncoding(this.encoding);
			//设置默认不自动格式化数字……以防sb……
			this.configuration.setNumberFormat("#");
//			this.cfg.setDirectoryForTemplateLoading(new File(templateDir));
			
			/*if(templateProvider!=null){
				this.configuration.setTemplateLoader(new DynamicTemplateLoader(templateProvider));
			}*/
			if(LangUtils.isNotEmpty(getFreemarkerVariables()))
				configuration.setAllSharedVariables(new SimpleHash(freemarkerVariables, configuration.getObjectWrapper()));
			
			//template loader
			/*if(!LangUtils.isEmpty(templatePaths)){
				TemplateLoader loader = FtlUtils.getTemplateLoader(resourceLoader, templatePaths);
				this.configuration.setTemplateLoader(loader);
			}*/
			this.configuration.setTemplateLoader(loader);
			
			this.buildConfigration(this.configuration);
			
			initialized = true;
		} catch (Exception e) {
			throw new BaseException("create freemarker template error : " + e.getMessage(), e);
		}
	}
 
Example #7
Source File: MultiVarMethod.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public TemplateHashModelEx toMapModel(Environment env) {
    SimpleHash map = new SimpleHash(env.getObjectWrapper());
    map.put("ctxVars", ctxVars);
    map.put("globalCtxVars", globalCtxVars);
    map.put("reqAttribs", reqAttribs);
    return map;
}
 
Example #8
Source File: SiteContextResolvingFilter.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
protected void renderError(HttpServletResponse response) {
    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    try {
        Configuration configuration = freeMarkerConfigFactory.getObject().getConfiguration();
        Template template = configuration.getTemplate(errorTemplate);
        SimpleHash model = new SimpleHash(configuration.getObjectWrapper());
        configuration.setAllSharedVariables(model);
        template.process(model, response.getWriter());
    } catch (Exception e) {
        logger.error("Error rendering template for site resolving error", e);
    }
}
 
Example #9
Source File: FreeMarkerView.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Build a FreeMarker template model for the given model Map.
 * <p>The default implementation builds a {@link AllHttpScopesHashModel}.
 * @param model the model to use for rendering
 * @param request current HTTP request
 * @param response current servlet response
 * @return the FreeMarker template model, as a {@link SimpleHash} or subclass thereof
 */
protected SimpleHash buildTemplateModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) {
	AllHttpScopesHashModel fmModel = new AllHttpScopesHashModel(getObjectWrapper(), getServletContext(), request);
	fmModel.put(FreemarkerServlet.KEY_JSP_TAGLIBS, this.taglibFactory);
	fmModel.put(FreemarkerServlet.KEY_APPLICATION, this.servletContextHashModel);
	fmModel.put(FreemarkerServlet.KEY_SESSION, buildSessionModel(request, response));
	fmModel.put(FreemarkerServlet.KEY_REQUEST, new HttpRequestHashModel(request, response, getObjectWrapper()));
	fmModel.put(FreemarkerServlet.KEY_REQUEST_PARAMETERS, new HttpRequestParametersHashModel(request));
	fmModel.putAll(model);
	return fmModel;
}
 
Example #10
Source File: LangFtlUtil.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/**
 * Adds to simple hash from source map.
 * <p>
 * <em>WARN</em>: This is not BeanModel-aware (complex map).
 */
public static void addToSimpleMap(SimpleHash dest, TemplateHashModelEx source) throws TemplateModelException {
    TemplateCollectionModel keysModel = source.keys();
    TemplateModelIterator modelIt = keysModel.iterator();
    while(modelIt.hasNext()) {
        String key = getAsStringNonEscaping((TemplateScalarModel) modelIt.next());
        dest.put(key, source.get(key));
    }
}
 
Example #11
Source File: RenderComponentDirective.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException {
    TemplateModel componentParentParam = (TemplateModel) params.get(COMPONENT_PARENT_PARAM_NAME);
    TemplateModel componentParam = (TemplateModel) params.get(COMPONENT_PARAM_NAME);
    TemplateModel componentPathParam = (TemplateModel) params.get(COMPONENT_PATH_PARAM_NAME);
    TemplateModel additionalModelParam = (TemplateModel) params.get(ADDITIONAL_MODEL_PARAM_NAME);
    Map<String, Object> additionalModel = null;
    SiteItem component;

    if (componentParam == null && componentPathParam == null) {
        throw new TemplateException("No '" + COMPONENT_PARAM_NAME + "' or '" + COMPONENT_PATH_PARAM_NAME +
                                    "' param specified", env);
    } else if (componentParam != null) {
        component = getComponentFromNode(componentParentParam, componentParam, env);
    } else {
        component = getComponentFromPath(componentPathParam, env);
    }

    if (additionalModelParam != null) {
        additionalModel = unwrap(ADDITIONAL_MODEL_PARAM_NAME, additionalModelParam, Map.class, env);
    }

    Map<String, Object> templateModel = executeScripts(component, additionalModel, env);
    SimpleHash model = getFullModel(component, templateModel, additionalModel);
    Template template = getTemplate(component, env);
    Writer output = env.getOut();

    processComponentTemplate(template, model, output, env);
}
 
Example #12
Source File: RenderComponentDirective.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
protected void processComponentTemplate(Template template, SimpleHash model, Writer output, Environment env)
    throws TemplateException {
    try {
        template.process(model, output);
    } catch (IOException e) {
        throw new TemplateException("I/O exception while processing the component template", e, env);
    }
}
 
Example #13
Source File: FreeMarkerView.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Build a FreeMarker template model for the given model Map.
 * <p>The default implementation builds a {@link AllHttpScopesHashModel}.
 * @param model the model to use for rendering
 * @param request current HTTP request
 * @param response current servlet response
 * @return the FreeMarker template model, as a {@link SimpleHash} or subclass thereof
 */
protected SimpleHash buildTemplateModel(Map<String, Object> model, HttpServletRequest request,
		HttpServletResponse response) {

	AllHttpScopesHashModel fmModel = new AllHttpScopesHashModel(getObjectWrapper(), getServletContext(), request);
	fmModel.put(FreemarkerServlet.KEY_JSP_TAGLIBS, this.taglibFactory);
	fmModel.put(FreemarkerServlet.KEY_APPLICATION, this.servletContextHashModel);
	fmModel.put(FreemarkerServlet.KEY_SESSION, buildSessionModel(request, response));
	fmModel.put(FreemarkerServlet.KEY_REQUEST, new HttpRequestHashModel(request, response, getObjectWrapper()));
	fmModel.put(FreemarkerServlet.KEY_REQUEST_PARAMETERS, new HttpRequestParametersHashModel(request));
	fmModel.putAll(model);
	return fmModel;
}
 
Example #14
Source File: FreeMarkerView.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Build a FreeMarker template model for the given model Map.
 * <p>The default implementation builds a {@link AllHttpScopesHashModel}.
 * @param model the model to use for rendering
 * @param request current HTTP request
 * @param response current servlet response
 * @return the FreeMarker template model, as a {@link SimpleHash} or subclass thereof
 */
protected SimpleHash buildTemplateModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) {
	AllHttpScopesHashModel fmModel = new AllHttpScopesHashModel(getObjectWrapper(), getServletContext(), request);
	fmModel.put(FreemarkerServlet.KEY_JSP_TAGLIBS, this.taglibFactory);
	fmModel.put(FreemarkerServlet.KEY_APPLICATION, this.servletContextHashModel);
	fmModel.put(FreemarkerServlet.KEY_SESSION, buildSessionModel(request, response));
	fmModel.put(FreemarkerServlet.KEY_REQUEST, new HttpRequestHashModel(request, response, getObjectWrapper()));
	fmModel.put(FreemarkerServlet.KEY_REQUEST_PARAMETERS, new HttpRequestParametersHashModel(request));
	fmModel.putAll(model);
	return fmModel;
}
 
Example #15
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 #16
Source File: FreeMarkerView.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Build a FreeMarker template model for the given model Map.
 * <p>The default implementation builds a {@link AllHttpScopesHashModel}.
 * @param model the model to use for rendering
 * @param request current HTTP request
 * @param response current servlet response
 * @return the FreeMarker template model, as a {@link SimpleHash} or subclass thereof
 */
protected SimpleHash buildTemplateModel(Map<String, Object> model, HttpServletRequest request,
		HttpServletResponse response) {

	AllHttpScopesHashModel fmModel = new AllHttpScopesHashModel(getObjectWrapper(), getServletContext(), request);
	fmModel.put(FreemarkerServlet.KEY_JSP_TAGLIBS, this.taglibFactory);
	fmModel.put(FreemarkerServlet.KEY_APPLICATION, this.servletContextHashModel);
	fmModel.put(FreemarkerServlet.KEY_SESSION, buildSessionModel(request, response));
	fmModel.put(FreemarkerServlet.KEY_REQUEST, new HttpRequestHashModel(request, response, getObjectWrapper()));
	fmModel.put(FreemarkerServlet.KEY_REQUEST_PARAMETERS, new HttpRequestParametersHashModel(request));
	fmModel.putAll(model);
	return fmModel;
}
 
Example #17
Source File: LangFtlUtil.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
public static SimpleHash makeSimpleMap(TemplateHashModel map, TemplateSequenceModel keys, ObjectWrapper objectWrapper) throws TemplateModelException {
    SimpleHash res = new SimpleHash(objectWrapper);
    addToSimpleMap(res, map, LangFtlUtil.toStringSet(keys));
    return res;
}
 
Example #18
Source File: FreeMarkerConfigurationFactory.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * Prepare the FreeMarker Configuration and return it.
 * @return the FreeMarker Configuration object
 * @throws IOException if the config file wasn't found
 * @throws TemplateException on FreeMarker initialization failure
 */
public Configuration createConfiguration() throws IOException, TemplateException {
	Configuration config = newConfiguration();
	Properties props = new Properties();

	// Load config file if specified.
	if (this.configLocation != null) {
		if (logger.isInfoEnabled()) {
			logger.info("Loading FreeMarker configuration from " + this.configLocation);
		}
		PropertiesLoaderUtils.fillProperties(props, this.configLocation);
	}

	// Merge local properties if specified.
	if (this.freemarkerSettings != null) {
		props.putAll(this.freemarkerSettings);
	}

	// FreeMarker will only accept known keys in its setSettings and
	// setAllSharedVariables methods.
	if (!props.isEmpty()) {
		config.setSettings(props);
	}

	if (!CollectionUtils.isEmpty(this.freemarkerVariables)) {
		config.setAllSharedVariables(new SimpleHash(this.freemarkerVariables, config.getObjectWrapper()));
	}

	if (this.defaultEncoding != null) {
		config.setDefaultEncoding(this.defaultEncoding);
	}

	List<TemplateLoader> templateLoaders = new LinkedList<TemplateLoader>(this.templateLoaders);

	// Register template loaders that are supposed to kick in early.
	if (this.preTemplateLoaders != null) {
		templateLoaders.addAll(this.preTemplateLoaders);
	}

	// Register default template loaders.
	if (this.templateLoaderPaths != null) {
		for (String path : this.templateLoaderPaths) {
			templateLoaders.add(getTemplateLoaderForPath(path));
		}
	}
	postProcessTemplateLoaders(templateLoaders);

	// Register template loaders that are supposed to kick in late.
	if (this.postTemplateLoaders != null) {
		templateLoaders.addAll(this.postTemplateLoaders);
	}

	TemplateLoader loader = getAggregateTemplateLoader(templateLoaders);
	if (loader != null) {
		config.setTemplateLoader(loader);
	}

	postProcessConfiguration(config);
	return config;
}
 
Example #19
Source File: LangFtlUtil.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
/**
 * Makes a simple hash from source map; only specified keys.
 * <p>
 * <em>WARN</em>: This is not BeanModel-aware (complex map).
 */
public static SimpleHash makeSimpleMap(TemplateHashModel map, Set<String> keys, ObjectWrapper objectWrapper) throws TemplateModelException {
    SimpleHash res = new SimpleHash(objectWrapper);
    addToSimpleMap(res, map, keys);
    return res;
}
 
Example #20
Source File: PicoWSClientModule.java    From mwsc with MIT License 4 votes vote down vote up
@Override
public Set<FileInfo> generate(WSCodeGenModel cgModel, CGConfig config)
		throws WscModuleException {
	// freemarker datamodel
	SimpleHash fmModel = this.getFreemarkerModel();
	
	// container for target codes
	Set<FileInfo> targetFileSet = new HashSet<FileInfo>();
	
	info("Generating the Pico web serivce client classes...");
	
	if (config.picoPrefix == null) {
		warn("No prefix is provided, it's recommended to add prefix for Pico binding to avoid possible conflict");
	}
	String prefix = config.picoPrefix == null ? "" : config.picoPrefix;
	prefixType(cgModel, prefix);
	
	fmModel.put("group", config.picoServiceGroup);
	
	// generate endpoint interface
	for (SEIInfo interfaceInfo : cgModel.getServiceEndpointInterfaces()) {
		fmModel.put("imports", this.getInterfaceImports(interfaceInfo));
		fmModel.put("endpointInterface", interfaceInfo);
		// special logic for ebay service demo, just a convenient for ebay service proxy generation
		if (config.eBaySOAService) {
			fmModel.put("eBaySOAService", config.eBaySOAService);
		} else if (config.eBayShoppingAPI) {
			fmModel.put("eBayShoppingAPI", config.eBayShoppingAPI);
		} else if (config.eBayTradingAPI) {
			fmModel.put("eBayTradingAPI", config.eBayTradingAPI);
		}
		String relativePath = ClassNameUtil.packageNameToPath(interfaceInfo.getPackageName());
		relativePath += File.separator + "client";
		FileInfo eiSoapIntf = this.generateFile(eiIntfSOAPTemplate, fmModel, interfaceInfo.getName() + "_SOAPClient", "h", relativePath);
		targetFileSet.add(eiSoapIntf);
		FileInfo eiSoapImpl = this.generateFile(eiImplSOAPTemplate, fmModel, interfaceInfo.getName() + "_SOAPClient", "m", relativePath);
		targetFileSet.add(eiSoapImpl);
		FileInfo eiXmlIntf = this.generateFile(eiIntfXMLTemplate, fmModel, interfaceInfo.getName() + "_XMLClient", "h", relativePath);
		targetFileSet.add(eiXmlIntf);
		FileInfo eiXmlImpl = this.generateFile(eiImplXMLTemplate, fmModel, interfaceInfo.getName() + "_XMLClient", "m", relativePath);
		targetFileSet.add(eiXmlImpl);
	}
	
	return targetFileSet;
}
 
Example #21
Source File: FreemarkerTemplateEngine.java    From jbake with MIT License 4 votes vote down vote up
public LazyLoadingModel(ObjectWrapper wrapper, Map<String, Object> eagerModel, final ContentStore db) {
    this.eagerModel = new SimpleHash(eagerModel, wrapper);
    this.db = db;
    this.wrapper = wrapper;
}
 
Example #22
Source File: CrafterFreeMarkerView.java    From engine with GNU General Public License v3.0 4 votes vote down vote up
@Override
@SuppressWarnings("deprecation")
protected SimpleHash buildTemplateModel(final Map<String, Object> model, final HttpServletRequest request,
                                        final HttpServletResponse response) {
    AllHttpScopesAndAppContextHashModel templateModel = new AllHttpScopesAndAppContextHashModel(
        getObjectWrapper(), applicationContextAccessor, getServletContext(), request, disableVariableRestrictions);
    HttpSessionHashModel sessionModel = createSessionModel(request, response);
    HttpRequestHashModel requestModel = new HttpRequestHashModel(request, response, getObjectWrapper());
    HttpRequestParametersHashModel requestParamsModel = new HttpRequestParametersHashModel(request);
    Map<String, String> cookies = createCookieMap(request);

    if (disableVariableRestrictions) {
        templateModel.put(KEY_APPLICATION_CAP, servletContextHashModel);
        templateModel.put(KEY_APPLICATION, servletContextHashModel);
        templateModel.put(KEY_APP_CONTEXT_CAP, applicationContextAccessor);
        templateModel.put(KEY_APP_CONTEXT, applicationContextAccessor);
    }

    templateModel.put(KEY_SESSION_CAP, sessionModel);
    templateModel.put(KEY_SESSION, sessionModel);
    templateModel.put(KEY_REQUEST_CAP, requestModel);
    templateModel.put(KEY_REQUEST, requestModel);
    templateModel.put(KEY_REQUEST_PARAMS_CAP, requestParamsModel);
    templateModel.put(KEY_REQUEST_PARAMS, requestParamsModel);

    templateModel.put(KEY_COOKIES_CAP, cookies);
    templateModel.put(KEY_COOKIES, cookies);

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null) {
        templateModel.put(KEY_AUTH_TOKEN, auth);

        // for backwards compatibility with Profile ...

        if (auth.getPrincipal() instanceof ProfileUser) {
            ProfileUser details = (ProfileUser) auth.getPrincipal();
            templateModel.put(KEY_AUTH_CAP, details.getAuthentication());
            templateModel.put(KEY_AUTH, details.getAuthentication());
            templateModel.put(KEY_PROFILE_CAP, details.getProfile());
            templateModel.put(KEY_PROFILE, details.getProfile());
        }
    }

    SiteContext siteContext = SiteContext.getCurrent();
    Configuration siteConfig = siteContext.getConfig();
    Locale locale = LocaleContextHolder.getLocale();
    Object siteContextObject = disableVariableRestrictions?
            siteContext : new SiteContextHashModel(getObjectWrapper());
    TemplateHashModel staticModels = BeansWrapper.getDefaultInstance().getStaticModels();
    TemplateHashModel enumModels = BeansWrapper.getDefaultInstance().getEnumModels();

    templateModel.put(KEY_STATICS_CAP, staticModels);
    templateModel.put(KEY_STATICS, staticModels);
    templateModel.put(KEY_ENUMS_CAP, enumModels);
    templateModel.put(KEY_ENUMS, enumModels);
    templateModel.put(KEY_SITE_CONTEXT_CAP, siteContextObject);
    templateModel.put(KEY_SITE_CONTEXT, siteContextObject);
    templateModel.put(KEY_LOCALE_CAP, locale);
    templateModel.put(KEY_LOCALE, locale);

    if (siteConfig != null) {
        templateModel.put(KEY_SITE_CONFIG, siteConfig);
        templateModel.put(KEY_SITE_CONFIG_CAP, siteConfig);
    }

    templateModel.putAll(model);

    ObjectFactory<SimpleHash> componentModelFactory = new ObjectFactory<SimpleHash>() {
        public SimpleHash getObject() {
            return buildTemplateModel(model, request, response);
        }
    };

    RenderComponentDirective renderComponentDirective = new RenderComponentDirective();
    renderComponentDirective.setSiteItemService(siteItemService);
    renderComponentDirective.setModelFactory(componentModelFactory);
    renderComponentDirective.setTemplateXPathQuery(componentTemplateXPathQuery);
    renderComponentDirective.setTemplateNamePrefix(componentTemplateNamePrefix);
    renderComponentDirective.setTemplateNameSuffix(componentTemplateNameSuffix);
    renderComponentDirective.setIncludeElementName(componentIncludeElementName);
    renderComponentDirective.setComponentElementName(componentEmbeddedElementName);
    renderComponentDirective.setScriptResolver(componentScriptResolver);
    renderComponentDirective.setServletContext(getServletContext());

    ExecuteControllerDirective executeControllerDirective = new ExecuteControllerDirective();
    executeControllerDirective.setServletContext(getServletContext());

    templateModel.put(RENDER_COMPONENT_DIRECTIVE_NAME, renderComponentDirective);
    templateModel.put(EXECUTE_CONTROLLER_DIRECTIVE_NAME, executeControllerDirective);

    return templateModel;
}
 
Example #23
Source File: RenderComponentDirective.java    From engine with GNU General Public License v3.0 4 votes vote down vote up
@Required
public void setModelFactory(ObjectFactory<SimpleHash> modelFactory) {
    this.modelFactory = modelFactory;
}
 
Example #24
Source File: PicoClientModule.java    From mxjc with MIT License 4 votes vote down vote up
@Override
public Set<FileInfo> generate(CGModel cgModel, CGConfig config)
		throws XjcModuleException {
	// freemarker datamodel
	SimpleHash fmModel = this.getFreemarkerModel();
	
	// container for target codes
	Set<FileInfo> targetFileSet = new HashSet<FileInfo>();
	
	info("Generating the Pico client classes...");
	
	if (config.picoPrefix == null) {
		warn("No prefix is provided, it's recommended to add prefix for Pico binding to avoid possible conflict");
	}
	String prefix = config.picoPrefix == null ? "" : config.picoPrefix;
	prefixType(cgModel, prefix);
	
	fmModel.put("group", config.picoServiceGroup);
	
	
	String relativePath = null;
	// generate classes
	info("Generating classes ...");
	for(ClassInfo classInfo : cgModel.getClasses()) {
		this.convertFieldsType(classInfo);
		fmModel.put("superClassImports", this.getSuperClassImports(classInfo));
		fmModel.put("fieldClassImports", this.getFieldImports(classInfo));
		fmModel.put("clazz", classInfo);
		
		relativePath = ClassNameUtil.packageNameToPath(classInfo.getPackageName());
		FileInfo classIntf = this.generateFile(clzIntfTemplate, fmModel, classInfo.getName(), "h", relativePath);
		targetFileSet.add(classIntf);
		FileInfo classImpl = this.generateFile(clzImplTempalte, fmModel, classInfo.getName(), "m", relativePath);
		targetFileSet.add(classImpl);
	}
	
	// generate enums
	info("Generating enums ...");
	for(EnumInfo enumInfo : cgModel.getEnums()) {
		fmModel.put("enum", enumInfo);
		relativePath = ClassNameUtil.packageNameToPath(enumInfo.getPackageName());
		FileInfo enumDec = this.generateFile(enumDeclarationTemplate, fmModel, enumInfo.getName(), "h", relativePath);
		targetFileSet.add(enumDec);
		FileInfo enumDef = this.generateFile(enumDefinitionTemplate, fmModel, enumInfo.getName(), "m", relativePath);
		targetFileSet.add(enumDef);
	}
	
	// generate common header
	info("Generating common header ...");
	fmModel.put("classes", cgModel.getClasses());
	fmModel.put("enums", cgModel.getEnums());
	
	if (relativePath == null) {
		relativePath = "";
	}
	relativePath += File.separator + "common";
	String commonTypeFileName = prefix + "CommonTypes";
	FileInfo commonHeader = this.generateFile(commonHeaderTemplate, fmModel, commonTypeFileName, "h", relativePath);
	targetFileSet.add(commonHeader);
	
	return targetFileSet;
}
 
Example #25
Source File: FormTag.java    From javalite with Apache License 2.0 4 votes vote down vote up
@Override
protected void render(Map params, String body, Writer writer) throws Exception {

    SimpleHash activeweb = (SimpleHash) get("activeweb");
    if(activeweb == null || !(params.containsKey("controller") || activeweb.toMap().containsKey("controller")))
        throw  new ViewException("could not render this form, controller is not found");


    String httpMethod = Convert.toString(params.get("method"));
    if (httpMethod != null) {
        httpMethod = httpMethod.toLowerCase();
    }

    boolean putOrDelete = "put".equals(httpMethod) || "delete".equals(httpMethod);

    String bodyPrefix = "";

    if (CSRF.verificationEnabled() && (putOrDelete || "post".equals(httpMethod))) {
        bodyPrefix = "\n\t<input type='hidden' name='" + CSRF.name() + "' value='" + CSRF.token() + "' />";
    }

    if(putOrDelete){
        bodyPrefix += "\n\t<input type='hidden' name='_method' value='" + httpMethod + "' />";
        httpMethod = "post";
    }

    if(blank(body)){
        body = "&nbsp;";
    }

    TagFactory tf = new TagFactory("form", bodyPrefix + body);

    String action = Convert.toString(params.get("action"));

    Boolean restful = null;

    String controllerPath = Convert.toString(params.get("controller"));
    if (controllerPath == null) {
        controllerPath = activeweb.get("controller").toString();
        restful = ((TemplateBooleanModel)activeweb.get("restful")).getAsBoolean();
    }

    if(restful == null){// using current controller
        AppController controllerInstance = (AppController) Class.forName(
            ControllerFactory.getControllerClassName(controllerPath)
        ).getDeclaredConstructor().newInstance();

        restful = controllerInstance.restful();
    }

    String id = Convert.toString(params.get("id"));

    String formAction = Router.generate(controllerPath, action, id, restful, new HashMap());
    tf.attribute("action", getContextPath() + formAction);

    tf.attribute("method", httpMethod);
    tf.attribute("id", Convert.toString(params.get("html_id")));

    tf.addAttributesExcept(params, "controller", "action", "method", "id", "html_id", "data");
    tf.textAttributes(Convert.toString(params.get("data")));

    tf.write(writer);
}
 
Example #26
Source File: FreeMarkerTag.java    From javalite with Apache License 2.0 4 votes vote down vote up
private SimpleHash getSessionHash(){
    return (SimpleHash)get("session");
}
 
Example #27
Source File: LangFtlUtil.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
public static SimpleHash makeSimpleMap(TemplateHashModel map, TemplateCollectionModel keys, ObjectWrapper objectWrapper) throws TemplateModelException {
    SimpleHash res = new SimpleHash(objectWrapper);
    addToSimpleMap(res, map, LangFtlUtil.toStringSet(keys));
    return res;
}
 
Example #28
Source File: FreeMarkerConfigurationFactory.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * Prepare the FreeMarker Configuration and return it.
 * @return the FreeMarker Configuration object
 * @throws IOException if the config file wasn't found
 * @throws TemplateException on FreeMarker initialization failure
 */
public Configuration createConfiguration() throws IOException, TemplateException {
	Configuration config = newConfiguration();
	Properties props = new Properties();

	// Load config file if specified.
	if (this.configLocation != null) {
		if (logger.isDebugEnabled()) {
			logger.debug("Loading FreeMarker configuration from " + this.configLocation);
		}
		PropertiesLoaderUtils.fillProperties(props, this.configLocation);
	}

	// Merge local properties if specified.
	if (this.freemarkerSettings != null) {
		props.putAll(this.freemarkerSettings);
	}

	// FreeMarker will only accept known keys in its setSettings and
	// setAllSharedVariables methods.
	if (!props.isEmpty()) {
		config.setSettings(props);
	}

	if (!CollectionUtils.isEmpty(this.freemarkerVariables)) {
		config.setAllSharedVariables(new SimpleHash(this.freemarkerVariables, config.getObjectWrapper()));
	}

	if (this.defaultEncoding != null) {
		config.setDefaultEncoding(this.defaultEncoding);
	}

	List<TemplateLoader> templateLoaders = new ArrayList<>(this.templateLoaders);

	// Register template loaders that are supposed to kick in early.
	if (this.preTemplateLoaders != null) {
		templateLoaders.addAll(this.preTemplateLoaders);
	}

	// Register default template loaders.
	if (this.templateLoaderPaths != null) {
		for (String path : this.templateLoaderPaths) {
			templateLoaders.add(getTemplateLoaderForPath(path));
		}
	}
	postProcessTemplateLoaders(templateLoaders);

	// Register template loaders that are supposed to kick in late.
	if (this.postTemplateLoaders != null) {
		templateLoaders.addAll(this.postTemplateLoaders);
	}

	TemplateLoader loader = getAggregateTemplateLoader(templateLoaders);
	if (loader != null) {
		config.setTemplateLoader(loader);
	}

	postProcessConfiguration(config);
	return config;
}
 
Example #29
Source File: LangFtlUtil.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
public static void addToSimpleMap(SimpleHash dest, TemplateHashModel source, Set<String> keys) throws TemplateModelException {
    for(String key : keys) {
        dest.put(key, source.get(key));
    }
}
 
Example #30
Source File: LangFtlUtil.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
public static TemplateHashModelEx makeSimpleMapCopy(Map<?, ?> map, ObjectWrapper objectWrapper) throws TemplateModelException {
    return new SimpleHash(map, objectWrapper);
}