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

The following examples show how to use org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader. 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: VelocityTest.java    From snake-yaml with Apache License 2.0 6 votes vote down vote up
public void testTemplate1() throws Exception {
    VelocityContext context = new VelocityContext();
    MyBean bean = createBean();
    context.put("bean", bean);
    Yaml yaml = new Yaml();
    context.put("list", yaml.dump(bean.getList()));
    VelocityEngine ve = new VelocityEngine();
    ve.setProperty("file.resource.loader.class", ClasspathResourceLoader.class.getName());
    ve.init();
    Template t = ve.getTemplate("template/mybean1.vm");
    StringWriter writer = new StringWriter();
    t.merge(context, writer);
    String output = writer.toString().trim().replaceAll("\\r\\n", "\n");
    // System.out.println(output);
    String etalon = Util.getLocalResource("template/etalon2-template.yaml").trim();
    assertEquals(etalon.length(), output.length());
    assertEquals(etalon, output);
    // parse the YAML document
    Yaml loader = new Yaml();
    MyBean parsedBean = loader.loadAs(output, MyBean.class);
    assertEquals(bean, parsedBean);
}
 
Example #2
Source File: APIInfoResource.java    From ontopia with Apache License 2.0 6 votes vote down vote up
@Get
public Representation getAPIInfo() throws IOException {
	TemplateRepresentation r = new TemplateRepresentation("net/ontopia/topicmaps/rest/resources/info.html", MediaType.TEXT_HTML);
	r.getEngine().addProperty(VelocityEngine.RESOURCE_LOADER, "classpath");
	r.getEngine().addProperty("classpath." + VelocityEngine.RESOURCE_LOADER + ".class", ClasspathResourceLoader.class.getName());
	
	Map<Restlet, String> allRoutes = new HashMap<>();
	list(allRoutes, getApplication().getInboundRoot(), "");
	Map<String, Object> data = new HashMap<>();
	data.put("util", this);
	data.put("root", getApplication().getInboundRoot());
	data.put("routes", allRoutes);
	data.put("cutil", ClassUtils.class);
	
	r.setDataModel(data);

	return r;
}
 
Example #3
Source File: OrcasDbDoc.java    From orcas with Apache License 2.0 6 votes vote down vote up
public void execute( Parameters pParameters )
{
  try
  {
    ExtensionHandlerImpl lExtensionHandlerImpl = (ExtensionHandlerImpl) pParameters.getExtensionHandler();

    Properties lProperties = new Properties();
    lProperties.setProperty( RuntimeConstants.RESOURCE_LOADER, "classpath" );
    lProperties.setProperty( "classpath.resource.loader.class", ClasspathResourceLoader.class.getName() );

    Velocity.init( lProperties );

    Schema lSchema = new DbLoader().loadSchema( _diagram, lExtensionHandlerImpl.loadSyexModel(), _tableregistry );
    lSchema.mergeAssociations();

    Main.writeDiagramsRecursive( _diagram, _styles, lSchema, _outfolder, _tmpfolder, pParameters.getModelFile() + "/tables", _tableregistry, _svg, pParameters.getDbdocPlantuml() );
  }
  catch( Exception e )
  {
    throw new RuntimeException( e );
  }
}
 
Example #4
Source File: TestUtils.java    From knox with Apache License 2.0 6 votes vote down vote up
public static String merge( String resource, Properties properties ) {
  ClasspathResourceLoader loader = new ClasspathResourceLoader();
  loader.getResourceStream( resource );

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

  VelocityContext context = new VelocityContext( properties );
  Template template = engine.getTemplate( resource );
  StringWriter writer = new StringWriter();
  template.merge( context, writer );
  return writer.toString();
}
 
Example #5
Source File: EagleMailClient.java    From Eagle with Apache License 2.0 6 votes vote down vote up
public EagleMailClient(AbstractConfiguration configuration) {
	try {
		ConcurrentMapConfiguration con = (ConcurrentMapConfiguration)configuration;
		velocityEngine = new VelocityEngine();
		velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
		velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
		velocityEngine.init();

		con.setProperty("mail.transport.protocol", "smtp");
		final Properties config = con.getProperties();
		if(Boolean.parseBoolean(config.getProperty(AUTH_CONFIG))){
			session = Session.getDefaultInstance(config, new Authenticator() {
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(config.getProperty(USER_CONFIG), config.getProperty(PWD_CONFIG));
				}
			});
		}
		else session = Session.getDefaultInstance(config, new Authenticator() {});
		final String debugMode =  config.getProperty(DEBUG_CONFIG, "false");
		final boolean debug =  Boolean.parseBoolean(debugMode);
		session.setDebug(debug);
	} catch (Exception e) {
           LOG.error("Failed connect to smtp server",e);
	}
}
 
Example #6
Source File: RESTToSOAPMsgTemplate.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * gets in sequence for the soap operation
 *
 * @param mapping       soap to rest mapping json
 * @param method        http method for the resource
 * @param soapAction    soap action for the operation
 * @param namespace     soap namespace for the operation
 * @param soapNamespace soap namespace for the soap version
 * @return in sequence string
 */
public String getMappingInSequence(Map<String, String> mapping, String method, String soapAction, String namespace,
        String soapNamespace, JSONArray array) {

    ConfigContext configcontext = new SOAPToRESTConfigContext(mapping, method, soapAction, namespace, soapNamespace,
            array);
    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 t = velocityengine.getTemplate(this.getInSeqTemplatePath());
        t.merge(context, writer);
    } catch (Exception e) {
        log.error("Velocity Error", e);
    }
    return writer.toString();
}
 
Example #7
Source File: VelocityConfigurer.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Provides a ClasspathResourceLoader in addition to any default or user-defined
 * loader in order to load the spring Velocity macros from the class path.
 * @see org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
 */
@Override
protected void postProcessVelocityEngine(VelocityEngine velocityEngine) {
	velocityEngine.setApplicationAttribute(ServletContext.class.getName(), this.servletContext);
	velocityEngine.setProperty(
			SPRING_MACRO_RESOURCE_LOADER_CLASS, ClasspathResourceLoader.class.getName());
	velocityEngine.addProperty(
			VelocityEngine.RESOURCE_LOADER, SPRING_MACRO_RESOURCE_LOADER_NAME);
	velocityEngine.addProperty(
			VelocityEngine.VM_LIBRARY, SPRING_MACRO_LIBRARY);

	if (logger.isInfoEnabled()) {
		logger.info("ClasspathResourceLoader with name '" + SPRING_MACRO_RESOURCE_LOADER_NAME +
				"' added to configured VelocityEngine");
	}
}
 
Example #8
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 #9
Source File: MarkdownRenderer.java    From bazel with Apache License 2.0 6 votes vote down vote up
public MarkdownRenderer(
    String headerTemplate,
    String ruleTemplate,
    String providerTemplate,
    String functionTemplate,
    String aspectTemplate) {
  this.headerTemplateFilename = headerTemplate;
  this.ruleTemplateFilename = ruleTemplate;
  this.providerTemplateFilename = providerTemplate;
  this.functionTemplateFilename = functionTemplate;
  this.aspectTemplateFilename = aspectTemplate;

  this.velocityEngine = new VelocityEngine();
  velocityEngine.setProperty("resource.loader", "classpath, jar");
  velocityEngine.setProperty("classpath.resource.loader.class",
      ClasspathResourceLoader.class.getName());
  velocityEngine.setProperty("jar.resource.loader.class", JarResourceLoader.class.getName());
  velocityEngine.setProperty("input.encoding", "UTF-8");
  velocityEngine.setProperty("output.encoding", "UTF-8");
  velocityEngine.setProperty("runtime.references.strict", true);
}
 
Example #10
Source File: VelocityConfigurer.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Provides a ClasspathResourceLoader in addition to any default or user-defined
 * loader in order to load the spring Velocity macros from the class path.
 * @see org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
 */
@Override
protected void postProcessVelocityEngine(VelocityEngine velocityEngine) {
	velocityEngine.setApplicationAttribute(ServletContext.class.getName(), this.servletContext);
	velocityEngine.setProperty(
			SPRING_MACRO_RESOURCE_LOADER_CLASS, ClasspathResourceLoader.class.getName());
	velocityEngine.addProperty(
			VelocityEngine.RESOURCE_LOADER, SPRING_MACRO_RESOURCE_LOADER_NAME);
	velocityEngine.addProperty(
			VelocityEngine.VM_LIBRARY, SPRING_MACRO_LIBRARY);

	if (logger.isInfoEnabled()) {
		logger.info("ClasspathResourceLoader with name '" + SPRING_MACRO_RESOURCE_LOADER_NAME +
				"' added to configured VelocityEngine");
	}
}
 
Example #11
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 #12
Source File: SchemaWriter.java    From qemu-java with GNU General Public License v2.0 6 votes vote down vote up
@Nonnull
private static VelocityEngine newVelocityEngine() {
    VelocityEngine engine = new VelocityEngine();
    engine
            .setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM_CLASS, CommonsLogLogChute.class
            .getName());
    // engine.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM_CLASS, SystemLogChute.class.getName());
    engine.setProperty(VelocityEngine.RESOURCE_LOADER,
            "classpath");
    engine.setProperty(
            "classpath.resource.loader.class", ClasspathResourceLoader.class
            .getName());
    // engine.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_CACHE, "true");
    // engine.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, "velocity/");
    engine.init();
    return engine;
}
 
Example #13
Source File: Container.java    From tomee with Apache License 2.0 6 votes vote down vote up
private void copyTemplateTo(final File targetDir, final String filename) throws Exception {
    final File file = new File(targetDir, filename);
    if (file.exists()) {
        return;
    }

    // don't break apps using Velocity facade
    final VelocityEngine engine = new VelocityEngine();
    engine.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM, new NullLogChute());
    engine.setProperty(Velocity.RESOURCE_LOADER, "class");
    engine.setProperty("class.resource.loader.description", "Velocity Classpath Resource Loader");
    engine.setProperty("class.resource.loader.class", ClasspathResourceLoader.class.getName());
    engine.init();
    final Template template = engine.getTemplate("/org/apache/tomee/configs/" + filename);
    final VelocityContext context = new VelocityContext();
    context.put("tomcatHttpPort", Integer.toString(configuration.getHttpPort()));
    context.put("tomcatShutdownPort", Integer.toString(configuration.getStopPort()));
    final Writer writer = new FileWriter(file);
    template.merge(context, writer);
    writer.flush();
    writer.close();
}
 
Example #14
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 #15
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 #16
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 #17
Source File: TemplateEngine.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new {@link Page} using the given .vm template file path. The template file
 * path must be the resource path for the .vm file in the JAR since the VelocityEngine
 * is configured to load .vm files from JAR resources.
 */
public static Page newPage(String template) {
  VelocityEngine engine = new VelocityEngine();
  engine.setProperty("resource.loader", "classpath, jar");
  engine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
  engine.setProperty("jar.resource.loader.class", JarResourceLoader.class.getName());
  engine.setProperty("input.encoding", "UTF-8");
  engine.setProperty("output.encoding", "UTF-8");
  engine.setProperty("directive.set.null.allowed", true);
  engine.setProperty("parser.pool.size", 3);
  engine.setProperty("runtime.references.strict", true);
  return new Page(engine, template);
}
 
Example #18
Source File: APITemplateBuilderImpl.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the necessary variables to velocity context
 *
 * @param endpointType Type of the endpoint : production or sandbox
 * @return The string of endpoint file content
 * @throws APITemplateException Thrown if an error occurred
 */
@Override
public String getConfigStringForEndpointTemplate(String endpointType) throws APITemplateException {
    StringWriter writer = new StringWriter();

    try {
        ConfigContext configcontext = new APIConfigContext(this.api);
        configcontext = new EndpointBckConfigContext(configcontext, api);
        configcontext = new EndpointConfigContext(configcontext, api);
        configcontext = new TemplateUtilContext(configcontext);

        configcontext.validate();

        VelocityContext context = configcontext.getContext();

        context.internalGetKeys();

        VelocityEngine velocityengine = new VelocityEngine();
        if (!"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.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, CarbonUtils.getCarbonHome());
        initVelocityEngine(velocityengine);

        context.put("type", endpointType);

        Template template = velocityengine.getTemplate(this.getEndpointTemplatePath());

        template.merge(context, writer);

    } catch (Exception e) {
        log.error("Velocity Error");
        throw new APITemplateException("Velocity Error", e);
    }
    return writer.toString();
}
 
Example #19
Source File: ThrottlePolicyTemplateBuilder.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Generate policy for subscription level.
 * @param policy policy with level 'sub'. 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 getThrottlePolicyForSubscriptionLevel(SubscriptionPolicy policy) throws APITemplateException {
    StringWriter writer = new StringWriter();

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

    if (!(policy instanceof SubscriptionPolicy)) {
        throw new APITemplateException("Invalid policy level :  Has to be 'sub'");
    }
    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 t = velocityengine.getTemplate(getTemplatePathForSubscription());

        VelocityContext context = new VelocityContext();
        setConstantContext(context);
        context.put("policy", policy);
        context.put("quotaPolicy", policy.getDefaultQuotaPolicy());
        t.merge(context, writer);
        if (log.isDebugEnabled()) {
            log.debug("Policy : " + writer.toString());
        }
    } catch (Exception e) {
        log.error("Velocity Error", e);
        throw new APITemplateException("Velocity Error", e);
    }

    return writer.toString();
}
 
Example #20
Source File: ThrottlePolicyTemplateBuilder.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Generate application level policy.
 * 
 * @param policy policy with level 'app'. 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 getThrottlePolicyForAppLevel(ApplicationPolicy policy) throws APITemplateException {
    StringWriter writer = new StringWriter();

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

    if (!(policy instanceof ApplicationPolicy)) {
        throw new APITemplateException("Invalid policy level : Has to be 'app'");
    }
    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(getTemplatePathForApplication());

        VelocityContext context = new VelocityContext();
        setConstantContext(context);
        context.put("policy", policy);
        context.put("quotaPolicy", policy.getDefaultQuotaPolicy());
        template.merge(context, writer);
        if (log.isDebugEnabled()) {
            log.debug("Policy : " + writer.toString());
        }

    } catch (Exception e) {
        log.error("Velocity Error", e);
        throw new APITemplateException("Velocity Error", e);
    }
    String str = writer.toString();
    return writer.toString();
}
 
Example #21
Source File: AmbariServiceDefinitionTest.java    From knox with Apache License 2.0 5 votes vote down vote up
public static void startGatewayServer() throws Exception {
  services = new DefaultGatewayServices();
  Map<String,String> options = new HashMap<>();
  options.put( "persist-master", "false" );
  options.put( "master", "password" );
  try {
    services.init( config, options );
  } catch ( ServiceLifecycleException e ) {
    e.printStackTrace(); // I18N not required.
  }
  topos = services.getService(ServiceType.TOPOLOGY_SERVICE);

  gateway = GatewayServer.startGateway( config, services );
  MatcherAssert.assertThat( "Failed to start gateway.", gateway, notNullValue() );

  gatewayPort = gateway.getAddresses()[0].getPort();
  gatewayUrl = "http://localhost:" + gatewayPort + "/" + config.getGatewayPath();
  String topologyPath = "/test-topology";
  clusterPath = "/" + config.getGatewayPath() + topologyPath;
  clusterUrl = gatewayUrl + topologyPath;

  LOG.info( "Gateway port = " + gateway.getAddresses()[ 0 ].getPort() );

  params = new Properties();
  params.put( "AMBARI_URL", "http://localhost:" + mockAmbari.getPort() );

  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();

  context = new VelocityContext();
  context.put( "cluster_url", clusterUrl );
  context.put( "cluster_path", clusterPath );
}
 
Example #22
Source File: HTMLMaker.java    From neoprofiler with Apache License 2.0 5 votes vote down vote up
public void html(DBProfile profile, Writer writer) throws IOException {
	VelocityEngine ve = new VelocityEngine();
       
	ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); 
	ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
	
	ve.init();
       
	Template t = null;
	
	if(ve.resourceExists("/template.html"))
		t = ve.getTemplate("/template.html");
	else {
		try { 
			t = ve.getTemplate("src/main/resources/template.html");				
		} catch(Exception exc) { 
			System.err.println("The application could not find a needed HTML template.");
			System.err.println("This is an unusual problem; please report it as an issue, and provide details of your configuration.");
			throw new RuntimeException("Could not find HTML template as resource.");
		}
	}
	
       VelocityContext context = new VelocityContext();

       StringWriter markdownContent = new StringWriter();
       
       // Write markdown content....
       new MarkdownMaker().markdown(profile, markdownContent);
       
       context.put("title", profile.getName());
       context.put("markdown", markdownContent.getBuffer().toString());
       context.put("links", generateGraph(profile)); 
       //context.put("d3graph", d3graph.toString());

       // Dump the contents of the template merged with the context.  That's it!
       t.merge(context, writer);
}
 
Example #23
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 #24
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 #25
Source File: AbstractVelocityExporter.java    From LicenseScout with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public final void export(final OutputResult outputResult, final ReportConfiguration reportConfiguration)
        throws Exception {
    final File outputFile = reportConfiguration.getOutputFile();
    final Charset charset = ExporterUtil.getOutputCharset(reportConfiguration);
    try (final FileWriter fileWriter = new FileWriter(outputFile, charset);
            final BufferedWriter bw = new BufferedWriter(fileWriter)) {

        Velocity.setProperty(RuntimeConstants.RESOURCE_LOADERS, "file,classpath");
        Velocity.setProperty(RuntimeConstants.RESOURCE_LOADER + ".file.class", FileResourceLoader.class.getName());
        /*
         * NOTE: setting the path to empty is necessary because the default is "." (current
         * directory) and then using absolute path names will not work.
         */
        Velocity.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, "");
        Velocity.setProperty(RuntimeConstants.RESOURCE_LOADER + ".classpath.class",
                ClasspathResourceLoader.class.getName());

        Velocity.init();

        final VelocityContext context = createVelocityContext(outputResult, reportConfiguration);
        final Template template = getTemplate(reportConfiguration);

        try (final StringWriter sw = new StringWriter()) {
            if (template != null) {
                template.merge(context, sw);
            }
            bw.write(sw.getBuffer().toString());
        }
    }
}
 
Example #26
Source File: VelocityKit.java    From kvf-admin with MIT License 5 votes vote down vote up
private static void newEngine() {
    VelocityEngine ve = new VelocityEngine();
    ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
    ve.init();
    velocityEngine = ve;
}
 
Example #27
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 #28
Source File: VelocityService.java    From cloud-portal with MIT License 5 votes vote down vote up
@PostConstruct
public void init() {

    // create velocity engine
    velocityEngine = new VelocityEngine();
    velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
    velocityEngine.init();
}
 
Example #29
Source File: J2clTestingVelocityUtil.java    From j2cl with Apache License 2.0 5 votes vote down vote up
/**
 * Creates and returns a VelocityEngine that will find templates on the
 * classpath.
 */
public static VelocityEngine createEngine() {
  VelocityEngine velocityEngine = new VelocityEngine();
  velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
  velocityEngine.setProperty(
      CLASSPATH_RESOURCE_LOADER_CLASS, ClasspathResourceLoader.class.getName());
  velocityEngine.setProperty("runtime.references.strict", "true");
  velocityEngine.init();
  return velocityEngine;
}
 
Example #30
Source File: VelocityUtil.java    From j2cl with Apache License 2.0 5 votes vote down vote up
/**
 * Creates and returns a VelocityEngine that will find templates on the
 * classpath.
 */
public static VelocityEngine createEngine() {
  VelocityEngine velocityEngine = new VelocityEngine();
  velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
  velocityEngine.setProperty(
      CLASSPATH_RESOURCE_LOADER_CLASS, ClasspathResourceLoader.class.getName());
  velocityEngine.init();
  return velocityEngine;
}