Java Code Examples for com.github.jknack.handlebars.Template

The following examples show how to use com.github.jknack.handlebars.Template. These examples are extracted from open source projects. 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 Project: arcusplatform   Author: arcus-smart-home   File: ObjCProcessor.java    License: Apache License 2.0 6 votes vote down vote up
protected void applyTemplates(List<CapabilityDefinition> capabilities,
      List<ServiceDefinition> services,
      List<ProtocolDefinition> protocols) throws IOException {
   Map<String, List<? extends Definition>> definitions
      = new HashMap<String, List<? extends Definition>>();
   definitions.put("capabilities", capabilities);
   definitions.put("services", services);
   definitions.put("protocols", protocols);

   Template template = handlebars.compile(templateName);
   OutputStreamWriter writer = new OutputStreamWriter(System.out);
   try {
      template.apply(definitions, writer);
      writer.flush();
   }
   finally {
      writer.close();
   }
}
 
Example #2
Source Project: arcusplatform   Author: arcus-smart-home   File: JavaProcessor.java    License: Apache License 2.0 6 votes vote down vote up
protected void applyTemplates(
      List<CapabilityDefinition> capabilities, 
      List<ServiceDefinition> services,
      List<ProtocolDefinition> protocols,
      List<TypeDefinition> types
) throws IOException {
   Map<String, List<? extends Definition>> definitions 
      = new HashMap<String, List<? extends Definition>>();
   definitions.put("capabilities", capabilities);
   definitions.put("services", services);
   definitions.put("protocols", protocols);
   definitions.put("types", types);
         
   Template template = handlebars.compile(templateName);
   OutputStreamWriter writer = new OutputStreamWriter(System.out);
   try {
      template.apply(definitions, writer);
      writer.flush();
   }
   finally {
      writer.close();
   }
}
 
Example #3
Source Project: krazo   Author: eclipse-ee4j   File: HandlebarsViewEngine.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void processView(ViewEngineContext context) throws ViewEngineException {
    handlebars.with(new ServletContextTemplateLoader(servletContext, getViewFolder(context)));

    Map<String, Object> model = new HashMap<>(context.getModels().asMap());
    model.put("request", context.getRequest(HttpServletRequest.class));

    Charset charset = resolveCharsetAndSetContentType(context);

    try (Writer writer = new OutputStreamWriter(context.getOutputStream(), charset);

        InputStream resourceAsStream = servletContext.getResourceAsStream(resolveView(context));
        InputStreamReader in = new InputStreamReader(resourceAsStream, "UTF-8");
        BufferedReader bufferedReader = new BufferedReader(in);) {

        String viewContent = bufferedReader.lines().collect(Collectors.joining());

        Template template = handlebars.compileInline(viewContent);
        template.apply(model, writer);

    } catch (IOException e) {
        throw new ViewEngineException(e);
    }
}
 
Example #4
Source Project: product-microgateway   Author: wso2   File: CodegenUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Compile given template.
 *
 * @param defaultTemplateDir template directory
 * @param templateName template name
 * @return Generated template
 * @throws IOException if file read went wrong
 */
public static Template compileTemplate(String defaultTemplateDir, String templateName) throws IOException {
    String templatesDirPath = System.getProperty(GeneratorConstants.TEMPLATES_DIR_PATH_KEY, defaultTemplateDir);
    ClassPathTemplateLoader cpTemplateLoader = new ClassPathTemplateLoader((templatesDirPath));
    FileTemplateLoader fileTemplateLoader = new FileTemplateLoader(templatesDirPath);
    cpTemplateLoader.setSuffix(GeneratorConstants.TEMPLATES_SUFFIX);
    fileTemplateLoader.setSuffix(GeneratorConstants.TEMPLATES_SUFFIX);

    Handlebars handlebars = new Handlebars().with(cpTemplateLoader, fileTemplateLoader);
    handlebars.setStringParams(true);
    handlebars.registerHelpers(StringHelpers.class);
    handlebars.registerHelper("equals", (object, options) -> {
        Object param0 = options.param(0, null);

        if (param0 == null) {
            throw new IllegalArgumentException("found 'null', expected 'string'");
        }
        if (object != null && object.toString().equals(param0.toString())) {
                return options.fn(options.context);
        }

        return options.inverse();
    });

    return handlebars.compile(templateName);
}
 
Example #5
Source Project: spring-cloud-release   Author: spring-cloud   File: TemplateGenerator.java    License: Apache License 2.0 6 votes vote down vote up
File generate(List<Project> projects,
		List<ConfigurationProperty> configurationProperties) {
	PathMatchingResourcePatternResolver resourceLoader = new PathMatchingResourcePatternResolver();
	try {
		Resource[] resources = resourceLoader
				.getResources("templates/spring-cloud/*.hbs");
		List<TemplateProject> templateProjects = templateProjects(projects);
		for (Resource resource : resources) {
			File templateFile = resource.getFile();
			File outputFile = new File(outputFolder, renameTemplate(templateFile));
			Template template = template(templateFile.getName().replace(".hbs", ""));
			Map<String, Object> map = new HashMap<>();
			map.put("projects", projects);
			map.put("springCloudProjects", templateProjects);
			map.put("properties", configurationProperties);
			String applied = template.apply(map);
			Files.write(outputFile.toPath(), applied.getBytes());
			info("Successfully rendered [" + outputFile.getAbsolutePath() + "]");
		}
	}
	catch (IOException e) {
		throw new IllegalStateException(e);
	}
	return outputFolder;
}
 
Example #6
Source Project: sling-samples   Author: apache   File: HandlebarsScriptEngine.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object eval(String script, ScriptContext context) throws ScriptException {
    final Resource resource = (Resource) context.getBindings(ScriptContext.ENGINE_SCOPE).get(SlingBindings.RESOURCE);
    final PrintWriter out = (PrintWriter) context.getBindings(ScriptContext.ENGINE_SCOPE).get(SlingBindings.OUT);

    try {
        final Handlebars handlebars = setupHandlebars();
        final Template template = handlebars.compileInline(script);
        out.println(template.apply(getData(resource)));
    } catch(IOException ioe) {
        final ScriptException up = new ScriptException("IOException in eval");
        up.initCause(ioe);
        throw up;
    }
    return null;
}
 
Example #7
Source Project: ozark   Author: mvc-spec   File: HandlebarsViewEngine.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void processView(ViewEngineContext context) throws ViewEngineException {

    Map<String, Object> model = new HashMap<>(context.getModels().asMap());
    model.put("request", context.getRequest(HttpServletRequest.class));
    
    Charset charset = resolveCharsetAndSetContentType(context);

    try (Writer writer = new OutputStreamWriter(context.getOutputStream(), charset);
         
        InputStream resourceAsStream = servletContext.getResourceAsStream(resolveView(context));
        InputStreamReader in = new InputStreamReader(resourceAsStream, "UTF-8");
        BufferedReader bufferedReader = new BufferedReader(in);) {

        String viewContent = bufferedReader.lines().collect(Collectors.joining());

        Template template = handlebars.compileInline(viewContent);
        template.apply(model, writer);
        
    } catch (IOException e) {
        throw new ViewEngineException(e);
    }
}
 
Example #8
Source Project: bootstraped-multi-test-results-report   Author: web-innovate   File: TestNgReportBuilder.java    License: MIT License 6 votes vote down vote up
private void generateHtmlReport(Template templateTestClassReport, TestModel tm) throws IOException {
    for (ClassModel cm : tm.getClasses()) {

        File file = new File(classesSummaryPath + tm.getName() + cm.getName() + ".html");
        if (!file.exists()) {
            file.getParentFile().mkdirs();
            file.createNewFile();
        }
        OutputStream os =
            new FileOutputStream(file);

        PrintWriter rw = new PrintWriter(os);
        rw.print(templateTestClassReport.apply(cm));
        rw.close();
        os.close();
    }
}
 
Example #9
Source Project: bootstraped-multi-test-results-report   Author: web-innovate   File: CucumberReportBuilder.java    License: MIT License 6 votes vote down vote up
private void writeFeaturePassedReport() throws IOException {
    Template template = bars.compile(FEATURE_OVERVIEW_REPORT);

    List<Feature> onlyPassed = new ArrayList<>(getProcessedFeatures());
    for (Iterator<Feature> it = onlyPassed.listIterator(); it.hasNext(); ) {

        Feature f = it.next();
        if (f.getOverallStatus().equalsIgnoreCase(Constants.FAILED)) {
            it.remove();
        }
    }

    AllFeatureReports allFeatures = new AllFeatureReports(FEATURES_PASSED_OVERVIEW, onlyPassed);
    FileUtils.writeStringToFile(new File(REPORTS_OVERVIEW_PATH + FEATURES_PASSED_HTML),
        template.apply(allFeatures));
}
 
Example #10
Source Project: bootstraped-multi-test-results-report   Author: web-innovate   File: RSpecReportBuilder.java    License: MIT License 6 votes vote down vote up
private void writeTestsPassedReport() throws IOException {
    Template template = new Helpers(new Handlebars()).registerHelpers().compile(TEST_OVERVIEW_REPORT);

    List<TestSuiteModel> onlyPassed = new ArrayList<>(processedTestSuites);

    for (Iterator<TestSuiteModel> it = onlyPassed.listIterator(); it.hasNext(); ) {
        TestSuiteModel f = it.next();
        if (f.getOverallStatus().equalsIgnoreCase(Constants.FAILED)) {
            it.remove();
        }
    }

    AllRSpecJUnitReports allTestSuites = new AllRSpecJUnitReports("Passed test suites report", onlyPassed);
    FileUtils.writeStringToFile(new File(TEST_OVERVIEW_PATH + "testsPassed.html"),
        template.apply(allTestSuites));
}
 
Example #11
Source Project: bootstraped-multi-test-results-report   Author: web-innovate   File: RSpecReportBuilder.java    License: MIT License 6 votes vote down vote up
private void writeTestsFailedReport() throws IOException {
    Template template = new Helpers(new Handlebars()).registerHelpers().compile(TEST_OVERVIEW_REPORT);

    List<TestSuiteModel> onlyFailed = new ArrayList<>(processedTestSuites);

    for (Iterator<TestSuiteModel> it = onlyFailed.listIterator(); it.hasNext(); ) {
        TestSuiteModel f = it.next();
        if (f.getOverallStatus().equalsIgnoreCase(Constants.PASSED)) {
            it.remove();
        }
    }

    AllRSpecJUnitReports allTestSuites = new AllRSpecJUnitReports("Failed test suites report", onlyFailed);
    FileUtils.writeStringToFile(new File(TEST_OVERVIEW_PATH + "testsFailed.html"),
        template.apply(allTestSuites));
}
 
Example #12
Source Project: arcusplatform   Author: arcus-smart-home   File: TestTemplatesCompile.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testTemplatesCompile() throws Exception {
   TemplateLoader loader = new IrisResourceLoader("templates", 0);
   Handlebars handlebars = 
         new Handlebars(loader)
            .registerHelper(EnumHelper.NAME, EnumHelper.INSTANCE)
            .registerHelpers(HandlebarsHelpersSource.class)
            .registerHelper(IfEqualHelper.NAME, IfEqualHelper.INSTANCE)
            .registerHelpers(StringHelpers.class);
   Validator v = new Validator();
   String templateDir =
         Resources
            .getResource("templates")
            .getUri()
            .toURL()
            .getPath();
   for(File template: new File(templateDir).listFiles((file) -> file != null && file.getName() != null && file.getName().endsWith(".hbs"))) {
      try {
         String name = template.getName();
         name = name.substring(0, name.length() - 4);
         Template tpl = handlebars.compile(name);
         if(name.endsWith("-email")) {
            // TODO validate email xml
            continue;
         }
         
         String body  = tpl.apply(Context.newContext(Collections.emptyMap()));
         JSON.fromJson(body, Map.class);
      }
      catch(Exception e) {
         e.printStackTrace();
         v.error("Failed to compile: " + template.getName() + " -- " + e.getMessage());
      }
   }
   v.throwIfErrors();
}
 
Example #13
Source Project: arcusplatform   Author: arcus-smart-home   File: TestMessages.java    License: Apache License 2.0 5 votes vote down vote up
@Override
   public String render(String templateId, Object context) {
Template template;
      try {
       template = handlebars.compileInline(templates.get(templateId));
       return template.apply(context);
      } catch (IOException e) {
       Assert.fail("Unable to apply template");
       return null;
      }			
   }
 
Example #14
Source Project: arcusplatform   Author: arcus-smart-home   File: ObjCProcessor.java    License: Apache License 2.0 5 votes vote down vote up
public String apply(Object context, Template template, String fileName)
throws IOException {
   try {
      String java = template.apply(context);
      writeFile(fileName, java);
      logger.info("Class generated [{}]", fileName);
      return fileName;

   } catch (IOException e) {
      logger.error("Could not create capability file for " + context, e);
      throw e;
   }
}
 
Example #15
Source Project: arcusplatform   Author: arcus-smart-home   File: BackboneViewProcessor.java    License: Apache License 2.0 5 votes vote down vote up
public String apply(Object context, Template template, String fileName) throws IOException {
    try {
        String java = template.apply(context);
        writeFile(fileName, java);
        logger.info("Class generated [{}]", fileName);
        return fileName;

    } catch (IOException e) {
        logger.error("Could not create capability file for " + context, e);
        throw e;
    }
}
 
Example #16
Source Project: arcusplatform   Author: arcus-smart-home   File: HTMLProcessor.java    License: Apache License 2.0 5 votes vote down vote up
public void createFrameSet(DefinitionIndex index) throws IOException {
   try {
      Template template = handlebars.compile("capframe");
      String html = template.apply(index.getCapabilities().get(0).getHtmlFile());
      writeFile("index.html", html);
      logger.info("Frameset created");
   } catch (IOException e) {
      logger.error("Could not create fameset page");
      throw e;
   }
}
 
Example #17
Source Project: arcusplatform   Author: arcus-smart-home   File: HTMLProcessor.java    License: Apache License 2.0 5 votes vote down vote up
public void createIndexFrame(DefinitionIndex index) throws IOException {
   try {
      Template template = handlebars.compile("capindex");
      String html = template.apply(index);
      writeFile("capability-index.html", html);
      logger.info("Index frame created");
   } catch (IOException e) {
      logger.error("Could not create capability index page");
      throw e;
   }
}
 
Example #18
Source Project: spring-cloud-release   Author: spring-cloud   File: HandlebarsHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static Template template(String templateName) {
	try {
		Handlebars handlebars = new Handlebars(
				new ClassPathTemplateLoader("/templates/spring-cloud/"));
		handlebars.registerHelper("replace", StringHelpers.replace);
		handlebars.registerHelper("capitalizeFirst", StringHelpers.capitalizeFirst);
		return handlebars.compile(templateName);
	}
	catch (IOException e) {
		throw new IllegalStateException(e);
	}
}
 
Example #19
Source Project: arcusplatform   Author: arcus-smart-home   File: JavaProcessor.java    License: Apache License 2.0 5 votes vote down vote up
public void createClasses(Object context) throws IOException {
   Template template = handlebars.compile(templateName);
   OutputStreamWriter writer = new OutputStreamWriter(System.out);
   try {
      template.apply(context, writer);
      writer.flush();
   }
   finally {
      writer.close();
   }
}
 
Example #20
Source Project: arcusplatform   Author: arcus-smart-home   File: JavaProcessor.java    License: Apache License 2.0 5 votes vote down vote up
public String apply(Object context, Template template, String fileName)
throws IOException {
   try {
      String java = template.apply(context);
      writeFile(fileName, java);
      logger.info("Class generated [{}]", fileName);
      return fileName;
      
   } catch (IOException e) {
      logger.error("Could not create java file for " + context, e);
      throw e;
   }
}
 
Example #21
Source Project: arcusplatform   Author: arcus-smart-home   File: JavaProcessor.java    License: Apache License 2.0 5 votes vote down vote up
public String apply(Object context, Template template, String fileName)
throws IOException {
   try {
      String java = template.apply(context);
      writeFile(fileName, java);
      logger.info("Class generated [{}]", fileName);
      return fileName;
      
   } catch (IOException e) {
      logger.error("Could not create capability file for " + context, e);
      throw e;
   }
}
 
Example #22
Source Project: openapi-generator   Author: OpenAPITools   File: HandlebarsEngineAdapter.java    License: Apache License 2.0 5 votes vote down vote up
public String compileTemplate(TemplatingExecutor executor,
                              Map<String, Object> bundle, String templateFile) throws IOException {
    TemplateLoader loader = new AbstractTemplateLoader() {
        @Override
        public TemplateSource sourceAt(String location) {
            return findTemplate(executor, location);
        }
    };

    Context context = Context
            .newBuilder(bundle)
            .resolver(
                    MapValueResolver.INSTANCE,
                    JavaBeanValueResolver.INSTANCE,
                    FieldValueResolver.INSTANCE)
            .build();

    Handlebars handlebars = new Handlebars(loader);
    handlebars.registerHelperMissing((obj, options) -> {
        LOGGER.warn(String.format(Locale.ROOT, "Unregistered helper name '%s', processing template:\n%s", options.helperName, options.fn.text()));
        return "";
    });
    handlebars.registerHelper("json", Jackson2Helper.INSTANCE);
    StringHelpers.register(handlebars);
    handlebars.registerHelpers(ConditionalHelpers.class);
    handlebars.registerHelpers(org.openapitools.codegen.templating.handlebars.StringHelpers.class);
    Template tmpl = handlebars.compile(templateFile);
    return tmpl.apply(context);
}
 
Example #23
Source Project: openapi-generator   Author: OpenAPITools   File: StringHelpersTest.java    License: Apache License 2.0 5 votes vote down vote up
private void evaluate(HashMap<String, Object> data, String template, String expect) throws IOException {

        Context context = Context
                .newBuilder(data)
                .resolver(
                        FieldValueResolver.INSTANCE)
                .build();

        Template tmpl = handlebars.compileInline(template);
        String actual = tmpl.apply(context);
        assertEquals(actual, expect);
    }
 
Example #24
Source Project: sakai   Author: sakaiproject   File: PASystemImpl.java    License: Educational Community License v2.0 5 votes vote down vote up
private String getBannersFooter(Handlebars handlebars, Map<String, Object> context) {
    try {
        Template template = handlebars.compile("templates/banner_footer");

        context.put("bannerJSON", getActiveBannersJSON());

        return template.apply(context);
    } catch (IOException e) {
        log.warn("IOException while getting banners footer", e);
        return "";
    }
}
 
Example #25
Source Project: product-microgateway   Author: wso2   File: ThrottlePolicyGenerator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve generated source content as a String value.
 *
 * @param object context to be used by template engine
 * @return String with populated template
 * @throws IOException when template population fails
 */
private String getContent(ThrottlePolicy object) throws IOException {
    Template template = CodegenUtils.compileTemplate(GeneratorConstants.DEFAULT_TEMPLATE_DIR,
            GeneratorConstants.THROTTLE_POLICY_TEMPLATE_NAME);
    Context context = Context.newBuilder(object)
            .resolver(MapValueResolver.INSTANCE, JavaBeanValueResolver.INSTANCE, FieldValueResolver.INSTANCE)
            .build();

    return template.apply(context);
}
 
Example #26
Source Project: product-microgateway   Author: wso2   File: ThrottlePolicyGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private String getPolicyInitContent(ThrottlePolicyInitializer object)
        throws IOException {
    Template template = CodegenUtils.compileTemplate(GeneratorConstants.DEFAULT_TEMPLATE_DIR,
            GeneratorConstants.THROTTLE_POLICY_INIT_TEMPLATE_NAME);
    Context context = Context.newBuilder(object)
            .resolver(MapValueResolver.INSTANCE, JavaBeanValueResolver.INSTANCE, FieldValueResolver.INSTANCE)
            .build();

    return template.apply(context);
}
 
Example #27
Source Project: spring-cloud-release-tools   Author: spring-cloud   File: BlogTemplateGenerator.java    License: Apache License 2.0 5 votes vote down vote up
BlogTemplateGenerator(Template template, String releaseVersion, File blogOutput,
		Projects projects, ProjectGitHubHandler handler) {
	this.template = template;
	this.releaseVersion = releaseVersion;
	this.blogOutput = blogOutput;
	this.projects = projects;
	this.notesGenerator = new NotesGenerator(handler);
}
 
Example #28
Source Project: spring-cloud-release-tools   Author: spring-cloud   File: TemplateGenerator.java    License: Apache License 2.0 5 votes vote down vote up
public File blog(Projects projects) {
	File blogOutput = file(this.blogOutput);
	String releaseVersion = parsedVersion(projects);
	Template template = template(BLOG_TEMPLATE);
	return new BlogTemplateGenerator(template, releaseVersion, blogOutput, projects,
			this.handler).blog();
}
 
Example #29
Source Project: spring-cloud-release-tools   Author: spring-cloud   File: TemplateGenerator.java    License: Apache License 2.0 5 votes vote down vote up
public File releaseNotes(Projects projects) {
	File output = file(this.releaseNotesOutput);
	String releaseVersion = parsedVersion(projects);
	Template template = template(RELEASE_NOTES_TEMPLATE);
	return new ReleaseNotesTemplateGenerator(template, releaseVersion, output,
			projects, this.handler).releaseNotes();
}
 
Example #30
Source Project: spring-cloud-release-tools   Author: spring-cloud   File: ReleaseNotesTemplateGenerator.java    License: Apache License 2.0 5 votes vote down vote up
ReleaseNotesTemplateGenerator(Template template, String releaseVersion,
		File blogOutput, Projects projects, ProjectGitHubHandler handler) {
	this.template = template;
	this.releaseVersion = releaseVersion;
	this.blogOutput = blogOutput;
	this.projects = projects;
	this.notesGenerator = new NotesGenerator(handler);
}