public CodeGenerator(CodeGeneratorContext context, M model, Writer writer, URL templateUrl, String templateResource, Set<Class<? extends Directive>> directives) { this.context = context != null ? context : new CodeGeneratorContext(); this.model = model; this.writer = writer; this.templateResource = templateResource; this.templateUrl = templateUrl; this.directives = directives; StringResourceRepository repo = StringResourceLoader.getRepository(); try { repo.putStringResource(TEMPLATE, 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); }
private VelocityEngine buildVelocityEngine() throws IOException { if(site == null) throw new SiteNotLoadedException(); // merge the configs Map<String, String> velConfig = ConfigurationUtil.getProperties(mergedSiteConfig, "velocity", true); Properties props = new Properties(); props.putAll(velConfig); VelocityEngine ve = new VelocityEngine(); ve.init(props); StringResourceRepository repo = StringResourceLoader.getRepository(); // add site specific macros if(site.getMacros() != null) for(Macro macro : site.getMacros()) repo.putStringResource(macro.getName(), macro.getText()); // add content.vm // String content = IOUtils.toString(SiteManager.class.getResourceAsStream("/vm/content.vm")); // repo.putStringResource("content.vm", content); logger.info("*** VelocityEngine successful initialized for: {}", site.getUrl()); return ve; }
/** * Generate a script from the specified template * using the given object map. * * @param template * @param objMap * * @return script * * @throws IOException */ public String generateScript(PraatScriptContext ctx) throws IOException { final Properties p = new Properties(); p.setProperty(RuntimeConstants.RESOURCE_LOADER, "string"); p.setProperty("string.resource.loader.class", "org.apache.velocity.runtime.resource.loader.StringResourceLoader"); final VelocityEngine ve = new VelocityEngine(); ve.init(p); if(scriptTemplate == null || scriptTemplate.length() == 0) { // install string and set template name scriptTemplate = UUID.randomUUID().toString(); StringResourceRepository repository = StringResourceLoader.getRepository(); repository.putStringResource(scriptTemplate, scriptText); } // load template final Template t = ve.getTemplate(getScriptTemplate()); final StringWriter sw = new StringWriter(); t.merge(ctx.velocityContext(), sw); return sw.toString(); }
public String merge(NodeWizardReportContext ctx) { // TODO move velocity init somewhere else final Properties p = new Properties(); try { p.load(getClass().getResourceAsStream("velocity.properties")); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e); } final VelocityEngine ve = new VelocityEngine(); ve.init(p); StringResourceRepository repository = StringResourceLoader.getRepository(); repository.putStringResource(getName(), getTemplate(), "UTF-8"); // load template final Template t = ve.getTemplate(getName(), "UTF-8"); final StringWriter sw = new StringWriter(); t.merge(ctx.velocityContext(), sw); return sw.toString(); }
/** * Initialization of a VelocityEngine for a {@link Site}. <i>It is necessary to have different {@link VelocityEngine}s because we need different * configurations for each site, e.g. velocity macros. </i> <br> * The VelocityEngines are managed by the {@link SiteHolder}, so the engine can live and die with the site object. * * @param site * @return VelocityEngine */ public static VelocityEngine getSiteEngine(final Site site) { logger.debug("Entered initEngine."); Properties commonProperties = InitializationManager.getBean(PropertiesManager.class).getVelocityProperties(); VelocityEngine velocityEngine = new VelocityEngine(); try { velocityEngine.init(commonProperties); StringResourceRepository repo = StringResourceLoader.getRepository(); // add site specific macros if (site.getMacros() != null) for (Macro macro : site.getMacros()) repo.putStringResource(macro.getName(), macro.getText()); // add content.vm repo.putStringResource("content.vm", FileTool.toString(new File(InitializationManager.getDefaultResourcesPath(), "content.vm"))); logger.info("*** VelocityEngine is initialized for: ".concat(site.getUrl())); } catch (Exception e) { throw new FatalException("Error initializing a VelocityEngine for: " + site.getUrl(), e); } return velocityEngine; }
/** * This method will return a {@link Template} object containing the requested * template. This method will also throw a {@link RuntimeException} if the * template could not be loaded, in which case you probably specified the * wrong file. * * @param templatePath The template file to load. * * @return The loaded {@link Template} object. */ public Template getTemplate(final String templatePath) { synchronized (engine) { if (!engine.resourceExists(templatePath)) { StringResourceRepository repo = StringResourceLoader.getRepository(); repo.putStringResource(templatePath, getTemplateFromResource(templatePath)); } try { return engine.getTemplate(templatePath); } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); throw new DevHubException(e); } } }
private String applyVelocityTemplate(String templateData) throws Exception { Properties properties = new Properties(); properties.setProperty("resource.loader", "string"); properties.setProperty("string.resource.loader.class", "org.apache.velocity.runtime.resource.loader.StringResourceLoader"); properties.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogSystem"); properties.setProperty("userdirective", "com.github.xmltopdf.MoneyUAHDirective," + "com.github.xmltopdf.MoneyToStrDirective," + "com.github.xmltopdf.DateDirective," + "com.github.xmltopdf.UkrToLatinDirective"); Velocity.init(properties); StringResourceRepository repo = StringResourceLoader.getRepository(); repo.putStringResource("template", templateData); Template template = Velocity.getTemplate("template", "UTF-8"); StringWriter writer = new StringWriter(); VelocityContext context = new VelocityContext(); context.put("xml", xmlTag); template.merge(context, writer); writer.flush(); writer.close(); return writer.toString(); }
/** * Create an instance. * @param header The fixed header * @param footer The fixed footer * @param row The template for the rows */ public VelocityTemplate(String header, String footer, String row) { super(header, footer); VelocityEngine engine = new VelocityEngine(); 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 repository = (StringResourceRepository)engine.getApplicationAttribute( StringResourceLoader.REPOSITORY_NAME_DEFAULT); repository.putStringResource(TEMPLATE_NAME, row); template = engine.getTemplate(TEMPLATE_NAME); }
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; }
private void updateTemplates() { LOG.info("Updating template cache..."); StringResourceRepository repo = StringResourceLoader.getRepository(); URI uri = path.toUri(); if (uri == null) { LOG.error("Could not locate templates folder!"); return; } File dir = new File(uri); File[] templates = dir.listFiles(new FilenameFilter() { @Override public boolean accept(File arg0, String arg1) { boolean isTemplateFile = arg1 != null && arg1.endsWith(".tpl"); if (!isTemplateFile) { return false; } return fileHasBeenModified(new File(arg0, arg1)); } }); if (templates != null && templates.length > 0) { for (File template : templates) { repo.putStringResource(template.getName(), getTemplateFromResource(template.getName())); } } }
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); }