org.apache.velocity.app.VelocityEngine Java Examples

The following examples show how to use org.apache.velocity.app.VelocityEngine. 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: VelocityNonStrictHelper.java    From herd with 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 #2
Source File: SafeConfig.java    From velocity-tools with 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 #3
Source File: Analyzer.java    From osmo with 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 #4
Source File: ParseWithMacroLibsTestCase.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
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 #5
Source File: VelocityParser.java    From ApprovalTests.Java with 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 #6
Source File: VelocityConfigurerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #7
Source File: CucumberITGeneratorByFeature.java    From cucumber-jvm-parallel-plugin with Apache License 2.0 6 votes vote down vote up
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
Source File: SAMLConfig.java    From spring-boot-security-saml-samples with 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 #9
Source File: VelocityConfigurer.java    From spring4-understanding with 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 #10
Source File: VelocityUtil.java    From feiqu-opensource with 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 #11
Source File: PortalEntityProvider.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
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 #12
Source File: StringResourceLoaderRepositoryTestCase.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
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 #13
Source File: VelocityInlineDispatcher.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
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 #14
Source File: ParseWithMacroLibsTestCase.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
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 #15
Source File: VelocityConfigurer.java    From lams with 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 #16
Source File: SchemaWriter.java    From qemu-java with 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 #17
Source File: HTTPArtifactEncoder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructor.
 * 
 * @param engine velocity engine used to construct the POST form
 * @param template ID of velocity template used to construct the POST form
 * @param map artifact map used to store artifact/message bindings
 */
public HTTPArtifactEncoder(VelocityEngine engine, String template, SAMLArtifactMap map) {
    super();
    postEncoding = false;
    velocityEngine = engine;
    velocityTemplateId = template;
    artifactMap = map;
    defaultArtifactType = SAML2ArtifactType0004.TYPE_CODE;
}
 
Example #18
Source File: ScopeTestCase.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
protected void setUpEngine(VelocityEngine engine)
{
    engine.setProperty("a.provide.scope.control", "true");
    engine.setProperty("define.provide.scope.control", "true");
    engine.setProperty("evaluate.provide.scope.control", "true");
    engine.setProperty("foo.provide.scope.control", "true");
    engine.setProperty("macro.provide.scope.control", "true");
    engine.setProperty("template.provide.scope.control", "true");
    engine.setProperty("vm.provide.scope.control", "true");
    engine.setProperty("space.gobbling", "bc");
}
 
Example #19
Source File: MicroServiceTemplateUtil.java    From nh-micro with Apache License 2.0 5 votes vote down vote up
public static String sqlTemplateService(String template,Map paramMap,List placeList){
	VelocityEngine ve = new VelocityEngine();
	ve.addProperty("userdirective", "com.nh.micro.template.vext.MicroSqlReplace");
	ve.init();
	VelocityContext context = new VelocityContext();
	context.put("param", paramMap);
	context.put("placeList", placeList);
	StringWriter writer = new StringWriter();
	ve.evaluate(context, writer, "", template);
	return writer.toString();
}
 
Example #20
Source File: SamlFederationResource.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
private Template getTemplate() {
    Properties props = new Properties();
    props.setProperty("resource.loader", "class");
    props.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    VelocityEngine velocityEngine = new VelocityEngine(props);
    velocityEngine.init();

    return velocityEngine.getTemplate(METADATA_TEMPLATE);
}
 
Example #21
Source File: SpaceGobblingTestCase.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Return and initialize engine
 * @return
 */
private VelocityEngine createEngine(SpaceGobbling mode)
        throws Exception
{
    VelocityEngine ve = new VelocityEngine();
    ve.setProperty(Velocity.RUNTIME_LOG_INSTANCE, log);
    ve.setProperty(RuntimeConstants.RESOURCE_LOADERS, "file");
    ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, TEST_COMPARE_DIR + "/gobbling");
    ve.setProperty(RuntimeConstants.SPACE_GOBBLING, mode.toString());
    ve.init();

    return ve;
}
 
Example #22
Source File: VelocityEngineFactory.java    From scoold with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize a Velocity resource loader for the given VelocityEngine: either a standard Velocity FileResourceLoader
 * or a SpringResourceLoader.
 * <p>
 * Called by {@code createVelocityEngine()}.
 *
 * @param velocityEngine the VelocityEngine to configure
 * @param resourceLoaderPath the path to load Velocity resources from
 * @see #createVelocityEngine()
 */
protected void initVelocityResourceLoader(VelocityEngine velocityEngine, String resourceLoaderPath) {
	if (isPreferFileSystemAccess()) {
		// Try to load via the file system, fall back to SpringResourceLoader
		// (for hot detection of template changes, if possible).
		try {
			StringBuilder resolvedPath = new StringBuilder();
			String[] paths = StringUtils.commaDelimitedListToStringArray(resourceLoaderPath);
			for (int i = 0; i < paths.length; i++) {
				String path = paths[i];
				Resource resource = getResourceLoader().getResource(path);
				File file = resource.getFile();  // will fail if not resolvable in the file system
				if (logger.isDebugEnabled()) {
					logger.debug("Resource loader path [" + path + "] resolved to file [" + file.getAbsolutePath() + "]");
				}
				resolvedPath.append(file.getAbsolutePath());
				if (i < paths.length - 1) {
					resolvedPath.append(',');
				}
			}
			velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADERS, "file");
			velocityEngine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, "true");
			velocityEngine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, resolvedPath.toString());
		} catch (IOException ex) {
			if (logger.isDebugEnabled()) {
				logger.debug("Cannot resolve resource loader path [" + resourceLoaderPath
						+ "] to [java.io.File]: using SpringResourceLoader", ex);
			}
			initSpringResourceLoader(velocityEngine, resourceLoaderPath);
		}
	} else {
		// Always load via SpringResourceLoader
		// (without hot detection of template changes).
		if (logger.isDebugEnabled()) {
			logger.debug("File system access not preferred: using SpringResourceLoader");
		}
		initSpringResourceLoader(velocityEngine, resourceLoaderPath);
	}
}
 
Example #23
Source File: AbstractGenerator.java    From webstart with MIT License 5 votes vote down vote up
private void initVelocity( Properties props )
{
    try
    {
        engine = new VelocityEngine();
        engine.setProperty( "runtime.log.logsystem", new NullLogSystem() );
        engine.init( props );
    }
    catch ( Exception e )
    {
        IllegalArgumentException iae = new IllegalArgumentException( "Could not initialise Velocity" );
        iae.initCause( e );
        throw iae;
    }
}
 
Example #24
Source File: BuiltInEventHandlerTestCase.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Test reporting of invalid syntax
 * @throws Exception
 */
public void testReportNullInvalidReferences() throws Exception
{
    VelocityEngine ve = new VelocityEngine();
    ve.setProperty("event_handler.invalid_references.null","true");
    ReportInvalidReferences reporter = new ReportInvalidReferences();
    ve.init();

    VelocityContext context = new VelocityContext();
    EventCartridge ec = new EventCartridge();
    ec.addEventHandler(reporter);
    ec.attachToContext(context);

    context.put("a1","test");
    context.put("b1","test");
    context.put("n1", null);
    Writer writer = new StringWriter();

    ve.evaluate(context,writer,"test","$a1 $c1 $a1.length() $a1.foobar() $!c1 $n1 $!n1 #if($c1) nop #end");

    List errors = reporter.getInvalidReferences();
    assertEquals(3,errors.size());
    assertEquals("$c1",((InvalidReferenceInfo) errors.get(0)).getInvalidReference());
    assertEquals("$a1.foobar()",((InvalidReferenceInfo) errors.get(1)).getInvalidReference());
    assertEquals("$n1",((InvalidReferenceInfo) errors.get(2)).getInvalidReference());

    log("Caught invalid references (local configuration).");
}
 
Example #25
Source File: HollowUIRouter.java    From hollow with Apache License 2.0 5 votes vote down vote up
protected VelocityEngine initVelocity() {
    VelocityEngine ve = new VelocityEngine();
    ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
    ve.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.SimpleLog4JLogSystem");
    ve.setProperty("runtime.log.logsystem.log4j.category", "velocity");
    ve.setProperty("runtime.log.logsystem.log4j.logger", "velocity");
    ve.init();
    return ve;
}
 
Example #26
Source File: VelocityUtil.java    From j2cl with Apache License 2.0 5 votes vote down vote up
/**
 * Creates and returns a VelocityEngine that will find templates on the
 * classpath.
 */
public static VelocityEngine createEngine() {
  VelocityEngine velocityEngine = new VelocityEngine();
  velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
  velocityEngine.setProperty(
      CLASSPATH_RESOURCE_LOADER_CLASS, ClasspathResourceLoader.class.getName());
  velocityEngine.init();
  return velocityEngine;
}
 
Example #27
Source File: LoadVelocityDemo.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
/**
 * 加载classpath目录下的vm文件
 */
public static void loadByClasspath() {
	System.out.println("========== loadByClasspath ==========");

	Properties p = new Properties();
	p.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
	VelocityEngine ve = new VelocityEngine();
	ve.init(p);
	Template t = ve.getTemplate("template/hello.vm");

	System.out.println(fillTemplate(t));
}
 
Example #28
Source File: VelocityEngineFactory.java    From scoold with Apache License 2.0 5 votes vote down vote up
/**
 * Prepare the VelocityEngine instance and return it.
 *
 * @return the VelocityEngine instance
 * @throws IOException if the config file wasn't found
 * @throws VelocityException on Velocity initialization failure
 */
public VelocityEngine createVelocityEngine() throws IOException, VelocityException {
	VelocityEngine velocityEngine = newVelocityEngine();
	Map<String, Object> props = new HashMap<String, Object>();

	// Load config file if set.
	if (this.configLocation != null) {
		if (logger.isInfoEnabled()) {
			logger.info("Loading Velocity config from [" + this.configLocation + "]");
		}
		CollectionUtils.mergePropertiesIntoMap(PropertiesLoaderUtils.loadProperties(this.configLocation), props);
	}

	// Merge local properties if set.
	if (!this.velocityProperties.isEmpty()) {
		props.putAll(this.velocityProperties);
	}

	// Set a resource loader path, if required.
	if (this.resourceLoaderPath != null) {
		initVelocityResourceLoader(velocityEngine, this.resourceLoaderPath);
	}

	// Apply properties to VelocityEngine.
	for (Map.Entry<String, Object> entry : props.entrySet()) {
		velocityEngine.setProperty(entry.getKey(), entry.getValue());
	}

	postProcessVelocityEngine(velocityEngine);

	// Perform actual initialization.
	velocityEngine.init();

	return velocityEngine;
}
 
Example #29
Source File: ExceptionTestCase.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
public void testDirectiveException()
throws Exception
{
    ve = new VelocityEngine();
    ve.setProperty("userdirective",ExceptionGeneratingDirective.class.getName());
    ve.init();
    assertException(ve,"#Exception() test #end");
}
 
Example #30
Source File: ConversionHandlerTestCase.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Test conversions
 * @param ve
 * @param templateFile template
 * @param outputBaseFileName
 * @throws Exception
 */
private void testConversions(VelocityEngine ve, String templateFile, String outputBaseFileName)
        throws Exception
{
    assureResultsDirectoryExists(RESULT_DIR);

    FileOutputStream fos = new FileOutputStream (getFileName(
            RESULT_DIR, outputBaseFileName, RESULT_FILE_EXT));

    VelocityContext context = createContext();

    Writer writer = new BufferedWriter(new OutputStreamWriter(fos));

    log.setEnabledLevel(TestLogger.LOG_LEVEL_ERROR);

    Template template = ve.getTemplate(templateFile);
    template.merge(context, writer);

    /**
     * Write to the file
     */
    writer.flush();
    writer.close();

    if (!isMatch(RESULT_DIR, COMPARE_DIR, outputBaseFileName,
            RESULT_FILE_EXT,CMP_FILE_EXT))
    {
        String result = getFileContents(RESULT_DIR, outputBaseFileName, RESULT_FILE_EXT);
        String compare = getFileContents(COMPARE_DIR, outputBaseFileName, CMP_FILE_EXT);

        String msg = "Processed template did not match expected output\n"+
            "-----Result-----\n"+ result +
            "----Expected----\n"+ compare +
            "----------------";

        fail(msg);
    }
}