org.apache.velocity.runtime.resource.loader.ResourceLoader Java Examples

The following examples show how to use org.apache.velocity.runtime.resource.loader.ResourceLoader. 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: SpringResourceLoader.java    From scoold with Apache License 2.0 6 votes vote down vote up
@Override
public void init(ExtProperties configuration) {
	this.resourceLoader = (org.springframework.core.io.ResourceLoader)
			this.rsvc.getApplicationAttribute(SPRING_RESOURCE_LOADER);
	String resourceLoaderPath = (String) this.rsvc.getApplicationAttribute(SPRING_RESOURCE_LOADER_PATH);
	if (this.resourceLoader == null) {
		throw new IllegalArgumentException(
				"'resourceLoader' application attribute must be present for SpringResourceLoader");
	}
	if (resourceLoaderPath == null) {
		throw new IllegalArgumentException(
				"'resourceLoaderPath' application attribute must be present for SpringResourceLoader");
	}
	this.resourceLoaderPaths = StringUtils.commaDelimitedListToStringArray(resourceLoaderPath);
	for (int i = 0; i < this.resourceLoaderPaths.length; i++) {
		String path = this.resourceLoaderPaths[i];
		if (!path.endsWith("/")) {
			this.resourceLoaderPaths[i] = path + "/";
		}
	}
	if (logger.isInfoEnabled()) {
		logger.info("SpringResourceLoader for Velocity: using resource loader [" + this.resourceLoader +
				"] and resource loader paths " + Arrays.asList(this.resourceLoaderPaths));
	}
}
 
Example #2
Source File: ResourceLoaderInstanceTestCase.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
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 #3
Source File: VelocityScriptEngine.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 * Compile a template
 * @param script template source
 * @return compiled template
 * @throws ScriptException
 */
public CompiledScript compile(Reader script) throws ScriptException
{
    initVelocityEngine(null);
    ResourceLoader resourceLoader = new SingleResourceReader(script);
    Template template = new Template();
    template.setRuntimeServices(velocityEngine);
    template.setResourceLoader(resourceLoader);
    try
    {
        template.process();
    }
    catch(Exception e)
    {
        // CB TODO - exception may have line/col informations, that ScriptException can exploit
        throw new ScriptException(e);
    }
    return new VelocityCompiledScript(this, template);
}
 
Example #4
Source File: SpringResourceLoader.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
@Override
public void init(ExtendedProperties configuration) {
	this.resourceLoader = (org.springframework.core.io.ResourceLoader)
			this.rsvc.getApplicationAttribute(SPRING_RESOURCE_LOADER);
	String resourceLoaderPath = (String) this.rsvc.getApplicationAttribute(SPRING_RESOURCE_LOADER_PATH);
	if (this.resourceLoader == null) {
		throw new IllegalArgumentException(
				"'resourceLoader' application attribute must be present for SpringResourceLoader");
	}
	if (resourceLoaderPath == null) {
		throw new IllegalArgumentException(
				"'resourceLoaderPath' application attribute must be present for SpringResourceLoader");
	}
	this.resourceLoaderPaths = StringUtils.commaDelimitedListToStringArray(resourceLoaderPath);
	for (int i = 0; i < this.resourceLoaderPaths.length; i++) {
		String path = this.resourceLoaderPaths[i];
		if (!path.endsWith("/")) {
			this.resourceLoaderPaths[i] = path + "/";
		}
	}
	if (logger.isInfoEnabled()) {
		logger.info("SpringResourceLoader for Velocity: using resource loader [" + this.resourceLoader +
				"] and resource loader paths " + Arrays.asList(this.resourceLoaderPaths));
	}
}
 
Example #5
Source File: SpringResourceLoader.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public void init(ExtendedProperties configuration) {
	this.resourceLoader = (org.springframework.core.io.ResourceLoader)
			this.rsvc.getApplicationAttribute(SPRING_RESOURCE_LOADER);
	String resourceLoaderPath = (String) this.rsvc.getApplicationAttribute(SPRING_RESOURCE_LOADER_PATH);
	if (this.resourceLoader == null) {
		throw new IllegalArgumentException(
				"'resourceLoader' application attribute must be present for SpringResourceLoader");
	}
	if (resourceLoaderPath == null) {
		throw new IllegalArgumentException(
				"'resourceLoaderPath' application attribute must be present for SpringResourceLoader");
	}
	this.resourceLoaderPaths = StringUtils.commaDelimitedListToStringArray(resourceLoaderPath);
	for (int i = 0; i < this.resourceLoaderPaths.length; i++) {
		String path = this.resourceLoaderPaths[i];
		if (!path.endsWith("/")) {
			this.resourceLoaderPaths[i] = path + "/";
		}
	}
	if (logger.isInfoEnabled()) {
		logger.info("SpringResourceLoader for Velocity: using resource loader [" + this.resourceLoader +
				"] and resource loader paths " + Arrays.asList(this.resourceLoaderPaths));
	}
}
 
Example #6
Source File: SpringResourceLoader.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void init(ExtendedProperties configuration) {
	this.resourceLoader = (org.springframework.core.io.ResourceLoader)
			this.rsvc.getApplicationAttribute(SPRING_RESOURCE_LOADER);
	String resourceLoaderPath = (String) this.rsvc.getApplicationAttribute(SPRING_RESOURCE_LOADER_PATH);
	if (this.resourceLoader == null) {
		throw new IllegalArgumentException(
				"'resourceLoader' application attribute must be present for SpringResourceLoader");
	}
	if (resourceLoaderPath == null) {
		throw new IllegalArgumentException(
				"'resourceLoaderPath' application attribute must be present for SpringResourceLoader");
	}
	this.resourceLoaderPaths = StringUtils.commaDelimitedListToStringArray(resourceLoaderPath);
	for (int i = 0; i < this.resourceLoaderPaths.length; i++) {
		String path = this.resourceLoaderPaths[i];
		if (!path.endsWith("/")) {
			this.resourceLoaderPaths[i] = path + "/";
		}
	}
	if (logger.isInfoEnabled()) {
		logger.info("SpringResourceLoader for Velocity: using resource loader [" + this.resourceLoader +
				"] and resource loader paths " + Arrays.asList(this.resourceLoaderPaths));
	}
}
 
Example #7
Source File: AliadaResourceManager.java    From aliada-tool with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected Resource refreshResource(final Resource resource, final String encoding) {
    resource.touch();

    final ResourceLoader loader = resource.getResourceLoader();
    if (resourceLoaders.size() > 0 && resourceLoaders.indexOf(loader) > 0) {
        final String name = resource.getName();
        if (loader != getLoaderForResource(name)) {
            return loadResource(name, resource.getType(), encoding);
        }
    }

    if (resource.isSourceModified()) {
        if (!StringUtils.equals(resource.getEncoding(), encoding)) {
            resource.setEncoding(encoding);
        }
        
        final String resourceName = resource.getName();
        final Resource newResource = AliadaResourceFactory.getResource(resourceName, resource.getType());

        newResource.setRuntimeServices(rsvc);
        newResource.setName(resourceName);
        newResource.setEncoding(resource.getEncoding());
        newResource.setResourceLoader(loader);
        newResource.setModificationCheckInterval(loader.getModificationCheckInterval());

        newResource.process();
        newResource.setLastModified(loader.getLastModified(resource));

        globalCache.put(
        		new StringBuilder(resource.getType())
        			.append(resource.getName())
        			.toString(), 
        		newResource);
        return newResource;
    }
    return resource;
}
 
Example #8
Source File: AliadaResourceManager.java    From aliada-tool with GNU General Public License v3.0 5 votes vote down vote up
/**
    * Returns the first {@link ResourceLoader} in which the specified
    * resource exists.
    * 
    * @param resourceName the resource name.
    * @return a resource loader for the given resource.
    */
@SuppressWarnings("unchecked")
private ResourceLoader getLoaderForResource(final String resourceName) {
       for (final Iterator<ResourceLoader> i = resourceLoaders.iterator(); i.hasNext();) {
           final ResourceLoader loader = (ResourceLoader)i.next();
           if (loader.resourceExists(resourceName)) {
               return loader;
           }
       }
       return null;
   }
 
Example #9
Source File: TestVelocityView.java    From gocd with Apache License 2.0 5 votes vote down vote up
TestVelocityView(String templatePath, Map<String, Object> modelData) {
    this.templatePath = templatePath;
    this.modelData = modelData;

    this.additionalTemplates = new ArrayList<>();
    loader = mock(ResourceLoader.class);
    runtimeServices = spy(new RuntimeInstance());

    setupToolAttributes();
}
 
Example #10
Source File: TestVelocityView.java    From gocd with Apache License 2.0 5 votes vote down vote up
private Template setupTemplate(ResourceLoader loader, RuntimeInstance runtimeServices, String templateName, InputStream templateContents) throws IOException {
    Template template = new Template();
    template.setRuntimeServices(runtimeServices);
    template.setResourceLoader(loader);
    template.setName(templateName);

    byte[] bytes = IOUtils.toByteArray(templateContents);
    templateContents.close();

    when(loader.getResourceStream(templateName)).thenReturn(new ByteArrayInputStream(bytes));
    doReturn(template).when(runtimeServices).getTemplate(templateName);
    doReturn(template).when(runtimeServices).getTemplate(eq(templateName), any(String.class));

    return template;
}
 
Example #11
Source File: TestVelocityView.java    From gocd with Apache License 2.0 5 votes vote down vote up
private void setupContentResource(ResourceLoader loader, RuntimeInstance runtimeServices, String templateName, String fakeContent) {
    try {
        ContentResource resource = new ContentResource();
        resource.setRuntimeServices(runtimeServices);
        resource.setResourceLoader(loader);
        resource.setName(templateName);
        resource.setData(fakeContent);

        doReturn(resource).when(runtimeServices).getContent(templateName);
        doReturn(resource).when(runtimeServices).getContent(eq(templateName), any(String.class));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #12
Source File: ResourceManagerImpl.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Determines if a template exists, and returns name of the loader that provides it. This is a slightly less hokey way to
 * support the Velocity.templateExists() utility method, which was broken when per-template encoding was introduced. We can
 * revisit this.
 *
 * @param  resourceName  Name of template or content resource
 *
 * @return  class name of loader than can provide it
 */
public String getLoaderNameForResource(String resourceName)
{
    ResourceLoader loader = getLoaderForResource(resourceName);
    if (loader == null)
    {
        return null;
    }
    return loader.getClass().toString();
}
 
Example #13
Source File: ResourceManagerImpl.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the first {@link ResourceLoader} in which the specified
 * resource exists.
 */
private ResourceLoader getLoaderForResource(String resourceName)
{
    for (ResourceLoader loader : resourceLoaders)
    {
        if (loader.resourceExists(resourceName))
        {
            return loader;
        }
    }
    return null;
}
 
Example #14
Source File: ResourceManagerImpl.java    From velocity-engine with Apache License 2.0 4 votes vote down vote up
/**
 * Loads a resource from the current set of resource loaders.
 *
 * @param  resourceName  The name of the resource to retrieve.
 * @param  resourceType  The type of resource (<code>RESOURCE_TEMPLATE</code>, <code>RESOURCE_CONTENT</code>, etc.).
 * @param  encoding  The character encoding to use.
 *
 * @return  Resource with the template parsed and ready.
 *
 * @throws  ResourceNotFoundException  if template not found from any available source.
 * @throws  ParseErrorException  if template cannot be parsed due to syntax (or other) error.
 */
protected Resource loadResource(String resourceName, int resourceType, String encoding)
    throws ResourceNotFoundException,
        ParseErrorException
{
    Resource resource = createResource(resourceName, resourceType);
    resource.setRuntimeServices(rsvc);
    resource.setName(resourceName);
    resource.setEncoding(encoding);

    /*
     * Now we have to try to find the appropriate
     * loader for this resource. We have to cycle through
     * the list of available resource loaders and see
     * which one gives us a stream that we can use to
     * make a resource with.
     */

    long howOldItWas = 0;

    for (ResourceLoader resourceLoader : resourceLoaders)
    {
        resource.setResourceLoader(resourceLoader);

        /*
         *  catch the ResourceNotFound exception
         *  as that is ok in our new multi-loader environment
         */

        try
        {

            if (resource.process())
            {
                /*
                 *  FIXME  (gmj)
                 *  moved in here - technically still
                 *  a problem - but the resource needs to be
                 *  processed before the loader can figure
                 *  it out due to to the new
                 *  multi-path support - will revisit and fix
                 */

                if (logWhenFound)
                {
                    log.debug("ResourceManager: found {} with loader {}",
                        resourceName, resourceLoader.getClassName());
                }

                howOldItWas = resourceLoader.getLastModified(resource);

                break;
            }
        }
        catch (ResourceNotFoundException rnfe)
        {
            /*
             *  that's ok - it's possible to fail in
             *  multi-loader environment
             */
        }
    }

    /*
     * Return null if we can't find a resource.
     */
    if (resource.getData() == null)
    {
        throw new ResourceNotFoundException("Unable to find resource '" + resourceName + "'", null, rsvc.getLogContext().getStackTrace());
    }

    /*
     *  some final cleanup
     */

    resource.setLastModified(howOldItWas);
    resource.setModificationCheckInterval(resource.getResourceLoader().getModificationCheckInterval());

    resource.touch();

    return resource;
}
 
Example #15
Source File: ResourceManagerImpl.java    From velocity-engine with Apache License 2.0 4 votes vote down vote up
/**
 * Takes an existing resource, and 'refreshes' it. This generally means that the source of the resource is checked for changes
 * according to some cache/check algorithm and if the resource changed, then the resource data is reloaded and re-parsed.
 *
 * @param  resource  resource to refresh
 * @param  encoding  character encoding of the resource to refresh.
 * @return resource
 * @throws  ResourceNotFoundException  if template not found from current source for this Resource
 * @throws  ParseErrorException  if template cannot be parsed due to syntax (or other) error.
 */
protected Resource refreshResource(Resource resource, final String encoding)
    throws ResourceNotFoundException, ParseErrorException
{
    /*
     * The resource knows whether it needs to be checked
     * or not, and the resource's loader can check to
     * see if the source has been modified. If both
     * these conditions are true then we must reload
     * the input stream and parse it to make a new
     * AST for the resource.
     */

    String resourceKey = resource.getType() + resource.getName();

    /*
     *  touch() the resource to reset the counters
     */
    resource.touch();

    /* check whether this can now be found in a higher priority
     * resource loader.  if so, pass the request off to loadResource.
     */
    ResourceLoader loader = resource.getResourceLoader();
    if (resourceLoaders.size() > 0 && resourceLoaders.indexOf(loader) > 0)
    {
        String name = resource.getName();
        if (loader != getLoaderForResource(name))
        {
            resource = loadResource(name, resource.getType(), encoding);
            if (resource.getResourceLoader().isCachingOn())
            {
                globalCache.put(resourceKey, resource);
            }
        }
    }

    if (resource.isSourceModified())
    {
        /*
         *  now check encoding info.  It's possible that the newly declared
         *  encoding is different than the encoding already in the resource
         *  this strikes me as bad...
         */

        if (!StringUtils.equals(resource.getEncoding(), encoding))
        {
            log.warn("Declared encoding for template '{}' is different on reload. Old = '{}' New = '{}'",
                     resource.getName(), resource.getEncoding(), encoding);
            resource.setEncoding(encoding);
        }

        /*
         *  read how old the resource is _before_
         *  processing (=>reading) it
         */
        long howOldItWas = loader.getLastModified(resource);

        /*
         * we create a copy to avoid partially overwriting a
         * template which may be in use in another thread
         */

        Resource newResource =
            ResourceFactory.getResource(resource.getName(), resource.getType());

        newResource.setRuntimeServices(rsvc);
        newResource.setName(resource.getName());
        newResource.setEncoding(resource.getEncoding());
        newResource.setResourceLoader(loader);
        newResource.setModificationCheckInterval(loader.getModificationCheckInterval());

        newResource.process();
        newResource.setLastModified(howOldItWas);
        resource = newResource;

        globalCache.put(resourceKey, newResource);
    }
    return resource;
}
 
Example #16
Source File: Resource.java    From velocity-engine with Apache License 2.0 2 votes vote down vote up
/**
 * Return the template loader that pulled
 * in the template stream
 * @return The resource loader for this resource.
 */
public ResourceLoader getResourceLoader()
{
    return resourceLoader;
}
 
Example #17
Source File: Resource.java    From velocity-engine with Apache License 2.0 2 votes vote down vote up
/**
 * Set the template loader for this template. Set
 * when the Runtime determines where this template
 * came from the list of possible sources.
 * @param resourceLoader
 */
public void setResourceLoader(ResourceLoader resourceLoader)
{
    this.resourceLoader = resourceLoader;
}