Java Code Examples for org.apache.velocity.util.ExtProperties

The following examples show how to use org.apache.velocity.util.ExtProperties. 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: scoold   Source File: SpringResourceLoader.java    License: 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
protected void readData(ExtProperties dataset)
{
    if (dataset != null)
    {
        for (Iterator i = dataset.getKeys(); i.hasNext(); )
        {
            String key = (String)i.next();
            // if it contains a period, it can't be a context key; 
            // it must be a data property. ignore it for now.
            if (key.indexOf('.') >= 0)
            {
                continue;
            }

            Data data = new Data();
            data.setKey(key);
            data.setValue(dataset.getString(key));

            // get/set the type/converter properties
            ExtProperties props = dataset.subset(key);
            setProperties(props, data);

            addData(data);
        }
    }
}
 
Example 3
Source Project: velocity-engine   Source File: JarResourceLoader.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Called by Velocity to initialize the loader
 * @param configuration
 */
public void init( ExtProperties configuration)
{
    log.trace("JarResourceLoader: initialization starting.");

    List paths = configuration.getList(RuntimeConstants.RESOURCE_LOADER_PATHS);

    if (paths != null)
    {
        log.debug("JarResourceLoader # of paths: {}", paths.size() );

        for (ListIterator<String> it = paths.listIterator(); it.hasNext(); )
        {
            String jar = StringUtils.trim(it.next());
            it.set(jar);
            loadJar(jar);
        }
    }

    log.trace("JarResourceLoader: initialization complete.");
}
 
Example 4
Source Project: velocity-engine   Source File: URLResourceLoader.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @param configuration
 * @see ResourceLoader#init(org.apache.velocity.util.ExtProperties)
 */
public void init(ExtProperties configuration)
{
    log.trace("URLResourceLoader: initialization starting.");

    roots = configuration.getStringArray("root");
    if (log.isDebugEnabled())
    {
        for (String root : roots)
        {
            log.debug("URLResourceLoader: adding root '{}'", root);
        }
    }

    timeout = configuration.getInt("timeout", -1);

    // init the template paths map
    templateRoots = new HashMap();

    log.trace("URLResourceLoader: initialization complete.");
}
 
Example 5
Source Project: velocity-engine   Source File: FileResourceLoader.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @see ResourceLoader#init(org.apache.velocity.util.ExtProperties)
 */
public void init( ExtProperties configuration)
{
    log.trace("FileResourceLoader: initialization starting.");

    paths.addAll( configuration.getVector(RuntimeConstants.RESOURCE_LOADER_PATHS) );

    // trim spaces from all paths
    for (ListIterator<String> it = paths.listIterator(); it.hasNext(); )
    {
        String path = StringUtils.trim(it.next());
        it.set(path);
        log.debug("FileResourceLoader: adding path '{}'", path);
    }
    log.trace("FileResourceLoader: initialization complete.");
}
 
Example 6
Source Project: velocity-engine   Source File: RuntimeInstance.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Allow an external system to set an ExtProperties
 * object to use.
 *
 * @param  configuration
 * @since 2.0
 */
public void setConfiguration( ExtProperties configuration)
{
    if (overridingProperties == null)
    {
        overridingProperties = configuration;
    }
    else
    {
        // Avoid possible ConcurrentModificationException
        if (overridingProperties != configuration)
        {
            overridingProperties.combine(configuration);
        }
    }
}
 
Example 7
Source Project: oxTrust   Source File: ClasspathPathResourceLoader.java    License: MIT License 5 votes vote down vote up
/**
 * @see ResourceLoader#init(org.apache.velocity.util.ExtProperties)
 */
public void init(ExtProperties configuration) {
	log.trace("PathClasspathResourceLoader: initialization starting.");

	paths.addAll(configuration.getVector(RuntimeConstants.RESOURCE_LOADER_PATHS));

	// trim spaces from all paths
	for (ListIterator<String> it = paths.listIterator(); it.hasNext();) {
		String path = StringUtils.trim(it.next());
		it.set(path);
		log.debug("PathClasspathResourceLoader: adding path '{}'", path);
	}
	log.trace("PathClasspathResourceLoader: initialization complete.");
}
 
Example 8
/**
 * <p>Reads an properties file from an {@link InputStream}
 * and uses it to configure this {@link FactoryConfiguration}.</p>
 * 
 * @param url the URL to read from
 */
protected void readImpl(URL url) throws IOException
{
    ExtProperties props = new ExtProperties();
    props.load(url.openStream());

    // all factory settings should be prefixed with "tools"
    read(props.subset("tools"));
}
 
Example 9
public void read(ExtProperties factory)
{
    // get the global properties
    readProperties(factory, this);

    // get the toolboxes
    readToolboxes(factory);

    // get the data
    readData(factory.subset("data"));
}
 
Example 10
protected void readProperties(ExtProperties configProps,
                              Configuration config)
{
    ExtProperties properties = configProps.subset("property");
    if (properties != null)
    {
        for (Iterator i = properties.getKeys(); i.hasNext(); )
        {
            String name = (String)i.next();
            String value = properties.getString(name);

            ExtProperties propProps = properties.subset(name);
            if (propProps.size() == 1)
            {
                // then set this as a 'simple' property
                config.setProperty(name, value);
            }
            else
            {
                // add it as a convertable property
                Property property = new Property();
                property.setName(name);
                property.setValue(value);

                // set the type/converter properties
                setProperties(propProps, property);
            }
        }
    }
}
 
Example 11
protected void readToolboxes(ExtProperties factory)
{
    String[] scopes = factory.getStringArray("toolbox");
    for (String scope : scopes)
    {
        ToolboxConfiguration toolbox = new ToolboxConfiguration();
        toolbox.setScope(scope);
        addToolbox(toolbox);

        ExtProperties toolboxProps = factory.subset(scope);
        readTools(toolboxProps, toolbox);
        readProperties(toolboxProps, toolbox);
    }
}
 
Example 12
protected void readTools(ExtProperties tools,
                         ToolboxConfiguration toolbox)
{
    for (Iterator i = tools.getKeys(); i.hasNext(); )
    {
        String key = (String)i.next();
        // if it contains a period, it can't be a context key; 
        // it must be a tool property. ignore it for now.
        if (key.indexOf('.') >= 0)
        {
            continue;
        }

        String classname = tools.getString(key);
        ToolConfiguration tool = new ToolConfiguration();
        tool.setClassname(classname);
        tool.setKey(key);
        toolbox.addTool(tool);

        // get tool properties prefixed by 'property'
        ExtProperties toolProps = tools.subset(key);
        readProperties(toolProps, tool);

        // ok, get tool properties that aren't prefixed by 'property'
        for (Iterator j = toolProps.getKeys(); j.hasNext(); )
        {
            String name = (String)j.next();
            if (!name.equals(tool.getKey()))
            {
                tool.setProperty(name, toolProps.getString(name));
            }
        }

        // get special props explicitly
        String restrictTo = toolProps.getString("restrictTo");
        tool.setRestrictTo(restrictTo);
    }
}
 
Example 13
protected void setProperties(ExtProperties props, Data data)
{
    // let's just set/convert anything we can
    // this could be simplified to just check for type/class/converter
    try
    {
        BeanUtils.populate(data, props);
    }
    catch (Exception e)
    {
        throw new RuntimeException(e);
    }
}
 
Example 14
Source Project: velocity-engine   Source File: DataSourceResourceLoader.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @see ResourceLoader#init(org.apache.velocity.util.ExtProperties)
 */
public void init(ExtProperties configuration)
{
    dataSourceName  = StringUtils.trim(configuration.getString("datasource_url"));
    tableName       = StringUtils.trim(configuration.getString("resource.table"));
    keyColumn       = StringUtils.trim(configuration.getString("resource.key_column"));
    templateColumn  = StringUtils.trim(configuration.getString("resource.template_column"));
    timestampColumn = StringUtils.trim(configuration.getString("resource.timestamp_column"));

    if (dataSource != null)
    {
        log.debug("DataSourceResourceLoader: using dataSource instance with table \"{}\"", tableName);
        log.debug("DataSourceResourceLoader: using columns \"{}\", \"{}\" and \"{}\"", keyColumn, templateColumn, timestampColumn);

        log.trace("DataSourceResourceLoader initialized.");
    }
    else if (dataSourceName != null)
    {
        log.debug("DataSourceResourceLoader: using \"{}\" datasource with table \"{}\"", dataSourceName, tableName);
        log.debug("DataSourceResourceLoader: using columns \"{}\", \"{}\" and \"{}\"", keyColumn, templateColumn, timestampColumn);

        log.trace("DataSourceResourceLoader initialized.");
    }
    else
    {
        String msg = "DataSourceResourceLoader not properly initialized. No DataSource was identified.";
        log.error(msg);
        throw new RuntimeException(msg);
    }
}
 
Example 15
Source Project: velocity-engine   Source File: RuntimeInstance.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Resets the instance, so Velocity can be re-initialized again.
 *
 * @since 2.0.0
 */
public synchronized void reset()
{
    this.configuration = new ExtProperties();
    this.defaultEncoding = null;
    this.evaluateScopeName = "evaluate";
    this.eventCartridge = null;
    this.initialized = false;
    this.initializing = false;
    this.overridingProperties = null;
    this.parserPool = null;
    this.enabledScopeControls.clear();
    this.resourceManager = null;
    this.runtimeDirectives = new Hashtable();
    this.runtimeDirectivesShared = null;
    this.uberSpect = null;
    this.stringInterning = false;
    this.parserConfiguration = new ParserConfiguration();

    /*
     *  create a VM factory, introspector, and application attributes
     */
    vmFactory = new VelocimacroFactory( this );

    /*
     * and a store for the application attributes
     */
    applicationAttributes = new HashMap();
}
 
Example 16
Source Project: velocity-engine   Source File: RuntimeInstance.java    License: Apache License 2.0 5 votes vote down vote up
private void initializeScopeSettings()
{
    ExtProperties scopes = configuration.subset(CONTEXT_SCOPE_CONTROL);
    if (scopes != null)
    {
        Iterator<String> scopeIterator = scopes.getKeys();
        while (scopeIterator.hasNext())
        {
            String scope = scopeIterator.next();
            boolean enabled = scopes.getBoolean(scope);
            if (enabled) enabledScopeControls.add(scope);
        }
    }
}
 
Example 17
public void setUp()
        throws Exception
{

    assureResultsDirectoryExists(RESULTS_DIR);

    DataSource ds1 = new TestDataSource(TEST_JDBC_DRIVER_CLASS, TEST_JDBC_URI, TEST_JDBC_LOGIN, TEST_JDBC_PASSWORD);
    DataSourceResourceLoader rl1 = new DataSourceResourceLoader();
    rl1.setDataSource(ds1);

    DataSource ds2 = new TestDataSource(TEST_JDBC_DRIVER_CLASS, TEST_JDBC_URI, TEST_JDBC_LOGIN, TEST_JDBC_PASSWORD);
    DataSourceResourceLoader rl2 = new DataSourceResourceLoader();
    rl2.setDataSource(ds2);

    ExtProperties props = new ExtProperties();
    props.addProperty( "resource.loader", "ds" );
    props.setProperty( "ds.resource.loader.instance", rl1);
    props.setProperty( "ds.resource.loader.resource.table",           "velocity_template_varchar");
    props.setProperty( "ds.resource.loader.resource.keycolumn",       "vt_id");
    props.setProperty( "ds.resource.loader.resource.templatecolumn",  "vt_def");
    props.setProperty( "ds.resource.loader.resource.timestampcolumn", "vt_timestamp");
    props.setProperty(Velocity.RUNTIME_LOG_INSTANCE, new TestLogger(false, false));

    varcharTemplatesEngine = new RuntimeInstance();
    varcharTemplatesEngine.setConfiguration(props);
    varcharTemplatesEngine.init();

    ExtProperties props2 = (ExtProperties)props.clone();
    props2.setProperty( "ds.resource.loader.instance", rl2);
    props2.setProperty( "ds.resource.loader.resource.table",           "velocity_template_clob");
    clobTemplatesEngine = new RuntimeInstance();
    clobTemplatesEngine.setConfiguration(props2);
    clobTemplatesEngine.init();
}
 
Example 18
Source Project: krazo   Source File: ServletContextResourceLoader.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void init(ExtProperties configuration) {
    servletContext = (ServletContext) rsvc.getApplicationAttribute(ServletContext.class.getName());
}
 
Example 19
Source Project: lucene-solr   Source File: SolrVelocityResourceLoader.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void init(ExtProperties extendedProperties) {
}
 
Example 20
Source Project: consulo   Source File: VelocityWrapper.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void init(ExtProperties extProperties) {
}
 
Example 21
Source Project: velocity-tools   Source File: WebappResourceLoader.java    License: Apache License 2.0 4 votes vote down vote up
/**
 *  This is abstract in the base class, so we need it.
 *  <br>
 *  NOTE: this expects that the ServletContext has already
 *        been placed in the runtime's application attributes
 *        under its full class name (i.e. "javax.servlet.ServletContext").
 *
 * @param configuration the {@link ExtProperties} associated with
 *        this resource loader.
 */
public void init(ExtProperties configuration)
{
    log.trace("WebappResourceLoader: initialization starting.");

    /* get configured paths */
    paths = configuration.getStringArray("path");
    if (paths == null || paths.length == 0)
    {
        paths = new String[1];
        paths[0] = "/";
    }
    else
    {
        /* make sure the paths end with a '/' */
        for (int i=0; i < paths.length; i++)
        {
            if (!paths[i].endsWith("/"))
            {
                paths[i] += '/';
            }
            log.info("WebappResourceLoader: added template path - '{}'", paths[i]);
        }
    }

    /* get the ServletContext */
    Object obj = rsvc.getApplicationAttribute(ServletContext.class.getName());
    if (obj instanceof ServletContext)
    {
        servletContext = (ServletContext)obj;
    }
    else
    {
        log.error("WebappResourceLoader: unable to retrieve ServletContext");
    }

    /* init the template paths map */
    templatePaths = new HashMap();

    log.trace("WebappResourceLoader: initialization complete.");
}
 
Example 22
Source Project: velocity-engine   Source File: StringResourceLoader.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * @param configuration
 * @see ResourceLoader#init(org.apache.velocity.util.ExtProperties)
 */
public void init(final ExtProperties configuration)
{
    log.trace("StringResourceLoader: initialization starting.");

    // get the repository configuration info
    String repoClass = configuration.getString(REPOSITORY_CLASS, REPOSITORY_CLASS_DEFAULT);
    String repoName = configuration.getString(REPOSITORY_NAME, REPOSITORY_NAME_DEFAULT);
    boolean isStatic = configuration.getBoolean(REPOSITORY_STATIC, REPOSITORY_STATIC_DEFAULT);
    String encoding = configuration.getString(REPOSITORY_ENCODING);

    // look for an existing repository of that name and isStatic setting
    if (isStatic)
    {
        this.repository = getRepository(repoName);
        if (repository != null)
        {
            log.debug("Loaded repository '{}' from static repo store", repoName);
        }
    }
    else
    {
        this.repository = (StringResourceRepository)rsvc.getApplicationAttribute(repoName);
        if (repository != null)
        {
            log.debug("Loaded repository '{}' from application attributes", repoName);
        }
    }

    if (this.repository == null)
    {
        // since there's no repository under the repo name, create a new one
        this.repository = createRepository(repoClass, encoding);

        // and store it according to the isStatic setting
        if (isStatic)
        {
            setRepository(repoName, this.repository);
        }
        else
        {
            rsvc.setApplicationAttribute(repoName, this.repository);
        }
    }
    else
    {
        // ok, we already have a repo
        // warn them if they are trying to change the class of the repository
        if (!this.repository.getClass().getName().equals(repoClass))
        {
            log.debug("Cannot change class of string repository '{}' from {} to {}." +
                      " The change will be ignored.",
                      repoName, this.repository.getClass().getName(), repoClass);
        }

        // allow them to change the default encoding of the repo
        if (encoding != null &&
            !this.repository.getEncoding().equals(encoding))
        {
            log.debug("Changing the default encoding of string repository '{}' from {} to {}",
                      repoName, this.repository.getEncoding(), encoding);
            this.repository.setEncoding(encoding);
        }
    }

    log.trace("StringResourceLoader: initialization complete.");
}
 
Example 23
Source Project: velocity-engine   Source File: ClasspathResourceLoader.java    License: Apache License 2.0 4 votes vote down vote up
/**
 *  This is abstract in the base class, so we need it
 * @param configuration
 */
public void init( ExtProperties configuration)
{
    log.trace("ClasspathResourceLoader: initialization complete.");
}
 
Example 24
Source Project: velocity-engine   Source File: ResourceManagerImpl.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * This will produce a List of Hashtables, each hashtable contains the initialization info for a particular resource loader. This
 * Hashtable will be passed in when initializing the the template loader.
 */
private void assembleResourceLoaderInitializers()
{
    Vector resourceLoaderNames = rsvc.getConfiguration().getVector(RuntimeConstants.RESOURCE_LOADERS);

    for (ListIterator<String> it = resourceLoaderNames.listIterator(); it.hasNext(); )
    {
        /*
         * The loader id might look something like the following:
         *
         * resource.loader.file
         *
         * The loader id is the prefix used for all properties
         * pertaining to a particular loader.
         */
        String loaderName = StringUtils.trim(it.next());
        it.set(loaderName);
        StringBuilder loaderID = new StringBuilder();
        loaderID.append(RuntimeConstants.RESOURCE_LOADER).append('.').append(loaderName);

        ExtProperties loaderConfiguration =
    		rsvc.getConfiguration().subset(loaderID.toString());

        /*
         *  we can't really count on ExtProperties to give us an empty set
         */
        if (loaderConfiguration == null)
        {
            log.debug("ResourceManager : No configuration information found "+
                      "for resource loader named '{}' (id is {}). Skipping it...",
                      loaderName, loaderID);
            continue;
        }

        /*
         *  add the loader name token to the initializer if we need it
         *  for reference later. We can't count on the user to fill
         *  in the 'name' field
         */

        loaderConfiguration.setProperty(RuntimeConstants.RESOURCE_LOADER_IDENTIFIER, loaderName);

        /*
         * Add resources to the list of resource loader
         * initializers.
         */
        sourceInitializerList.add(loaderConfiguration);
    }
}
 
Example 25
Source Project: velocity-engine   Source File: CommonsExtPropTestCase.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Runs the test.
 */
public void testExtendedProperties ()
        throws Exception
{
        assureResultsDirectoryExists(RESULTS_DIR);

        ExtProperties c = new ExtProperties(TEST_CONFIG);

        FileWriter result = new FileWriter(
            getFileName(RESULTS_DIR, "output", "res"));

        message(result, "Testing order of keys ...");
        showIterator(result, c.getKeys());

        message(result, "Testing retrieval of CSV values ...");
        showVector(result, c.getVector("resource.loaders"));

        message(result, "Testing subset(prefix).getKeys() ...");
        ExtProperties subset = c.subset("resource.loader.file");
        showIterator(result, subset.getKeys());

        message(result, "Testing getVector(prefix) ...");
        showVector(result, subset.getVector("path"));

        message(result, "Testing getString(key) ...");
        result.write(c.getString("config.string.value"));
        result.write("\n\n");

        message(result, "Testing getBoolean(key) ...");
        result.write(Boolean.valueOf(c.getBoolean("config.boolean.value")).toString());
        result.write("\n\n");

        message(result, "Testing getByte(key) ...");
        result.write(new Byte(c.getByte("config.byte.value")).toString());
        result.write("\n\n");

        message(result, "Testing getShort(key) ...");
        result.write(new Short(c.getShort("config.short.value")).toString());
        result.write("\n\n");

        message(result, "Testing getInt(key) ...");
        result.write(new Integer(c.getInt("config.int.value")).toString());
        result.write("\n\n");

        message(result, "Testing getLong(key) ...");
        result.write(new Long(c.getLong("config.long.value")).toString());
        result.write("\n\n");

        message(result, "Testing getFloat(key) ...");
        result.write(new Float(c.getFloat("config.float.value")).toString());
        result.write("\n\n");

        message(result, "Testing getDouble(key) ...");
        result.write(new Double(c.getDouble("config.double.value")).toString());
        result.write("\n\n");

        message(result, "Testing escaped-comma scalar...");
        result.write( c.getString("escape.comma1"));
        result.write("\n\n");

        message(result, "Testing escaped-comma vector...");
        showVector(result,  c.getVector("escape.comma2"));
        result.write("\n\n");

        result.flush();
        result.close();

        if (!isMatch(RESULTS_DIR, COMPARE_DIR, "output","res","cmp"))
        {
            fail("Output incorrect.");
        }
}
 
Example 26
public void init(ExtProperties configuration)
{
}
 
Example 27
Source Project: velocity-engine   Source File: RuntimeSingleton.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Directly set the ExtProperties configuration object
 * @param configuration
 * @see RuntimeInstance#setConfiguration(ExtProperties)
 */
public static void setConfiguration(ExtProperties configuration)
{
    ri.setConfiguration(configuration);
}
 
Example 28
Source Project: velocity-engine   Source File: RuntimeSingleton.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Return the velocity runtime configuration object.
 *
 * @return ExtProperties configuration object which houses
 *                       the velocity runtime properties.
 * @see RuntimeInstance#getConfiguration()
 */
public static ExtProperties getConfiguration()
{
    return ri.getConfiguration();
}
 
Example 29
Source Project: velocity-engine   Source File: ResourceLoader.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Initialize the template loader with a
 * a resources class.
 *
 * @param configuration
 */
public abstract void init(ExtProperties configuration);
 
Example 30
Source Project: velocity-engine   Source File: RuntimeServices.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Allow an external system to set an ExtProperties
 * object to use.
 *
 * @param configuration
 * @since 2.0
 */
void setConfiguration(ExtProperties configuration);