org.apache.velocity.runtime.RuntimeConstants Java Examples

The following examples show how to use org.apache.velocity.runtime.RuntimeConstants. 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: 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 #2
Source File: VelocityHelper.java    From consulo with 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 #3
Source File: ScenarioExecutor.java    From testgrid with 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 #4
Source File: XmlUtils.java    From velocity-tools with 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 #5
Source File: BaseTestCase.java    From velocity-tools with 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 #6
Source File: MacroForwardDefineTestCase.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
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 #7
Source File: VelocityViewServlet.java    From velocity-tools with 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 #8
Source File: ScooldServer.java    From scoold with 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 #9
Source File: ResourceExistsTestCase.java    From velocity-engine with 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 #10
Source File: RESTToSOAPMsgTemplate.java    From carbon-apimgt with 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 #11
Source File: ParseWithMacroLibsTestCase.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #12
Source File: SimpleNode.java    From velocity-engine with 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 #13
Source File: ExceptionTestCase.java    From velocity-engine with 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 #14
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 #15
Source File: ConversionHandlerTestCase.java    From velocity-engine with 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 #16
Source File: ASTIdentifier.java    From velocity-engine with 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 #17
Source File: GeneratorUtil.java    From vaadinator with Apache License 2.0 5 votes vote down vote up
public static void runVelocity(BeanDescription desc, Map<String, Object> commonMap, String pckg, String modelPckg,
		String presenterPckg, String viewPckg, String profileName, String templateName, File outFile,
		boolean mandatory, String templatePackage, Log log) throws IOException {
	Velocity.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
	Velocity.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
	Template template;
	// Issue #6: for optional templates check whether it's there
	boolean runTemplate;
	if (mandatory) {
		runTemplate = true;
	} else {
		runTemplate = isTemplateExisting(templateName, templatePackage);
	}
	if (!runTemplate) {
		return;
	}
	template = Velocity.getTemplate(templatePackage + templateName);
	String className = desc != null ? desc.getClassName() : "no description found ";
	log.debug("Create file with template: "+ template.getName() + " for bean " + className + " in profile: " + profileName);
	VelocityContext context = new VelocityContext();
	context.put("bean", desc);
	context.put("common", commonMap);
	context.put("package", pckg);
	context.put("modelPackage", modelPckg);
	context.put("presenterPackage", presenterPckg);
	context.put("viewPackage", viewPckg);
	context.put("profileName", profileName);
	context.put("unicodeUtil", UnicodeUtil.SINGLETON);
	Writer writer = new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8");
	template.merge(context, writer);
	writer.close();
	log.info("Written file: " + outFile);
}
 
Example #18
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 #19
Source File: Velocity702TestCase.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
public void setUpEngine(VelocityEngine engine)
{
    engine.setProperty(RuntimeConstants.RESOURCE_LOADERS, "high,low");
    engine.addProperty("high.resource.loader.class", StringResourceLoader.class.getName());
    engine.addProperty("high.resource.loader.cache", "false");
    engine.addProperty("high.resource.loader.repository.name", "high");
    engine.addProperty("high.resource.loader.repository.static", "false");
    engine.addProperty("high.resource.loader.modificationCheckInterval", "1");
    engine.addProperty("low.resource.loader.class", StringResourceLoader.class.getName());
    engine.addProperty("low.resource.loader.cache", "true");
    engine.addProperty("low.resource.loader.repository.name", "low");
    engine.addProperty("low.resource.loader.repository.static", "false");
    engine.addProperty("low.resource.loader.modificationCheckInterval", "1");
    engine.init();
}
 
Example #20
Source File: Scaffolder.java    From yawp with MIT License 5 votes vote down vote up
private VelocityEngine createVelocityEngine() {
    VelocityEngine ve = new VelocityEngine();
    ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
    ve.init();
    return ve;
}
 
Example #21
Source File: Define.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 *  simple init - get the key
 */
public void init(RuntimeServices rs, InternalContextAdapter context, Node node)
    throws TemplateInitException
{
    super.init(rs, context, node);

    // the first child is the block name (key), the second child is the block AST body
    if ( node.jjtGetNumChildren() != 2 )
    {
        throw new VelocityException("parameter missing: block name at "
             + StringUtils.formatFileString(this),
            null,
            rsvc.getLogContext().getStackTrace());
    }

    /*
     * first token is the name of the block. We don't even check the format,
     * just assume it looks like this: $block_name. Should we check if it has
     * a '$' or not?
     */
    key = node.jjtGetChild(0).getFirstTokenImage().substring(1);

    /*
     * default max depth of two is used because intentional recursion is
     * unlikely and discouraged, so make unintentional ones end fast
     */
    maxDepth = rsvc.getInt(RuntimeConstants.DEFINE_DIRECTIVE_MAXDEPTH, 2);
}
 
Example #22
Source File: IndexTestCase.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
public void setUp() throws Exception
{
    super.setUp();
    engine.setProperty(RuntimeConstants.RUNTIME_REFERENCES_STRICT, Boolean.TRUE);

    context.put("NULL", null);
    context.put("red", "blue");

    int[] a = {1, 2, 3};
    context.put("a", a);
    String[] str = {"a", "ab", "abc"};
    context.put("str", str);

    ArrayList alist = new ArrayList();
    alist.add(1);
    alist.add(2);
    alist.add(3);
    alist.add(a);
    alist.add(null);
    context.put("alist", alist);

    Foo foo = new Foo();
    foo.bar = alist;
    context.put("foo", foo);

    Boo boo = new Boo();
    context.put("boo", boo);
}
 
Example #23
Source File: EmailFormatter.java    From karaf-decanter with Apache License 2.0 5 votes vote down vote up
public EmailFormatter() {
    Properties properties = new Properties();
    properties.setProperty(RuntimeConstants.RESOURCE_LOADERS, "file,classpath");
    properties.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, "/");
    properties.setProperty("resource.loader.classpath.class", ClasspathResourceLoader.class.getName());
    velocityEngine = new VelocityEngine(properties);
}
 
Example #24
Source File: VelocityLoginRenderEngine.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public void init() throws Exception {
	/*try
	{
		styleAble = serverConfigurationService.getBoolean("portal.styleable", false);
		styleAbleContentSummary = serverConfigurationService.getBoolean("portal.styleable.contentSummary", false);
	}
	catch (Exception ex)
	{
		log
				.warn("No Server configuration service available, assuming default settings ");
	}*/
	
	if ( sessionManager == null ) {
		log.warn("No session Manager, assuming test mode ");
	}

	vengine = new VelocityEngine();

	vengine.setApplicationAttribute(ServletContext.class.getName(), context);

	vengine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, new SLF4JLogChute());

	Properties p = new Properties();
	InputStream in = this.getClass().getResourceAsStream(loginConfig);
	if ( in == null ) {
		throw new RuntimeException("Unable to load configuration " + loginConfig);
	} else {
		log.info("Loaded " + loginConfig);
	}
	p.load(in);
	vengine.init(p);
	availableLoginSkins = new ArrayList();
	Map m = new HashMap();
	m.put("name", "defaultskin");
	m.put("display", "Default");
	availableLoginSkins.add(m);

	vengine.getTemplate("/vm/defaultskin/macros.vm");
}
 
Example #25
Source File: CodeGeneratorContext.java    From sundrio with Apache License 2.0 5 votes vote down vote up
public CodeGeneratorContext(VelocityEngine velocityEngine, VelocityContext velocityContext) {
    this.velocityEngine = velocityEngine;
    this.velocityContext = velocityContext;

    this.velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "string");
    this.velocityEngine.setProperty("string.resource.loader.class", StringResourceLoader.class.getName());
    //We are going to use shading so we need to make sure that the following configuration will be shade friendly...
    this.velocityEngine.setProperty(RuntimeConstants.RESOURCE_MANAGER_CLASS, ResourceManagerImpl.class.getName());
    this.velocityEngine.setProperty(RuntimeConstants.RESOURCE_MANAGER_CACHE_CLASS, ResourceCacheImpl.class.getName());
    this.velocityEngine.setProperty(RuntimeConstants.PARSER_POOL_CLASS, ParserPoolImpl.class.getName());
    this.velocityEngine.setProperty(RuntimeConstants.UBERSPECT_CLASSNAME, UberspectImpl.class.getName());
    this.velocityEngine.setProperty("runtime.log.logsystem.class", SystemLogChute.class.getName());

    ClassLoader current = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(VelocityEngine.class.getClassLoader());
        this.velocityEngine.init();

        //Load standard directives
        this.velocityEngine.loadDirective(ClassDirective.class.getCanonicalName());
        this.velocityEngine.loadDirective(MethodDirective.class.getCanonicalName());
        this.velocityEngine.loadDirective(FieldDirective.class.getCanonicalName());
        //Load utility directives
        this.velocityEngine.loadDirective(PluralizeDirective.class.getCanonicalName());
        this.velocityEngine.loadDirective(SingularizeDirective.class.getCanonicalName());
    } finally {
        Thread.currentThread().setContextClassLoader(current);
    }
}
 
Example #26
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 #27
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 #28
Source File: EagleMailClient.java    From eagle with Apache License 2.0 5 votes vote down vote up
public EagleMailClient(final Properties config) {
    try {
        velocityEngine = new VelocityEngine();
        velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,org.apache.velocity.runtime.log.Log4JLogChute.class.getName());
        velocityEngine.setProperty("runtime.log.logsystem.log4j.logger", LOG.getName());
        velocityEngine.init();

        config.put("mail.transport.protocol", "smtp");
        if (Boolean.parseBoolean(config.getProperty(AlertEmailConstants.CONF_MAIL_AUTH))) {
            session = Session.getInstance(config, new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(
                            config.getProperty(AlertEmailConstants.CONF_AUTH_USER),
                            config.getProperty(AlertEmailConstants.CONF_AUTH_PASSWORD)
                            );
                }
            });
        } else {
            session = Session.getInstance(config, new Authenticator() {
            });
        }
        
        final String debugMode = config.getProperty(AlertEmailConstants.CONF_MAIL_DEBUG, "false");
        final boolean debug = Boolean.parseBoolean(debugMode);
        LOG.info("Set email debug mode: " + debugMode);
        session.setDebug(debug);
    } catch (Exception e) {
        LOG.error("Failed to connect to smtp server", e);
    }
}
 
Example #29
Source File: EagleMailClient.java    From eagle with Apache License 2.0 5 votes vote down vote up
public EagleMailClient(final Properties config) {
    try {
        velocityEngine = new VelocityEngine();
        velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, org.apache.velocity.runtime.log.Log4JLogChute.class.getName());
        velocityEngine.setProperty("runtime.log.logsystem.log4j.logger", LOG.getName());
        velocityEngine.init();

        config.put("mail.transport.protocol", "smtp");
        if (Boolean.parseBoolean(config.getProperty(AlertEmailConstants.CONF_MAIL_AUTH))) {
            session = Session.getInstance(config, new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(
                            config.getProperty(AlertEmailConstants.CONF_AUTH_USER),
                            config.getProperty(AlertEmailConstants.CONF_AUTH_PASSWORD)
                            );
                }
            });
        } else {
            session = Session.getInstance(config, new Authenticator() {
            });
        }

        final String debugMode = config.getProperty(AlertEmailConstants.CONF_MAIL_DEBUG, "false");
        final boolean debug = Boolean.parseBoolean(debugMode);
        LOG.info("Set email debug mode: " + debugMode);
        session.setDebug(debug);
    } catch (Exception e) {
        LOG.error("Failed to connect to smtp server", e);
    }
}
 
Example #30
Source File: ASTMathNode.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Object init(InternalContextAdapter context, Object data) throws TemplateInitException
{
    super.init(context, data);
    strictMode = rsvc.getBoolean(RuntimeConstants.STRICT_MATH, false);
    cleanupParserAndTokens();
    return data;
}