org.apache.velocity.runtime.resource.util.StringResourceRepository Java Examples

The following examples show how to use org.apache.velocity.runtime.resource.util.StringResourceRepository. 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: CodeGenerator.java    From sundrio with Apache License 2.0 6 votes vote down vote up
public CodeGenerator(CodeGeneratorContext context, M model, String[] parameters, Writer writer, URL templateUrl, String templateResource, String templateContent, Set<Class<? extends Directive>> directives) {
    this.context = context != null ? context : new CodeGeneratorContext();
    this.model = model;
    this.parameters = parameters;
    this.writer = writer;
    this.templateResource = templateResource;
    this.templateUrl = templateUrl;
    this.templateContent = templateContent;
    this.directives = directives;

    StringResourceRepository repo = StringResourceLoader.getRepository();
    try {
        repo.putStringResource(TEMPLATE, templateContent != null ? templateContent : (templateUrl != null ? loadResource(templateUrl) : loadResource(templateResource)));
    } catch (Exception e) {
        throw new RuntimeException(TEMPLATE_READER_FAILURE, e);
    }

    for (Class<? extends Directive> directive : directives) {
        context.getVelocityEngine().loadDirective(directive.getCanonicalName());
    }

    this.template = this.context.getVelocityEngine().getTemplate(TEMPLATE);
    this.context.getVelocityContext().put(MODEL, model);
    this.context.getVelocityContext().put(PARAMETERS, parameters);
}
 
Example #2
Source File: VelocityTemplateParser.java    From eagle with 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 #3
Source File: StringResourceLoaderRepositoryTestCase.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
public void testAlternateStaticRepo() throws Exception
{
    VelocityEngine engine = newStringEngine("alternate.repo", true);
    // should be null be for init
    StringResourceRepository repo = getRepo("alternate.repo", null);
    assertNull(repo);
    engine.init();
    // and not null after init
    repo = getRepo("alternate.repo", null);
    assertNotNull(repo);
    repo.putStringResource("foo", "This is NOT $foo");

    // get and merge template with the same name from both runtimes with the same context
    String engineOut = render(engine.getTemplate("foo"));
    String singletonOut = render(RuntimeSingleton.getTemplate("foo"));

    // make sure they're NOT equal
    assertFalse(engineOut.equals(singletonOut));
}
 
Example #4
Source File: StringResourceLoaderRepositoryTestCase.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
protected StringResourceRepository getRepo(String name, VelocityEngine engine)
{
    if (engine == null)
    {
        if (name == null)
        {
            return StringResourceLoader.getRepository();
        }
        else
        {
            return StringResourceLoader.getRepository(name);
        }
    }
    else
    {
        if (name == null)
        {
            return (StringResourceRepository)engine.getApplicationAttribute(StringResourceLoader.REPOSITORY_NAME_DEFAULT);
        }
        else
        {
            return (StringResourceRepository)engine.getApplicationAttribute(name);
        }
    }
}
 
Example #5
Source File: StringResourceLoaderRepositoryTestCase.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
public void setUp() throws Exception
{
    Velocity.reset();
    Velocity.setProperty(Velocity.RESOURCE_LOADERS, "string");
    Velocity.addProperty("string.resource.loader.class", StringResourceLoader.class.getName());
    Velocity.addProperty("string.resource.loader.modificationCheckInterval", "1");
    Velocity.setProperty(Velocity.RUNTIME_LOG_INSTANCE, new TestLogger());
    Velocity.init();

    StringResourceRepository repo = getRepo(null, null);
    repo.putStringResource("foo", "This is $foo");
    repo.putStringResource("bar", "This is $bar");

    context = new VelocityContext();
    context.put("foo", "wonderful!");
    context.put("bar", "horrible!");
    context.put("woogie", "a woogie");
}
 
Example #6
Source File: VelocityAlertTemplateEngine.java    From eagle with Apache License 2.0 5 votes vote down vote up
@Override
public void init(Config config) {
    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.init();

    stringResourceRepository = (StringResourceRepository) engine.getApplicationAttribute(StringResourceLoader.REPOSITORY_NAME_DEFAULT);
    policyDefinitionRepository = new HashMap<>();
}
 
Example #7
Source File: VelocityTemplateTest.java    From eagle with Apache License 2.0 5 votes vote down vote up
@Test
public void testVelocityTemplate() {
    String templateString = "This alert ($category) was generated because $reason and $REASON from $source at $created_time";
    String resultString = "This alert ($category) was generated because timeout and IO error from localhost at 2016-11-30 05:52:47,053";
    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 repo = (StringResourceRepository) engine.getApplicationAttribute(StringResourceLoader.REPOSITORY_NAME_DEFAULT);
    repo.putStringResource("alert_template", "");
    repo.putStringResource("alert_template", templateString);

    Assert.assertEquals(templateString, repo.getStringResource("alert_template").getBody());

    VelocityContext context = new VelocityContext();
    context.put("reason", "timeout");
    context.put("REASON", "IO error");
    context.put("source","localhost");
    context.put("created_time", "2016-11-30 05:52:47,053");

    Template velocityTemplate = engine.getTemplate("alert_template");
    ASTprocess data = (ASTprocess) velocityTemplate.getData();
    ReferenceContext referenceContext = new ReferenceContext();
    data.jjtAccept(referenceContext,null);
    Assert.assertEquals(5, referenceContext.getReferences().size());
    StringWriter writer = new StringWriter();
    velocityTemplate.merge(context, writer);
    velocityTemplate.process();
    Assert.assertEquals(resultString, writer.toString());
}
 
Example #8
Source File: TemplateEngine.java    From gp2srv with GNU Lesser General Public License v3.0 5 votes vote down vote up
private StringResourceRepository initStringResourceRepository(Map<String, String> pathToTempalteMapping) throws IOException {
	StringResourceRepository result = new StringResourceRepositoryImpl();
	StringResourceLoader.setRepository(StringResourceLoader.REPOSITORY_NAME_DEFAULT, result);
	registerResource(result, RuntimeConstants.VM_LIBRARY_DEFAULT, RuntimeConstants.VM_LIBRARY_DEFAULT);
	for (Map.Entry<String, String> pathToTempalteMappingItem : pathToTempalteMapping.entrySet()) {
		registerResource(result, pathToTempalteMappingItem.getKey(), pathToTempalteMappingItem.getValue());
	}
	return result;
}
 
Example #9
Source File: VelocityViewTag.java    From velocity-tools with Apache License 2.0 5 votes vote down vote up
public StringResourceRepository getRepository()
{
    if (this.repository == null)
    {
        setRepository(StringResourceLoader.getRepository());
    }
    return this.repository;
}
 
Example #10
Source File: StringResourceLoaderRepositoryTestCase.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
public void testAlternateAppRepo() throws Exception
{
    VelocityEngine engine = newStringEngine("alternate.app.repo", false);
    engine.init();

    StringResourceRepository repo = getRepo("alternate.app.repo", engine);
    assertNotNull(repo);
    repo.putStringResource("you/foo.vm", "You look $foo");

    String out = render(engine.getTemplate("you/foo.vm"));
    assertEquals(out, "You look wonderful!");
}
 
Example #11
Source File: StringResourceLoaderRepositoryTestCase.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
public void testAppRepo() throws Exception
{
    VelocityEngine engine = newStringEngine(null, false);
    engine.init();

    StringResourceRepository repo = getRepo(null, engine);
    assertNotNull(repo);
    repo.putStringResource("woogie", "What is $woogie?");

    String out = render(engine.getTemplate("woogie"));
    assertEquals(out, "What is a woogie?");
}
 
Example #12
Source File: Velocity702TestCase.java    From velocity-engine with Apache License 2.0 4 votes vote down vote up
private StringResourceRepository getLowRepo()
{
    return (StringResourceRepository)engine.getApplicationAttribute("low");
}
 
Example #13
Source File: Velocity702TestCase.java    From velocity-engine with Apache License 2.0 4 votes vote down vote up
private StringResourceRepository getHighRepo()
{
    return (StringResourceRepository)engine.getApplicationAttribute("high");
}
 
Example #14
Source File: StringResourceLoader.java    From velocity-engine with 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 #15
Source File: StringResourceLoader.java    From velocity-engine with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a reference to the default static repository.
 * @return default static repository
 */
public static StringResourceRepository getRepository()
{
    return getRepository(REPOSITORY_NAME_DEFAULT);
}
 
Example #16
Source File: VelocityViewTag.java    From velocity-tools with Apache License 2.0 4 votes vote down vote up
public void setRepository(StringResourceRepository repo)
{
    this.repository = repo;
}
 
Example #17
Source File: TemplateEngine.java    From gp2srv with GNU Lesser General Public License v3.0 4 votes vote down vote up
private void registerResource(StringResourceRepository repo, String registeredName, String relativeClasspathRef) throws IOException {
	String templateClasspathRef = templatesClasspathPrefix + relativeClasspathRef.replaceAll("\\.\\./", "");
	InputStream templateBodyInputStream = GPhoto2Server.class.getResourceAsStream(templateClasspathRef);
	String templateBodyString = IOUtils.toString(templateBodyInputStream, "UTF-8");
	repo.putStringResource(registeredName, templateBodyString);
}
 
Example #18
Source File: StringResourceLoader.java    From velocity-engine with Apache License 2.0 2 votes vote down vote up
/**
 * Removes the {@link StringResourceRepository} stored under the specified
 * name.
 * @param name
 * @return removed repository
 * @since 1.6
 */
public static StringResourceRepository removeRepository(String name)
{
    return (StringResourceRepository)STATIC_REPOSITORIES.remove(name);
}
 
Example #19
Source File: StringResourceLoader.java    From velocity-engine with Apache License 2.0 2 votes vote down vote up
/**
 * Sets the specified {@link StringResourceRepository} in static storage
 * under the specified name.
 * @param name
 * @param repo
 * @since 1.6
 */
public static void setRepository(String name, StringResourceRepository repo)
{
    STATIC_REPOSITORIES.put(name, repo);
}
 
Example #20
Source File: StringResourceLoader.java    From velocity-engine with Apache License 2.0 2 votes vote down vote up
/**
 * Returns a reference to the repository stored statically under the
 * specified name.
 * @param name
 * @return named repository
 * @since 1.6
 */
public static StringResourceRepository getRepository(String name)
{
    return (StringResourceRepository)STATIC_REPOSITORIES.get(name);
}