Java Code Examples for org.apache.velocity.app.VelocityEngine

The following examples show how to use org.apache.velocity.app.VelocityEngine. These examples are extracted from open source projects. 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 Project: qemu-java   Source File: SchemaWriter.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Nonnull
private static VelocityEngine newVelocityEngine() {
    VelocityEngine engine = new VelocityEngine();
    engine
            .setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM_CLASS, CommonsLogLogChute.class
            .getName());
    // engine.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM_CLASS, SystemLogChute.class.getName());
    engine.setProperty(VelocityEngine.RESOURCE_LOADER,
            "classpath");
    engine.setProperty(
            "classpath.resource.loader.class", ClasspathResourceLoader.class
            .getName());
    // engine.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_CACHE, "true");
    // engine.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, "velocity/");
    engine.init();
    return engine;
}
 
Example 2
Source Project: feiqu-opensource   Source File: VelocityUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 根据模板生成文件
 * @param inputVmFilePath 模板路径
 * @param outputFilePath 输出文件路径
 * @param context
 * @throws Exception
 */
public static void generate(String inputVmFilePath, String outputFilePath, VelocityContext context) throws Exception {
	try {
		Properties properties = new Properties();
		String path = getPath(inputVmFilePath);
		properties.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, path);
		Velocity.init(properties);
		//VelocityEngine engine = new VelocityEngine();
		Template template = Velocity.getTemplate(getFile(inputVmFilePath), "utf-8");
		File outputFile = new File(outputFilePath);
		FileWriterWithEncoding writer = new FileWriterWithEncoding(outputFile, "utf-8");
		template.merge(context, writer);
		writer.close();
	} catch (Exception ex) {
		throw ex;
	}
}
 
Example 3
Source Project: herd   Source File: VelocityNonStrictHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Wrapper for {@link Velocity#evaluate(org.apache.velocity.context.Context, java.io.Writer, String, java.io.InputStream)}
 *
 * @param templateReader A {@link Reader} of a Velocity template.
 * @param variables Variables to add to context
 * @param logTag The log tag
 * @param strict The strict boolean flag determines whether or not to require runtime references or not during velocity evaluate.
 *
 * @return {@link String} result of evaluation
 */
private String evaluate(Reader templateReader, Map<String, Object> variables, String logTag, boolean strict)
{
    /*  Get and initialize a velocity engine  */
    VelocityEngine velocityEngine = new VelocityEngine();
    velocityEngine.setProperty(RuntimeConstants.RUNTIME_REFERENCES_STRICT, strict);
    velocityEngine.init();

    VelocityContext velocityContext = new VelocityContext(variables);
    StringWriter writer = new StringWriter();
    if (!velocityEngine.evaluate(velocityContext, writer, logTag, templateReader))
    {
        // Although the velocityEngine.evaluate method's Javadoc states that it will return false to indicate a failure when the template couldn't be
        // processed and to see the Velocity log messages for more details, upon examining the method's implementation, it doesn't look like
        // it will ever return false. Instead, other RuntimeExceptions will be thrown (e.g. ParseErrorException).
        // Nonetheless, we'll leave this checking here to honor the method's contract in case the implementation changes in the future.
        // Having said that, there will be no way to JUnit test this flow.
        throw new IllegalStateException("Error evaluating velocity template. See velocity log message for more details.");
    }
    return writer.toString();
}
 
Example 4
Source Project: ApprovalTests.Java   Source File: VelocityParser.java    License: Apache License 2.0 6 votes vote down vote up
public static Writer parse(String template, Properties props, ContextAware process[], Writer out)
{
  try
  {
    props.put("directive.foreach.counter.initial.value", "0");
    props.put(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, NullLogChute.class.getName());
    VelocityEngine engine = initializeEngine(props);
    VelocityContext context = new VelocityContext();
    Template velocityTemplate = engine.getTemplate(template);
    for (int i = 0; i < process.length; i++)
    {
      if (process[i] != null)
        process[i].setupContext(context);
    }
    velocityTemplate.merge(context, out);
    return out;
  }
  catch (Exception e)
  {
    throw ObjectUtils.throwAsError(e);
  }
}
 
Example 5
Source Project: osmo   Source File: Analyzer.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Create the string for the report to write to disk about found invariants.
 * 
 * @return The report to write.
 */
public String createReport() {
  if (state.getTests().size() == 0) return "No failing tests found.";
  VelocityEngine velocity = new VelocityEngine();
  VelocityContext vc = new VelocityContext();
  vc.put("testCount", state.getTestCount());
  vc.put("lengths", state.getLengths());
  vc.put("finalLength", state.getTests().get(0).getAllStepNames().size());
  vc.put("shortests", state.getTests().size());
  vc.put("stepCounts", invariants.getUsedStepCounts());
  vc.put("missingSteps", invariants.getMissingSteps());
  vc.put("finalSteps", invariants.getLastSteps());
  vc.put("s_precedences", invariants.getStrictPrecedences());
  vc.put("f_precedences", invariants.getFlexPrecedences());
  vc.put("sequences", invariants.getSequences());

  velocity.setProperty("resource.loader", "class");
  velocity.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
  StringWriter sw = new StringWriter();
  velocity.mergeTemplate("osmo/tester/optimizer/reducer/template.vm", "UTF8", vc, sw);
  return sw.toString();
}
 
Example 6
Source Project: lams   Source File: VelocityConfigurer.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Provides a ClasspathResourceLoader in addition to any default or user-defined
 * loader in order to load the spring Velocity macros from the class path.
 * @see org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
 */
@Override
protected void postProcessVelocityEngine(VelocityEngine velocityEngine) {
	velocityEngine.setApplicationAttribute(ServletContext.class.getName(), this.servletContext);
	velocityEngine.setProperty(
			SPRING_MACRO_RESOURCE_LOADER_CLASS, ClasspathResourceLoader.class.getName());
	velocityEngine.addProperty(
			VelocityEngine.RESOURCE_LOADER, SPRING_MACRO_RESOURCE_LOADER_NAME);
	velocityEngine.addProperty(
			VelocityEngine.VM_LIBRARY, SPRING_MACRO_LIBRARY);

	if (logger.isInfoEnabled()) {
		logger.info("ClasspathResourceLoader with name '" + SPRING_MACRO_RESOURCE_LOADER_NAME +
				"' added to configured VelocityEngine");
	}
}
 
Example 7
private void initTemplate() {
    final Properties props = new Properties();
    props.put("resource.loader", "class");
    props.put("class.resource.loader.class",
            "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    final String name;
    if (StringUtils.isNotBlank(config.getCustomVmTemplate())) {
        // Look for custom template on the classpath or as a relative file path
        props.put("resource.loader", "class, file");
        props.put("file.resource.loader.path", config.getProjectBasedir().getAbsolutePath());
        name = config.getCustomVmTemplate();
    } else if (config.useTestNG()) {
        name = "cucumber-testng-runner.java.vm";
    } else {
        name = "cucumber-junit-runner.java.vm";
    }
    final VelocityEngine engine = new VelocityEngine(props);
    engine.init();
    velocityTemplate = engine.getTemplate(name, config.getEncoding());
}
 
Example 8
@Test
@SuppressWarnings("deprecation")
public void velocityConfigurerWithCsvPathAndNonFileAccess() throws IOException, VelocityException {
	VelocityConfigurer vc = new VelocityConfigurer();
	vc.setResourceLoaderPath("file:/mydir,file:/yourdir");
	vc.setResourceLoader(new ResourceLoader() {
		@Override
		public Resource getResource(String location) {
			if ("file:/yourdir/test".equals(location)) {
				return new DescriptiveResource("");
			}
			return new ByteArrayResource("test".getBytes(), "test");
		}
		@Override
		public ClassLoader getClassLoader() {
			return getClass().getClassLoader();
		}
	});
	vc.setPreferFileSystemAccess(false);
	vc.afterPropertiesSet();
	assertThat(vc.createVelocityEngine(), instanceOf(VelocityEngine.class));
	VelocityEngine ve = vc.createVelocityEngine();
	assertEquals("test", VelocityEngineUtils.mergeTemplateIntoString(ve, "test", Collections.emptyMap()));
}
 
Example 9
Source Project: velocity-tools   Source File: SafeConfig.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Initialize logger. Default implementation will try to get a Velocity engine
 * from the configuration parameters, then try to use either the configured logger
 * instance, or the configured logger name suffixed by 'tools.&lt;key&gt;'
 * @param params configuration parameters
 */
protected void initLogger(ValueParser params)
{
    String loggerName = params.getString(LOGGER_NAME_KEY);
    if (loggerName != null)
    {
        log = LoggerFactory.getLogger(loggerName);
    }
    else
    {
        boolean useClassLogger = params.getBoolean(USE_CLASS_LOGGER_KEY, false);
        if (!useClassLogger)
        {
            VelocityEngine engine = (VelocityEngine) params.get(ToolContext.ENGINE_KEY);
            String key = (String) params.get(ToolContext.TOOLKEY_KEY);
            if (engine != null && key != null)
            {
                log = ConfigurationUtils.getLog(engine, "tools." + key);
            }
        }
        if (log == null)
        {
            log = LoggerFactory.getLogger(getClass());
        }
    }
}
 
Example 10
protected VelocityEngine newStringEngine(String repoName, boolean isStatic)
{
    VelocityEngine engine = new VelocityEngine();
    TestLogger logger = new TestLogger();
    engine.setProperty(Velocity.RESOURCE_LOADERS, "string");
    engine.addProperty("string.resource.loader.class", StringResourceLoader.class.getName());
    if (repoName != null)
    {
        engine.addProperty("string.resource.loader.repository.name", repoName);
    }
    if (!isStatic)
    {
        engine.addProperty("string.resource.loader.repository.static", "false");
    }
    engine.addProperty("string.resource.loader.modificationCheckInterval", "1");
    engine.setProperty(Velocity.RUNTIME_LOG_INSTANCE, logger);
    return engine;
}
 
Example 11
public void init(ServletContext context) throws ServletException
{
	inlineMacros = MACROS;
	try
	{
		vengine = new VelocityEngine();

		vengine.setApplicationAttribute(ServletContext.class.getName(), context);
		vengine.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM, new SLF4JLogChute());

		Properties p = new Properties();
		p.load(this.getClass().getResourceAsStream("rwikivelocity.config"));
		vengine.init(p);
		vengine.getTemplate(inlineMacros);

	}
	catch (Exception ex)
	{
		throw new ServletException(ex);
	}
}
 
Example 12
public void testParseMacroGlobalCacheOn()
throws Exception
{
    /*
     *  global scope, cache on
     */
    VelocityEngine ve = createEngine(true, false);

    // render twice to make sure there is no difference with cached templates
    testParseMacro(ve, "vm_library1.vm", "parseMacro1_3", false);
    testParseMacro(ve, "vm_library1.vm", "parseMacro1_3", false);

    // run again with different macro library
    testParseMacro(ve, "vm_library2.vm", "parseMacro1_3b", false);
    testParseMacro(ve, "vm_library2.vm", "parseMacro1_3b", false);
}
 
Example 13
public void testParseMacroLocalCacheOn()
throws Exception
{
    /*
     *  local scope, cache on
     */
    VelocityEngine ve = createEngine(true, true);

    // render twice to make sure there is no difference with cached templates
    testParseMacro(ve, "vm_library1.vm", "parseMacro1_1", false);
    testParseMacro(ve, "vm_library1.vm", "parseMacro1_1", false);

    // run again with different macro library
    testParseMacro(ve, "vm_library2.vm", "parseMacro1_1b", false);
    testParseMacro(ve, "vm_library2.vm", "parseMacro1_1b", false);
}
 
Example 14
Source Project: spring4-understanding   Source File: VelocityConfigurer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Provides a ClasspathResourceLoader in addition to any default or user-defined
 * loader in order to load the spring Velocity macros from the class path.
 * @see org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
 */
@Override
protected void postProcessVelocityEngine(VelocityEngine velocityEngine) {
	velocityEngine.setApplicationAttribute(ServletContext.class.getName(), this.servletContext);
	velocityEngine.setProperty(
			SPRING_MACRO_RESOURCE_LOADER_CLASS, ClasspathResourceLoader.class.getName());
	velocityEngine.addProperty(
			VelocityEngine.RESOURCE_LOADER, SPRING_MACRO_RESOURCE_LOADER_NAME);
	velocityEngine.addProperty(
			VelocityEngine.VM_LIBRARY, SPRING_MACRO_LIBRARY);

	if (logger.isInfoEnabled()) {
		logger.info("ClasspathResourceLoader with name '" + SPRING_MACRO_RESOURCE_LOADER_NAME +
				"' added to configured VelocityEngine");
	}
}
 
Example 15
public void init() {

		VelocityEngine ve = new VelocityEngine();
		ve.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM, new SLF4JLogChute());

		ve.setProperty("resource.loader", "class");
		ve.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
		// No logging. (If you want to log, you need to set an approrpriate directory in an approrpriate
		// velocity.properties file, or the log will be created in the directory in which tomcat is started, or
		// throw an error if it can't create/write in that directory.)
		ve.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogSystem");
		try {
			ve.init();
			formattedProfileTemplate = ve.getTemplate("org/sakaiproject/portal/entityprovider/profile-popup.vm");
		} catch (Exception e) {
			log.error("Failed to load profile-popup.vm", e);
		}
	}
 
Example 16
Source Project: spring-boot-security-saml-samples   Source File: SAMLConfig.java    License: MIT License 6 votes vote down vote up
@Bean
public SAMLProcessorImpl processor() {
    HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
    ArtifactResolutionProfileImpl artifactResolutionProfile = new ArtifactResolutionProfileImpl(httpClient);
    HTTPSOAP11Binding soapBinding = new HTTPSOAP11Binding(parserPool());
    artifactResolutionProfile.setProcessor(new SAMLProcessorImpl(soapBinding));

    VelocityEngine velocityEngine = VelocityFactory.getEngine();
    Collection<SAMLBinding> bindings = new ArrayList<>();
    bindings.add(new HTTPRedirectDeflateBinding(parserPool()));
    bindings.add(new HTTPPostBinding(parserPool(), velocityEngine));
    bindings.add(new HTTPArtifactBinding(parserPool(), velocityEngine, artifactResolutionProfile));
    bindings.add(new HTTPSOAP11Binding(parserPool()));
    bindings.add(new HTTPPAOS11Binding(parserPool()));
    return new SAMLProcessorImpl(bindings);
}
 
Example 17
Source Project: das   Source File: TransController.java    License: Apache License 2.0 5 votes vote down vote up
private String mergeTemplate(Context context) {
    java.util.Properties property = new java.util.Properties();
    property.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM_CLASS,
            "org.apache.velocity.runtime.log.NullLogChute");
    property.setProperty(VelocityEngine.RESOURCE_LOADER, "class");
    property.setProperty("class.resource.loader.class",
            "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    Velocity.init(property);

    StringWriter writer = new StringWriter();
    Velocity.mergeTemplate("templates/convert/convert1.tpl", "UTF-8", context, writer);
    return  writer.toString();
}
 
Example 18
@Test
public void velocityConfigurerWithCsvPath() throws IOException, VelocityException {
	VelocityConfigurer vc = new VelocityConfigurer();
	vc.setResourceLoaderPath("file:/mydir,file:/yourdir");
	vc.afterPropertiesSet();
	assertThat(vc.createVelocityEngine(), instanceOf(VelocityEngine.class));
	VelocityEngine ve = vc.createVelocityEngine();
	Vector<String> paths = new Vector<>();
	paths.add(new File("/mydir").getAbsolutePath());
	paths.add(new File("/yourdir").getAbsolutePath());
	assertEquals(paths, ve.getProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH));
}
 
Example 19
protected String generateHTML(final ITestContext tc, final boolean envt, final ISuite suite,
        final ITestContext ctx) {

    final StringBuffer res = new StringBuffer();
    try {
        final VelocityEngine ve = new VelocityEngine();
        ve.setProperty("resource.loader", "class");
        ve.setProperty("class.resource.loader.class",
            "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        ve.init();

        if (envt) {
            if (tc.getFailedConfigurations().getAllResults().size() > 0) {
                generatePanel(ve, tc.getFailedConfigurations(), res, "failed", suite, ctx, envt);
            }

            generatePanel(ve, failedTests.get(tc.getName()), res, "failed", suite, ctx, envt);
            if (tc.getFailedConfigurations().getAllResults().size() > 0) {
                generatePanel(ve, tc.getSkippedConfigurations(), res, "skipped", suite, ctx, envt);
            }

            generatePanel(ve, skippedTests.get(tc.getName()), res, "skipped", suite, ctx, envt);
            generatePanel(ve, tc.getPassedTests(), res, "passed", suite, ctx, envt);
        } else {
            generatePanel(ve, failedTests.get(tc.getName()), res, "failed", suite, ctx, envt);
            generatePanel(ve, skippedTests.get(tc.getName()), res, "skipped", suite, ctx, envt);
            generatePanel(ve, tc.getPassedTests(), res, "passed", suite, ctx, envt);
        }
    } catch (final Exception e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }

    return res.toString();
}
 
Example 20
Source Project: erp-framework   Source File: Generator.java    License: MIT License 5 votes vote down vote up
public void generateServiceImpl(String targetDir, Table table) {
    VelocityEngine velocityEngine = createVelocityEngine();
    VelocityContext context = createContext(table);
    Writer writer = createWriter(targetDir, configure.getServiceImplPackage()
            .replace(".", "/") + "/" + table.getBeanName() + "ServiceImpl.java");
    Template t = velocityEngine.getTemplate("serviceImplTemplate.vm");

    t.merge(context, writer);
    flushWriter(writer);
}
 
Example 21
@Override
public void init() throws Exception {
	try {
		Velocity.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM, this);
		Velocity.init();
	} catch (Throwable t) {
		_logger.error("Error initializing the VelocityEngine", t);
		//ApsSystemUtils.logThrowable(t, this, "init");
		throw new ApsSystemException("Error initializing the VelocityEngine", t);
	}
	_logger.debug("{} ready.", this.getName());
}
 
Example 22
Source Project: BigDataPlatform   Source File: TmpBuilder.java    License: GNU General Public License v3.0 5 votes vote down vote up
public TmpBuilder(InputParams ip) {
    this.ip = ip;
    ve = new VelocityEngine();
    ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
    ve.init();
}
 
Example 23
/**
 * Constructor
 *
 * @param velocityEngine The velocity engine, must not be null.
 */
public VelocityTemplateEngine(VelocityEngine velocityEngine) {
    if (velocityEngine == null) {
        throw new IllegalArgumentException("velocityEngine must not be null");
    }
    this.velocityEngine = velocityEngine;
}
 
Example 24
Source Project: web-flash   Source File: Generator.java    License: MIT License 5 votes vote down vote up
public String generateCode(String packageName, String templatePath) throws IOException {
    VelocityContext context = new VelocityContext();
    context.put("table", table);
    context.put("packageName", packageName);
    StringWriter writer = new StringWriter();

    String template = new String(Streams.readBytes(ClassLoader.getSystemResourceAsStream(templatePath)),
                                 Charset.forName("utf8"));
    VelocityEngine engine = new VelocityEngine();
    engine.setProperty("runtime.references.strict", false);
    engine.init();
    engine.evaluate(context, writer, "generator", template);
    return writer.toString();

}
 
Example 25
Source Project: kvf-admin   Source File: VelocityKit.java    License: MIT License 5 votes vote down vote up
private static void newEngine() {
    VelocityEngine ve = new VelocityEngine();
    ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
    ve.init();
    velocityEngine = ve;
}
 
Example 26
Source Project: velocity-engine   Source File: ExceptionTestCase.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Note - this is the one case where RuntimeExceptions *are not* passed through
 * verbatim.
 * @throws Exception
 */
public void testMethodExceptionEventHandlerException()
throws Exception
{
    ve = new VelocityEngine();
    ve.setProperty(RuntimeConstants.EVENTHANDLER_METHODEXCEPTION,ExceptionGeneratingEventHandler.class.getName());
    ve.init();
    Context context = new VelocityContext();
    context.put ("test",new TestProvider());
    assertMethodInvocationException(ve,context,"$test.getThrow()");
    assertMethodInvocationException(ve,context,"$test.throw");
}
 
Example 27
Source Project: velocity-engine   Source File: ExceptionTestCase.java    License: Apache License 2.0 5 votes vote down vote up
public void assertException(VelocityEngine ve)
throws Exception
{
    Context context = new VelocityContext();
    context.put ("test","test");
    assertException(ve,context,"this is a $test");
}
 
Example 28
Source Project: sundrio   Source File: CodeGeneratorContext.java    License: Apache License 2.0 5 votes vote down vote up
public CodeGeneratorContext(VelocityEngine velocityEngine, VelocityContext velocityContext) {
    this.velocityEngine = velocityEngine;
    this.velocityContext = velocityContext;

    this.velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "string");
    this.velocityEngine.setProperty("string.resource.loader.class", StringResourceLoader.class.getName());
    //We are going to use shading so we need to make sure that the following configuration will be shade friendly...
    this.velocityEngine.setProperty(RuntimeConstants.RESOURCE_MANAGER_CLASS, ResourceManagerImpl.class.getName());
    this.velocityEngine.setProperty(RuntimeConstants.RESOURCE_MANAGER_CACHE_CLASS, ResourceCacheImpl.class.getName());
    this.velocityEngine.setProperty(RuntimeConstants.PARSER_POOL_CLASS, ParserPoolImpl.class.getName());
    this.velocityEngine.setProperty(RuntimeConstants.UBERSPECT_CLASSNAME, UberspectImpl.class.getName());
    this.velocityEngine.setProperty("runtime.log.logsystem.class", SystemLogChute.class.getName());

    ClassLoader current = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(VelocityEngine.class.getClassLoader());
        this.velocityEngine.init();

        //Load standard directives
        this.velocityEngine.loadDirective(ClassDirective.class.getCanonicalName());
        this.velocityEngine.loadDirective(MethodDirective.class.getCanonicalName());
        this.velocityEngine.loadDirective(FieldDirective.class.getCanonicalName());
        //Load utility directives
        this.velocityEngine.loadDirective(PluralizeDirective.class.getCanonicalName());
        this.velocityEngine.loadDirective(SingularizeDirective.class.getCanonicalName());
    } finally {
        Thread.currentThread().setContextClassLoader(current);
    }
}
 
Example 29
private MailMessage composeMailMessage(final MailMessageTemplate mailMessageTemplate, final User respondent,
        final String surveyLinkToken) {

    Map<String, Object> model = new HashMap<>();
    model.put("lastname", StringUtils.defaultIfBlank(respondent.getSurname(), ""));
    model.put("firstname", StringUtils.defaultIfBlank(respondent.getGivenNames(), ""));
    model.put("gender", respondent.getGender());
    model.put("link", "http://localhost:8080/questionaires-ui/token=" + surveyLinkToken);

    Language preferredLanguage = respondent.getPreferredLanguage();

    StringBuilder templateLocation = new StringBuilder().append(mailMessageTemplate.getId());
    if (preferredLanguage != null) {
        templateLocation.append("/");
        templateLocation.append(preferredLanguage);
    }
    VelocityEngine velocityEngine = velocityFactory.getObject();

    String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templateLocation.toString(), "UTF-8",
            model);

    MailMessageTemplateLanguageSettings languageSettings = mailMessageTemplate.getLanguageSettings();
    if (preferredLanguage != null && !preferredLanguage.equals(mailMessageTemplate.getLanguage())) {
        MailMessageTemplateTranslation preferedTranslation = mailMessageTemplate.getTranslations().get(
                preferredLanguage);
        if (preferedTranslation != null) {
            languageSettings = preferedTranslation.getLanguageSettings();
        }
    }
    MailMessage mailMessage = MailMessage.with().subject(languageSettings.getSubject()).to(respondent.getEmail())
            .replyTo(mailMessageTemplate.getReplyTo()).from(mailMessageTemplate.getFromAddress()).text(body)
            .build();
    return mailMessage;
}
 
Example 30
@Test
public void testVelocityViewResolverWithToolboxSubclass() throws Exception {
	VelocityConfig vc = new VelocityConfig() {
		@Override
		public VelocityEngine getVelocityEngine() {
			TestVelocityEngine ve = new TestVelocityEngine();
			ve.addTemplate("prefix_test_suffix", new Template());
			ve.addTemplate(VelocityLayoutView.DEFAULT_LAYOUT_URL, new Template());
			return ve;
		}
	};

	StaticWebApplicationContext wac = new StaticWebApplicationContext();
	wac.getBeanFactory().registerSingleton("configurer", vc);
	wac.refresh();

	String toolbox = "org/springframework/web/servlet/view/velocity/toolbox.xml";

	VelocityViewResolver vr = new VelocityViewResolver();
	vr.setViewClass(VelocityLayoutView.class);
	vr.setPrefix("prefix_");
	vr.setSuffix("_suffix");
	vr.setToolboxConfigLocation(toolbox);
	vr.setApplicationContext(wac);

	View view = vr.resolveViewName("test", Locale.CANADA);
	assertEquals("Correct view class", VelocityLayoutView.class, view.getClass());
	assertEquals("Correct URL", "prefix_test_suffix", ((VelocityView) view).getUrl());
	assertEquals("Correct toolbox", toolbox, ((VelocityToolboxView) view).getToolboxConfigLocation());
}