Java Code Examples for org.apache.velocity.app.VelocityEngine#init()

The following examples show how to use org.apache.velocity.app.VelocityEngine#init() . 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: ProjectUtil.java    From sunbird-lms-service with MIT License 9 votes vote down vote up
public static String getSMSBody(Map<String, String> smsTemplate) {
  try {
    Properties props = new Properties();
    props.put("resource.loader", "class");
    props.put(
        "class.resource.loader.class",
        "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");

    VelocityEngine ve = new VelocityEngine();
    ve.init(props);
    smsTemplate.put("newline", "\n");
    smsTemplate.put(
        "instanceName",
        StringUtils.isBlank(smsTemplate.get("instanceName"))
            ? ""
            : smsTemplate.get("instanceName"));
    Template t = ve.getTemplate("/welcomeSmsTemplate.vm");
    VelocityContext context = new VelocityContext(smsTemplate);
    StringWriter writer = new StringWriter();
    t.merge(context, writer);
    return writer.toString();
  } catch (Exception ex) {
    ProjectLogger.log("Exception occurred while formating and sending SMS " + ex);
  }
  return "";
}
 
Example 2
Source File: PortalEntityProvider.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public void init() {

		VelocityEngine ve = new VelocityEngine();
		ve.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM, new SLF4JLogChute());

		ve.setProperty("resource.loader", "class");
		ve.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
		// No logging. (If you want to log, you need to set an approrpriate directory in an approrpriate
		// velocity.properties file, or the log will be created in the directory in which tomcat is started, or
		// throw an error if it can't create/write in that directory.)
		ve.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogSystem");
		try {
			ve.init();
			formattedProfileTemplate = ve.getTemplate("org/sakaiproject/portal/entityprovider/profile-popup.vm");
		} catch (Exception e) {
			log.error("Failed to load profile-popup.vm", e);
		}
	}
 
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: DefaultMailPlugin.java    From difido-reports with Apache License 2.0 6 votes vote down vote up
private String populateTemplate(String templateName) {
	VelocityEngine ve = new VelocityEngine();
	ve.init();
	Template t = ve.getTemplate(templateName);
	/* create a context and add data */
	VelocityContext context = new VelocityContext();
	String host = System.getProperty("server.address");
	if (null == host) {
		host = "localhost";
	}
	String port = System.getProperty("server.port");
	if (null == port) {
		port = "8080";
	}
	context.put("host", host);
	context.put("port", port);
	context.put("meta", getMetadata());
	final StringWriter writer = new StringWriter();
	t.merge(context, writer);
	return writer.toString();
}
 
Example 5
Source File: VelocityHelloWorld2.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
public static void main(String args[]) {
	/* 1.初始化 Velocity */
	Properties p = new Properties();
	try {
		p.load(VelocityUtil.class.getResourceAsStream("/template/velocity.properties"));
	} catch (IOException e) {
		e.printStackTrace();
	}
	VelocityEngine velocityEngine = new VelocityEngine();
	velocityEngine.init(p);

	/* 2.创建一个上下文对象 */
	VelocityContext context = new VelocityContext();

	/* 3.添加你的数据对象到上下文 */
	context.put("name", "Victor Zhang");
	context.put("project", "Velocity");

	/* 4.选择一个模板 */
	Template template = velocityEngine.getTemplate("template/hello.vm");

	/* 5.将你的数据与模板合并,产生输出内容 */
	StringWriter sw = new StringWriter();
	template.merge(context, sw);
	System.out.println("final output:\n" + sw);
}
 
Example 6
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 7
Source File: RenderPageServletAction.java    From ureport with Apache License 2.0 5 votes vote down vote up
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
	this.applicationContext=applicationContext;
	ve = new VelocityEngine();
	ve.setProperty(Velocity.RESOURCE_LOADER, "class");
	ve.setProperty("class.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
	ve.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM,new NullLogChute());
	ve.init();	
}
 
Example 8
Source File: VelocityManager.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public VelocityManager()
{
    velocity = new VelocityEngine();
    velocity.setProperty( RuntimeConstants.RESOURCE_LOADER, RESOURCE_LOADER_NAME );
    velocity.setProperty( RESOURCE_LOADER_NAME + ".resource.loader.class", ClasspathResourceLoader.class.getName() );
    velocity.setProperty( "runtime.log.logsystem.log4j.logger", "console" );
    velocity.setProperty( "runtime.log", "" );
            
    velocity.init();
}
 
Example 9
Source File: OldPropertiesTestCase.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Check default properties
 */
public void testNewProperties()
    throws Exception
{
    ve = new VelocityEngine();
    logger = new TestLogger(false, true);
    logger.setEnabledLevel(TestLogger.LOG_LEVEL_WARN);

    // put our test logger where it belongs for this test
    Field loggerField = DeprecationAwareExtProperties.class.getDeclaredField("logger");
    loggerField.setAccessible(true);
    loggerField.set(null, logger);

    logger.on();
    ve.init();
    logger.off();

    // check warnings in the logs
    String log = logger.getLog();
    String logLines[] = log.split("\\r?\\n");
    for (String logLine : logLines)
    {
        Matcher matcher = warnPattern.matcher(logLine);
        if (matcher.matches() && matcher.groupCount() == 2)
        {
            fail("Default properties contain deprecated property '" + matcher.group(1) + "', deprecated in favor of '" + matcher.group(2) + "'");
        }
    }

}
 
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: LoadVelocityDemo.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
/**
 * 加载classpath目录下的vm文件
 */
public static void loadByClasspath() {
	System.out.println("========== loadByClasspath ==========");

	Properties p = new Properties();
	p.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
	VelocityEngine ve = new VelocityEngine();
	ve.init(p);
	Template t = ve.getTemplate("template/hello.vm");

	System.out.println(fillTemplate(t));
}
 
Example 13
Source File: RenderPageServletHandler.java    From urule with Apache License 2.0 5 votes vote down vote up
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
	this.applicationContext=applicationContext;
	ve = new VelocityEngine();
	ve.setProperty(Velocity.RESOURCE_LOADER, "class");
	ve.setProperty("class.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
	ve.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM,new NullLogChute());
	ve.init();	
}
 
Example 14
Source File: ReportGenerator.java    From acmeair with Apache License 2.0 5 votes vote down vote up
private void generateHtmlfile(Map<String, Object> input) {	   
 try{
 	VelocityEngine ve = new VelocityEngine();
 	ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
 	ve.setProperty("classpath.resource.loader.class",ClasspathResourceLoader.class.getName());
 	ve.init();
 	Template template = ve.getTemplate("templates/acmeair-report.vtl");
 	VelocityContext context = new VelocityContext();
 	 	    
 	 
 	for(Map.Entry<String, Object> entry: input.entrySet()){
 		context.put(entry.getKey(), entry.getValue());
 	}
 	context.put("math", new MathTool());
 	context.put("number", new NumberTool());
 	context.put("date", new ComparisonDateTool());
 	
 	Writer file = new FileWriter(new File(searchingLocation
	+ System.getProperty("file.separator") + RESULTS_FILE));	    
 	template.merge( context, file );
 	file.flush();
 	file.close();
   
 }catch(Exception e){
 	e.printStackTrace();
 }
}
 
Example 15
Source File: IssuesReportListener.java    From pitest-descartes with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void runStart() {
    VelocityEngine engine = new VelocityEngine();
    engine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    engine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
    engine.init();

    methodResportTemplate = engine.getTemplate("templates/method-report.vm", "UTF-8");
    indexTemplate = engine.getTemplate("templates/index-report.vm", "UTF-8");

    findings = new ArrayList<>();
}
 
Example 16
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 17
Source File: BuiltInEventHandlerTestCase.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Test reporting of invalid syntax
 * @throws Exception
 */
public void testReportQuietInvalidReferences() throws Exception
{
    VelocityEngine ve = new VelocityEngine();
    ve.setProperty("event_handler.invalid_references.quiet","true");
    ReportInvalidReferences reporter = new ReportInvalidReferences();
    ve.init();

    VelocityContext context = new VelocityContext();
    EventCartridge ec = new EventCartridge();
    ec.addEventHandler(reporter);
    ec.attachToContext(context);

    context.put("a1","test");
    context.put("b1","test");
    context.put("n1", null);
    Writer writer = new StringWriter();

    ve.evaluate(context,writer,"test","$a1 $c1 $a1.length() $a1.foobar() $!c1 $n1 $!n1 #if($c1) nop #end");

    List errors = reporter.getInvalidReferences();
    assertEquals(3,errors.size());
    assertEquals("$c1",((InvalidReferenceInfo) errors.get(0)).getInvalidReference());
    assertEquals("$a1.foobar()",((InvalidReferenceInfo) errors.get(1)).getInvalidReference());
    assertEquals("$c1",((InvalidReferenceInfo) errors.get(2)).getInvalidReference());

    log("Caught invalid references (local configuration).");
}
 
Example 18
Source File: ParserTestCase.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 *  Test to see if we force the first arg to #macro() to be a word
 */
public void testMacro()
    throws Exception
{
    VelocityEngine ve = new VelocityEngine();
    TestLogger logger = new TestLogger();
    ve.setProperty(RuntimeConstants.RUNTIME_LOG_INSTANCE, logger);
    ve.init();

    /*
     * this should work
     */

    String template = "#macro(foo) foo #end";

    ve.evaluate(new VelocityContext(), new StringWriter(), "foo", template);

     /*
      *  this should throw an exception
      */

    template = "#macro($x) foo #end";

    try
    {
        ve.evaluate(new VelocityContext(), new StringWriter(), "foo", template);
        fail("Could evaluate macro with errors!");
    }
    catch(ParseErrorException pe)
    {
        // Do nothing
    }
}
 
Example 19
Source File: ThrottlePolicyTemplateBuilder.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * Generate policy for global level. 
 * @param policy policy with level 'global'. Multiple pipelines are not allowed. Can define more than one condition
 * as set of conditions. all these conditions should be passed as a single pipeline 
 * @return
 * @throws APITemplateException
 */
public String getThrottlePolicyForGlobalLevel(GlobalPolicy policy) throws APITemplateException {
    StringWriter writer = new StringWriter();

    if (log.isDebugEnabled()) {
        log.debug("Generating policy for globalLevel :" + policy.toString());
    }

    if (!(policy instanceof GlobalPolicy)) {
        throw new APITemplateException("Invalid policy level : Has to be 'global'");
    }
    try {
        VelocityEngine velocityengine = new VelocityEngine();
        velocityengine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,
                CommonsLogLogChute.class.getName());
        if (!"not-defined".equalsIgnoreCase(getVelocityLogger())) {
            velocityengine.setProperty(VelocityEngine.RESOURCE_LOADER, "classpath");
            velocityengine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        }
        velocityengine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, CarbonUtils.getCarbonHome());
        velocityengine.init();

        Template template = velocityengine.getTemplate(getTemplatePathForGlobal());

        VelocityContext context = new VelocityContext();
        setConstantContext(context);
        context.put("policy", policy);
       /* if (policy.getPipelines() != null && !policy.getPipelines().isEmpty()) {
            String conditionString = getPolicyCondition(policy.getPipelines().get(0).getConditions());
            context.put("condition", conditionString);
        } else {
            context.put("condition", "");
        }*/
        if (log.isDebugEnabled()) {
            log.debug("Policy : " + writer.toString());
        }
        template.merge(context, writer);
    } catch (Exception e) {
        log.error("Velocity Error", e);
        throw new APITemplateException("Velocity Error", e);
    }

    return writer.toString();
}
 
Example 20
Source File: GatewayBasicFuncTest.java    From knox with Apache License 2.0 4 votes vote down vote up
private void getYarnRmApp( ContentType contentType, boolean running ) throws Exception {
    String username = "hdfs";
    String password = "hdfs-password";
    String path = "/v1/cluster/apps/application_1399541193872_0033/";
    String resource;
    if ( running ) {
      resource = "/yarn/app_running";
    } else {
      resource = "/yarn/app_succeeded";
    }

    switch( contentType ) {
    case JSON:
      resource += ".json";
      break;
    case XML:
      resource += ".xml";
      break;
    default:
      break;
    }
    String gatewayPath = driver.getUrl( "RESOURCEMANAGER" ) + path + (driver.isUseGateway() ? "" : "?user.name=" + username);
    InetSocketAddress gatewayAddress = driver.gateway.getAddresses()[0];
    String gatewayHostName = gatewayAddress.getHostName();
    String gatewayAddrName = InetAddress.getByName( gatewayHostName ).getHostAddress();

    VelocityEngine velocity = new VelocityEngine();
    velocity.setProperty( RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.NullLogSystem" );
    velocity.setProperty( RuntimeConstants.RESOURCE_LOADER, "classpath" );
    velocity.setProperty( "classpath.resource.loader.class", ClasspathResourceLoader.class.getName() );
    velocity.init();

    VelocityContext context = new VelocityContext();
    context.put( "proxy_address", driver.getRealUrl( "RESOURCEMANAGER" ) );

    String name = TestUtils.getResourceName( this.getClass(), resource );
    Template template = velocity.getTemplate( name );
    StringWriter sw = new StringWriter();
    template.merge( context, sw );
    String request = sw.toString();

    driver.getMock( "RESOURCEMANAGER" ).expect().method( "GET" )
        .pathInfo( path ).queryParam( "user.name", username ).respond()
        .status( HttpStatus.SC_OK )
        .content( request.getBytes(StandardCharsets.UTF_8) )
        .contentType( contentType.toString() );

    ResponseSpecification response = given()
//         .log().all()
        .auth()
        .preemptive()
        .basic( username, password )
        .header( "X-XSRF-Header", "jksdhfkhdsf" )
        .then()
//         .log().all()
        .statusCode( HttpStatus.SC_OK )
        .contentType( contentType );
    if ( running ) {
      response.body(
          "app.trackingUrl",
          anyOf(
              startsWith( "http://" + gatewayHostName + ":" + gatewayAddress.getPort() + "/" ),
              startsWith( "http://" + gatewayAddrName + ":" + gatewayAddress.getPort() + "/" ) ) );
    } else {
      response.body( "app.trackingUrl", is(emptyString()) );
    }

    response.body( "app.amContainerLogs", is(emptyString()) )
        .body( "app.amHostHttpAddress", is(emptyString()) )
        .when()
        .get( gatewayPath );

    driver.assertComplete();
  }