Java Code Examples for org.apache.velocity.runtime.RuntimeConstants

The following examples show how to use org.apache.velocity.runtime.RuntimeConstants. 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
public void setUp()
    throws Exception
{
    assureResultsDirectoryExists(RESULTS_DIR);

    // use Velocity.setProperty (instead of properties file) so that we can use actual instance of log
    Velocity.reset();
    Velocity.setProperty(RuntimeConstants.RESOURCE_LOADERS,"file");
    Velocity.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, FILE_RESOURCE_LOADER_PATH );
    Velocity.setProperty(RuntimeConstants.RUNTIME_LOG_REFERENCE_LOG_INVALID,"true");

    // actual instance of logger
    logger.setEnabledLevel(TestLogger.LOG_LEVEL_DEBUG);
    Velocity.setProperty(RuntimeConstants.RUNTIME_LOG_INSTANCE, logger);
    Velocity.init();
}
 
Example 2
Source Project: testgrid   Source File: ScenarioExecutor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This method prepares the content of the run-scenario script which will include complete shell commands including
 * script file names.
 * @param  files sorted list of files needs to be added to the script
 * @return content of the run-scenario.sh script
 */
private String prepareScriptContent(List<String> files) {
        VelocityEngine velocityEngine = new VelocityEngine();
        //Set velocity class loader as to refer templates from resources directory.
        velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());

        velocityEngine.init();
        VelocityContext context = new VelocityContext();
        context.put("scripts", files);

        Template template = velocityEngine.getTemplate(RUN_SCENARIO_SCRIPT_TEMPLATE);
        StringWriter writer = new StringWriter();
        template.merge(context, writer);
        return writer.toString();
}
 
Example 3
Source Project: scoold   Source File: ScooldServer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @return Velocity config bean
 */
@Bean
public VelocityConfigurer velocityConfigBean() {
	Properties velocityProperties = new Properties();
	velocityProperties.put(RuntimeConstants.VM_LIBRARY, "macro.vm");
	velocityProperties.put(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, Config.IN_PRODUCTION);
	velocityProperties.put(RuntimeConstants.VM_LIBRARY_AUTORELOAD, !Config.IN_PRODUCTION);
	velocityProperties.put(RuntimeConstants.VM_PERM_ALLOW_INLINE_REPLACE_GLOBAL, true);
	velocityProperties.put(RuntimeConstants.EVENTHANDLER_REFERENCEINSERTION,
			"org.apache.velocity.app.event.implement.EscapeHtmlReference");
	velocityProperties.put("eventhandler.escape.html.match", "^((?!_).)+$");

	VelocityConfigurer vc = new VelocityConfigurer();
	vc.setVelocityProperties(velocityProperties);
	vc.setResourceLoaderPath("classpath:templates/");
	vc.setPreferFileSystemAccess(!Config.IN_PRODUCTION); // use SpringResourceLoader only in production
	return vc;
}
 
Example 4
Source Project: velocity-engine   Source File: ConversionHandlerTestCase.java    License: Apache License 2.0 6 votes vote down vote up
public void testCustomConversionHandlerInstance()
{
    RuntimeInstance ve = new RuntimeInstance();
    ve.setProperty( Velocity.VM_PERM_INLINE_LOCAL, Boolean.TRUE);
    ve.setProperty(Velocity.RUNTIME_LOG_INSTANCE, log);
    ve.setProperty(RuntimeConstants.RESOURCE_LOADERS, "file");
    ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, TEST_COMPARE_DIR + "/conversion");
    ve.setProperty(RuntimeConstants.CONVERSION_HANDLER_INSTANCE, new MyCustomConverter());
    ve.init();
    Uberspect uberspect = ve.getUberspect();
    assertTrue(uberspect instanceof UberspectImpl);
    UberspectImpl ui = (UberspectImpl)uberspect;
    TypeConversionHandler ch = ui.getConversionHandler();
    assertTrue(ch != null);
    assertTrue(ch instanceof MyCustomConverter);
    VelocityContext context = new VelocityContext();
    context.put("obj", new Obj());
    Writer writer = new StringWriter();
    ve.evaluate(context, writer, "test", "$obj.objectString(1.0)");
    assertEquals("String ok: foo", writer.toString());
}
 
Example 5
Source Project: velocity-engine   Source File: ASTIdentifier.java    License: Apache License 2.0 6 votes vote down vote up
/**
 *  simple init - don't do anything that is context specific.
 *  just get what we need from the AST, which is static.
 * @param context
 * @param data
 * @return The data object.
 * @throws TemplateInitException
 */
public  Object init(InternalContextAdapter context, Object data)
    throws TemplateInitException
{
    super.init(context, data);

    identifier = rsvc.useStringInterning() ? getFirstToken().image.intern() : getFirstToken().image;

    uberInfo = new Info(getTemplateName(), getLine(), getColumn());

    strictRef = rsvc.getBoolean(RuntimeConstants.RUNTIME_REFERENCES_STRICT, false);

    saveTokenImages();
    cleanupParserAndTokens();

    return data;
}
 
Example 6
public void setUp()
        throws Exception
{

    ResourceLoader rl = new FileResourceLoader();

    // pass in an instance to Velocity
    Velocity.reset();
    Velocity.setProperty( "resource.loader", "testrl" );
    Velocity.setProperty( "testrl.resource.loader.instance", rl );
    Velocity.setProperty( "testrl.resource.loader.path", FILE_RESOURCE_LOADER_PATH );

    // actual instance of logger
    logger.on();
    Velocity.setProperty(RuntimeConstants.RUNTIME_LOG_INSTANCE, logger);
    Velocity.setProperty("runtime.log.logsystem.test.level", "debug");

    Velocity.init();
}
 
Example 7
Source Project: eagle   Source File: VelocityTemplateParser.java    License: Apache License 2.0 6 votes vote down vote up
public VelocityTemplateParser(String templateString) throws ParseErrorException {
    VelocityEngine engine = new VelocityEngine();
    engine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.Log4JLogChute");
    engine.setProperty("runtime.log.logsystem.log4j.logger", LOG.getName());
    engine.setProperty(Velocity.RESOURCE_LOADER, "string");
    engine.addProperty("string.resource.loader.class", StringResourceLoader.class.getName());
    engine.addProperty("string.resource.loader.repository.static", "false");
    engine.addProperty("runtime.references.strict", "true");
    engine.init();
    StringResourceRepository resourceRepository = (StringResourceRepository) engine.getApplicationAttribute(StringResourceLoader.REPOSITORY_NAME_DEFAULT);
    resourceRepository.putStringResource(TEMPLATE_NAME, templateString);
    template = engine.getTemplate(TEMPLATE_NAME);
    ASTprocess data = (ASTprocess) template.getData();
    visitor = new ParserNodeVisitor();
    data.jjtAccept(visitor, null);
}
 
Example 8
Source Project: velocity-engine   Source File: ExceptionTestCase.java    License: Apache License 2.0 6 votes vote down vote up
public void testResourceLoaderException()
throws Exception
{
    ve = new VelocityEngine();
    ve.setProperty(RuntimeConstants.RESOURCE_LOADERS,"except");
    ve.setProperty("except.resource.loader.class",ExceptionGeneratingResourceLoader.class.getName());
    try
    {
        ve.init();  // tries to get the macro file
        ve.getTemplate("test.txt");
        fail("Should have thrown RuntimeException");
    }
    catch (RuntimeException E)
    {
        // do nothing
    }
}
 
Example 9
Source Project: velocity-engine   Source File: SimpleNode.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <p>Dumps nodes tree on System.out.</p>
 * <p>Override {@link #dump(String, PrintWriter)} if you want to customize
 * how the node dumps out its children.
 *
 * @param prefix display prefix
 * @param out output print stream
 */
public final void dump(String prefix, PrintStream out)
{
    Charset charset = null;
    if (rsvc != null) /* may be null if node isn't yet initialized */
    {
        String encoding = rsvc.getString(RuntimeConstants.INPUT_ENCODING);
        try
        {
            charset = Charset.forName(encoding);
        }
        catch (Exception e) {}
    }
    if (charset == null)
    {
        charset = Charset.defaultCharset();
    }
    PrintWriter pw = new PrintWriter(new OutputStreamWriter(out, charset));
    dump(prefix, pw);
    pw.flush();
}
 
Example 10
/**
 * Return and initialize engine
 * @return
 */
private VelocityEngine createEngine(boolean cache, boolean local)
throws Exception
{
    VelocityEngine ve = new VelocityEngine();
    ve.setProperty( Velocity.VM_PERM_INLINE_LOCAL, Boolean.TRUE);
    ve.setProperty("velocimacro.permissions.allow.inline.to.replace.global",
        local);
    ve.setProperty("file.resource.loader.cache", cache);
    ve.setProperty(
            Velocity.RUNTIME_LOG_INSTANCE, new TestLogger());
    ve.setProperty(RuntimeConstants.RESOURCE_LOADERS, "file");
    ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH,
            TEST_COMPARE_DIR + "/parsemacros");
    ve.init();

    return ve;
}
 
Example 11
Source Project: carbon-apimgt   Source File: RESTToSOAPMsgTemplate.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * gets out sequence for the soap operation
 *
 * @return out sequence for the converted soap operation
 */
public String getMappingOutSequence() {

    ConfigContext configcontext = new SOAPToRESTConfigContext();
    StringWriter writer = new StringWriter();
    try {
        VelocityContext context = configcontext.getContext();
        context.internalGetKeys();

        VelocityEngine velocityengine = new VelocityEngine();
        if (!SOAPToRESTConstants.Template.NOT_DEFINED.equalsIgnoreCase(getVelocityLogger())) {
            velocityengine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,
                    CommonsLogLogChute.class.getName());
            velocityengine.setProperty(VelocityEngine.RESOURCE_LOADER, "classpath");
            velocityengine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        }

        velocityengine.init();
        org.apache.velocity.Template template = velocityengine.getTemplate(this.getOutSeqTemplatePath());

        template.merge(context, writer);
    } catch (Exception e) {
        log.error("Velocity Error", e);
    }
    return writer.toString();
}
 
Example 12
Source Project: velocity-engine   Source File: ResourceExistsTestCase.java    License: Apache License 2.0 6 votes vote down vote up
public void setUp() throws Exception
    {
try {
        velocity = new VelocityEngine();
        velocity.setProperty("resource.loader", "file,string");
        velocity.setProperty("file.resource.loader.path", path);
        velocity.setProperty("string.resource.loader.class", StringResourceLoader.class.getName());

        // actual instance of logger
        logger.on();
        velocity.setProperty(RuntimeConstants.RUNTIME_LOG_INSTANCE, logger);
        velocity.setProperty("runtime.log.logsystem.test.level", "debug");
} catch (Exception e) {
    System.out.println("exception via gump: "+e);
    e.printStackTrace();
    System.out.println("log: "+logger.getLog());
}
    }
 
Example 13
Source Project: consulo   Source File: VelocityHelper.java    License: Apache License 2.0 6 votes vote down vote up
private static synchronized VelocityEngine getEngine() {
  if (instance == null) {
    try {
      Properties extendedProperties = new Properties();

      extendedProperties.setProperty(RuntimeConstants.RESOURCE_LOADER, "file");
      extendedProperties.setProperty(RuntimeConstants.PARSER_POOL_SIZE, "1");

      extendedProperties.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
      extendedProperties.setProperty("file.resource.loader.path", "resources");

      VelocityEngine engine = new VelocityEngine(extendedProperties);
      engine.init();

      instance = engine;
    }
    catch (Exception ignored) {
    }
  }

  return instance;
}
 
Example 14
Source Project: velocity-tools   Source File: XmlUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * XML Node to string
 * @param node XML node
 * @return XML node string representation
 */
public static String nodeToString(Node node)
{
    StringWriter sw = new StringWriter();
    try
    {
        Transformer t = TransformerFactory.newInstance().newTransformer();
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        t.setOutputProperty(OutputKeys.INDENT, "no");
        /* CB - Since everything is already stored as strings in memory why shoud an encoding be required here? */
        t.setOutputProperty(OutputKeys.ENCODING, RuntimeConstants.ENCODING_DEFAULT);
        t.transform(new DOMSource(node), new StreamResult(sw));
    }
    catch (TransformerException te)
    {
        LOGGER.error("could not convert XML node to string", te);
    }
    return sw.toString();
}
 
Example 15
Source Project: velocity-tools   Source File: BaseTestCase.java    License: Apache License 2.0 6 votes vote down vote up
protected void setUp() throws Exception
{
    engine = new VelocityEngine();

    //by default, make the engine's log output go to the test-report
    log = new MockLogger(false, false);
    log.setEnabledLevel(MockLogger.LOG_LEVEL_INFO);
    engine.setProperty(RuntimeConstants.RUNTIME_LOG_INSTANCE, log);

    // use string resource loader by default, instead of file
    engine.setProperty(RuntimeConstants.RESOURCE_LOADER, "file,string");
    engine.addProperty("string.resource.loader.class", StringResourceLoader.class.getName());
    engine.addProperty("string.resource.loader.repository.name", stringRepoName);
    engine.addProperty("string.resource.loader.repository.static", "false");

    setUpEngine(engine);

    context = new VelocityContext();
    setUpContext(context);
}
 
Example 16
Source Project: velocity-tools   Source File: VelocityViewServlet.java    License: Apache License 2.0 6 votes vote down vote up
/**
 *  <p>
 *    Request and response initialization. Default version does
 *    only one thing: set request POST parameters encoding to
 *    Velocity input encoding.
 *  </p>
 *
 * @param request  HttpServletRequest object containing client request
 * @param response HttpServletResponse object for the response
 * @throws IOException if thrown by underlying handling
 */
protected void initRequest(HttpServletRequest request, HttpServletResponse response) throws IOException
{
    // adjust HTTP encoding: use value provided for input.encoding
    // (this affects POST parameters only;
    // to adjust GET URI and parameters encoding, please refer to your
    // J2EE container documentation (for instance, under tomcat,
    // use <Connector ... URIEncoding="UTF-8">)
    try
    {
        request.setCharacterEncoding(getVelocityProperty(RuntimeConstants.INPUT_ENCODING, RuntimeConstants.ENCODING_DEFAULT));
    }
    catch (UnsupportedEncodingException uee)
    {
        error(request, response, uee);
        throw uee;
    }
}
 
Example 17
Source Project: velocity-engine   Source File: ASTComparisonNode.java    License: Apache License 2.0 5 votes vote down vote up
public boolean compareNonNumber(Object left, Object right)
{
    // by default, log and bail
    String msg = (right instanceof Number ? "Left" : "Right")
                   + " side of comparison operation is not a number at "
                   + StringUtils.formatFileString(this);
    if (rsvc.getBoolean(RuntimeConstants.RUNTIME_REFERENCES_STRICT, false))
    {
        throw new VelocityException(msg, null, rsvc.getLogContext().getStackTrace());
    }
    log.error(msg);
    return false;
}
 
Example 18
Source Project: velocity-engine   Source File: ResourceLoader.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Builds a Reader given a raw InputStream and an encoding. Should be use
 * by every subclass that whishes to accept optional BOMs in resources.
 * This method does *not* close the given input stream whenever an exception is thrown.
 *
 * @param rawStream The raw input stream.
 * @param encoding  The asked encoding.
 * @return found reader
 * @throws IOException
 * @throws UnsupportedEncodingException
 * @since 2.0
 */
protected Reader buildReader(InputStream rawStream, String encoding)
        throws IOException
{
    UnicodeInputStream inputStream = new UnicodeInputStream(rawStream);
    /*
     * Check encoding
     */
    String foundEncoding = inputStream.getEncodingFromStream();
    if (foundEncoding != null && encoding != null && !UnicodeInputStream.sameEncoding(foundEncoding, encoding))
    {
        log.warn("Found BOM encoding '{}' differs from asked encoding: '{}' - using BOM encoding to read resource.", foundEncoding, encoding);
        encoding = foundEncoding;
    }
    if (encoding == null)
    {
        if (foundEncoding == null)
        {
            encoding = rsvc.getString(RuntimeConstants.INPUT_ENCODING);
        } else
        {
            encoding = foundEncoding;
        }
    }

    try
    {
        return new InputStreamReader(inputStream, encoding);
    }
    catch (UnsupportedEncodingException uee)
    {
        try
        {
            inputStream.close();
        }
        catch (IOException ioe) {}
        throw uee;
    }
}
 
Example 19
Source Project: velocity-engine   Source File: ForeachTestCase.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests limiting of the number of loop iterations.
 */
public void testMaxNbrLoopsConstraint()
    throws Exception
{
    // Limit the loop to three iterations.
    engine.setProperty(RuntimeConstants.MAX_NUMBER_LOOPS,
        3);

    assertEvalEquals("1 2 3 ", "#foreach ($item in [1..10])$item #end");
}
 
Example 20
Source Project: velocity-engine   Source File: ScopeTestCase.java    License: Apache License 2.0 5 votes vote down vote up
public void testRecursiveBodyMacroScope()
{
    engine.setProperty(RuntimeConstants.VM_MAX_DEPTH, "5");
    String template = "#macro( foo )$bodyContent$macro.i#end"+
                      "#@foo()#set( $macro.i = \"$!macro.i$foo.info.depth,\" )"+
                      "$!bodyContent#end";
    assertEvalEquals("1,2,3,4,5,", template);
    assertNull(context.get("foo"));
    assertNull(context.get("macro"));
}
 
Example 21
Source Project: acmeair   Source File: ReportGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private void generateHtmlfile(Map<String, Object> input) {	   
 try{
 	VelocityEngine ve = new VelocityEngine();
 	ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
 	ve.setProperty("classpath.resource.loader.class",ClasspathResourceLoader.class.getName());
 	ve.init();
 	Template template = ve.getTemplate("templates/acmeair-report.vtl");
 	VelocityContext context = new VelocityContext();
 	 	    
 	 
 	for(Map.Entry<String, Object> entry: input.entrySet()){
 		context.put(entry.getKey(), entry.getValue());
 	}
 	context.put("math", new MathTool());
 	context.put("number", new NumberTool());
 	context.put("date", new ComparisonDateTool());
 	
 	Writer file = new FileWriter(new File(searchingLocation
	+ System.getProperty("file.separator") + RESULTS_FILE));	    
 	template.merge( context, file );
 	file.flush();
 	file.close();
   
 }catch(Exception e){
 	e.printStackTrace();
 }
}
 
Example 22
Source Project: cloud-portal   Source File: VelocityService.java    License: MIT License 5 votes vote down vote up
@PostConstruct
public void init() {

    // create velocity engine
    velocityEngine = new VelocityEngine();
    velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
    velocityEngine.init();
}
 
Example 23
Source Project: urule   Source File: RenderPageServletHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
	this.applicationContext=applicationContext;
	ve = new VelocityEngine();
	ve.setProperty(Velocity.RESOURCE_LOADER, "class");
	ve.setProperty("class.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
	ve.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM,new NullLogChute());
	ve.init();	
}
 
Example 24
Source Project: lams   Source File: VelocityEngineFactory.java    License: GNU General Public License v2.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);
	}

	// Log via Commons Logging?
	if (this.overrideLogging) {
		velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM, new CommonsLogLogChute());
	}

	// 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 25
Source Project: velocity-engine   Source File: Parse.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Init's the #parse directive.
 * @param rs
 * @param context
 * @param node
 * @throws TemplateInitException
 */
public void init(RuntimeServices rs, InternalContextAdapter context, Node node)
    throws TemplateInitException
{
    super.init(rs, context, node);

    this.maxDepth = rsvc.getInt(RuntimeConstants.PARSE_DIRECTIVE_MAXDEPTH, 10);

    strictRef = rsvc.getBoolean(RuntimeConstants.RUNTIME_REFERENCES_STRICT, false);
}
 
Example 26
Source Project: velocity-engine   Source File: StrictMathTestCase.java    License: Apache License 2.0 5 votes vote down vote up
public void setUp() throws Exception
{
    super.setUp();
    engine.setProperty(RuntimeConstants.STRICT_MATH, Boolean.TRUE);
    context.put("num", 5);
    context.put("zero", 0);
}
 
Example 27
Source Project: j2cl   Source File: J2clTestingVelocityUtil.java    License: 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.setProperty("runtime.references.strict", "true");
  velocityEngine.init();
  return velocityEngine;
}
 
Example 28
Source Project: scoold   Source File: VelocityEngineFactory.java    License: 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 29
Source Project: velocity-engine   Source File: ScopeTestCase.java    License: Apache License 2.0 5 votes vote down vote up
public void testTurningOffMacroScope()
{
    engine.setProperty("macro."+RuntimeConstants.PROVIDE_SCOPE_CONTROL, "false");
    engine.setProperty("foo."+RuntimeConstants.PROVIDE_SCOPE_CONTROL, "false");
    // macro definition
    assertEvalEquals("$macro", "#macro(a)$macro#end#a()");
    // macro body
    assertEvalEquals("$macro $foo", "#macro(foo)$bodyContent#end#@foo()$macro $foo#end");
}
 
Example 30
Source Project: sc-generator   Source File: VelocityUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static Template getTempate(String path) {
	VelocityEngine ve = new VelocityEngine();
	ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
	ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
	ve.init();
	Template t = ve.getTemplate(path, "utf-8");
	return t;
}