com.github.jknack.handlebars.Template Java Examples

The following examples show how to use com.github.jknack.handlebars.Template. 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: JavaProcessor.java    From arcusplatform with 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 #2
Source File: CucumberReportBuilder.java    From bootstraped-multi-test-results-report with 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 #3
Source File: RSpecReportBuilder.java    From bootstraped-multi-test-results-report with 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 #4
Source File: RSpecReportBuilder.java    From bootstraped-multi-test-results-report with 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 #5
Source File: CodegenUtils.java    From product-microgateway with 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 #6
Source File: HandlebarsViewEngine.java    From krazo with 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 #7
Source File: TemplateGenerator.java    From spring-cloud-release with 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 #8
Source File: TestNgReportBuilder.java    From bootstraped-multi-test-results-report with 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 File: HandlebarsScriptEngine.java    From sling-samples with 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 #10
Source File: HandlebarsViewEngine.java    From ozark with 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 #11
Source File: ObjCProcessor.java    From arcusplatform with 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 #12
Source File: PASystemImpl.java    From sakai with 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 #13
Source File: PASystemImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@Override
public String getFooter() {
    StringBuilder result = new StringBuilder();

    I18n i18n = getI18n(this.getClass().getClassLoader(), "org.sakaiproject.pasystem.impl.i18n.pasystem");
    Handlebars handlebars = loadHandleBars(i18n);

    Session session = SessionManager.getCurrentSession();

    Map<String, Object> context = new HashMap<String, Object>();

    try {
        Template template = handlebars.compile("templates/shared_footer");

        context.put("portalCDNQuery", PortalUtils.getCDNQuery());
        context.put("sakai_csrf_token", session.getAttribute("sakai.csrf.token"));

        result.append(template.apply(context));
    } catch (IOException e) {
        log.warn("IOException while getting footer", e);
        return "";
    }

    result.append(getBannersFooter(handlebars, context));
    result.append(getPopupsFooter(handlebars, context));
    result.append(getTimezoneCheckFooter(handlebars, context));

    return result.toString();
}
 
Example #14
Source File: VaadinConnectTsGenerator.java    From flow with Apache License 2.0 5 votes vote down vote up
private Helper<String> getMultipleLinesHelper() {
    return (context, options) -> {
        Options.Buffer buffer = options.buffer();
        String[] lines = context.split("\n");
        Context parent = options.context;
        Template fn = options.fn;
        for (String line : lines) {
            buffer.append(options.apply(fn, parent.combine("@line", line)));
        }
        return buffer;
    };
}
 
Example #15
Source File: PASystemImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
private String getPopupsFooter(Handlebars handlebars, Map<String, Object> context) {
    Session session = SessionManager.getCurrentSession();
    User currentUser = UserDirectoryService.getCurrentUser();

    if (currentUser == null || currentUser.getId() == null || "".equals(currentUser.getId())) {
        return "";
    }

    try {
        if (session.getAttribute(POPUP_SCREEN_SHOWN) == null) {
            Popup popup = new PopupForUser(currentUser).getPopup();
            if (popup.isActiveNow()) {
                context.put("popupTemplate", popup.getTemplate());
                context.put("popupUuid", popup.getUuid());
                context.put("popup", true);

                if (currentUser.getId() != null) {
                    // Delivered!
                    session.setAttribute(POPUP_SCREEN_SHOWN, "true");
                }
            }
        }


        Template template = handlebars.compile("templates/popup_footer");
        return template.apply(context);
    } catch (IOException | MissingUuidException e) {
        log.warn("IOException while getting popups footer", e);
        return "";
    }
}
 
Example #16
Source File: PASystemImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
private String getTimezoneCheckFooter(Handlebars handlebars, Map<String, Object> context) {
    if (ServerConfigurationService.getBoolean("pasystem.timezone-check", true)) {

        try {
            Template template = handlebars.compile("templates/timezone_footer");

            return template.apply(context);
        } catch (IOException e) {
            log.warn("Timezone footer failed", e);
            return "";
        }
    } else {
        return "";
    }
}
 
Example #17
Source File: HandlebarsTemplateEngine.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
@Override
public String render(final String templateName, final TemplateContext templateContext) {
    final Template template = compileTemplate(templateName);
    final Context context = contextFactory.create(handlebars, templateName, templateContext);
    try {
        LOGGER.debug("Rendering template " + templateName);
        return template.apply(context);
    } catch (IOException e) {
        throw new TemplateRenderException("Context could not be applied to template " + templateName, e);
    }
}
 
Example #18
Source File: RSpecReportBuilder.java    From bootstraped-multi-test-results-report with MIT License 5 votes vote down vote up
private void writeTestCaseSummaryReport() throws IOException {
    Template template = new Helpers(new Handlebars()).registerHelpers().compile(TEST_SUMMARY_REPORT);
    for (TestSuiteModel ts : processedTestSuites) {
        String content = template.apply(ts);
        FileUtils.writeStringToFile(new File(TEST_SUMMARY_PATH + ts.getUniqueID() + ".html"),
            content);
    }
}
 
Example #19
Source File: HandlebarsTemplateEngine.java    From spark-template-engines with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a handlebars template engine
 *
 * @param resourceRoot the resource root
 */
public HandlebarsTemplateEngine(String resourceRoot) {
    TemplateLoader templateLoader = new ClassPathTemplateLoader();
    templateLoader.setPrefix(resourceRoot);
    templateLoader.setSuffix(null);

    handlebars = new Handlebars(templateLoader);

    // Set Guava cache.
    Cache<TemplateSource, Template> cache = CacheBuilder.newBuilder().expireAfterWrite(10, TimeUnit.MINUTES)
            .maximumSize(1000).build();

    handlebars = handlebars.with(new GuavaTemplateCache(cache));
}
 
Example #20
Source File: ForeverTemplateCache.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Get/Parse a template source.
 *
 * @param source The template source.
 * @param parser The parser.
 * @return A Handlebars template.
 * @throws IOException If we can't read input.
 */
private Template cacheGet(final TemplateSource source, final Parser parser) throws IOException {
    Pair<TemplateSource, Template> entry = cache.get(source);
    if (entry == null) {
        log.debug("Loading: {}", source);
        entry = Pair.of(source, parser.parse(source));
        cache.put(source, entry);
    } else {
        log.debug("Found in cache: {}", source);
    }
    return entry.getValue();
}
 
Example #21
Source File: Templating.java    From StubbornJava with MIT License 5 votes vote down vote up
private String render(Template template, Object data) {
    try {
        // Can't currently get the jackson module working not sure why.
        Map<String, Object> jsonMap = Json.serializer().mapFromJson(Json.serializer().toString(data));
        if (log.isDebugEnabled()) {
            log.debug("rendering template " + template.filename() + "\n" + Json.serializer().toPrettyString(jsonMap));
        }
        return template.apply(jsonMap);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #22
Source File: AllHelperTest.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnsupportedContext_unknownType() throws Exception {

	Context ctx = Context.newContext( new Object());
	Handlebars handlebars = Mockito.mock( Handlebars.class );
	Template tpl = Mockito.mock(  Template.class  );
	Options opts = new Options(
			handlebars, "helper", TagType.SECTION, ctx, tpl, tpl,
			new Object[ 0 ],
			new HashMap<String,Object>( 0 ));

	AllHelper helper = new AllHelper();
	Assert.assertEquals( "", helper.apply( null, opts ));
}
 
Example #23
Source File: CucumberReportBuilder.java    From bootstraped-multi-test-results-report with MIT License 5 votes vote down vote up
private void writeFeatureSummaryReports() throws IOException {
    Template template = bars.compile(FEATURE_SUMMARY_REPORT);
    for (Feature feature : getProcessedFeatures()) {
        String generatedFeatureHtmlContent = template.apply(feature);
        // generatedFeatureSummaryReports.put(feature.getUniqueID(), generatedFeatureHtmlContent);
        FileUtils.writeStringToFile(new File(REPORTS_SUMMARY_PATH + feature.getUniqueID() + ".html"),
            generatedFeatureHtmlContent);
    }
}
 
Example #24
Source File: CloudStorageConfigDetails.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private String generateConfigWithParameters(String sourceTemplate, FileSystemType fileSystemType, Map<String, Object> templateObject) throws IOException {
    String defaultPath = fileSystemType.getDefaultPath();
    Template defaultPathTemplate = handlebars.compileInline(defaultPath, HandlebarTemplate.DEFAULT_PREFIX.key(), HandlebarTemplate.DEFAULT_POSTFIX.key());
    templateObject.put("defaultPath", defaultPathTemplate.apply(templateObject));
    Template template = handlebars.compileInline(sourceTemplate, HandlebarTemplate.DEFAULT_PREFIX.key(), HandlebarTemplate.DEFAULT_POSTFIX.key());
    return template.apply(templateObject);
}
 
Example #25
Source File: JUnitReportBuilder.java    From bootstraped-multi-test-results-report with MIT License 5 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<>(getProcessedTestSuites());
    for (Iterator<TestSuiteModel> it = onlyPassed.listIterator(); it.hasNext(); ) {
        TestSuiteModel f = it.next();
        if (f.getOverallStatus().equalsIgnoreCase(Constants.FAILED)) {
            it.remove();
        }
    }

    AllJUnitReports allTestSuites = new AllJUnitReports("Passed test suites report", onlyPassed);
    FileUtils.writeStringToFile(new File(TEST_OVERVIEW_PATH + "testsPassed.html"),
        template.apply(allTestSuites));
}
 
Example #26
Source File: JUnitReportBuilder.java    From bootstraped-multi-test-results-report with MIT License 5 votes vote down vote up
private void writeTestCaseSummaryReport() throws IOException {
    Template template = new Helpers(new Handlebars()).registerHelpers().compile(TEST_SUMMARY_REPORT);
    for (TestSuiteModel ts : processedTestSuites) {
        String content = template.apply(ts);
        FileUtils.writeStringToFile(new File(TEST_SUMMARY_PATH + ts.getUniqueID() + ".html"),
            content);
    }
}
 
Example #27
Source File: HandlebarsTemplateEngineImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public void render(Map<String, Object> context, String templateFile, Handler<AsyncResult<Buffer>> handler) {
  try {
    String src = adjustLocation(templateFile);
    TemplateHolder<Template> template = getTemplate(src);

    if (template == null) {
      // either it's not cache or cache is disabled
      int idx = src.lastIndexOf('/');
      String prefix = "";
      String basename = src;
      if (idx != -1) {
        prefix = src.substring(0, idx);
        basename = src.substring(idx + 1);
      }
      synchronized (this) {
        loader.setPrefix(prefix);
        template = new TemplateHolder<>(handlebars.compile(basename), prefix);
      }
      putTemplate(src, template);
    }

    Context engineContext = Context.newBuilder(context).resolver(getResolvers()).build();
    handler.handle(Future.succeededFuture(Buffer.buffer(template.template().apply(engineContext))));
  } catch (Exception ex) {
    handler.handle(Future.failedFuture(ex));
  }
}
 
Example #28
Source File: TestNgReportBuilder.java    From bootstraped-multi-test-results-report with MIT License 5 votes vote down vote up
private void writeTestsByNameOverview() throws IOException {
    Template template = new Helpers(new Handlebars()).registerHelpers().compile(testNameOverviewReport);
    AllTestNgReports allTestNgReports =
        new AllTestNgReports("Tests by name overview report", processedTestNgReports);
    FileUtils.writeStringToFile(new File(testOverviewPath + "testsByNameOverview.html"),
        template.apply(allTestNgReports));
}
 
Example #29
Source File: TestNgReportBuilder.java    From bootstraped-multi-test-results-report with MIT License 5 votes vote down vote up
private void writeTestsByClassOverview() throws IOException {
    Template template = new Helpers(new Handlebars()).registerHelpers().compile(testOverviewReport);
    AllTestNgReports allTestNgReports =
        new AllTestNgReports("Tests by class overview report", processedTestNgReports);
    FileUtils.writeStringToFile(new File(testOverviewPath + TESTS_BY_CLASS_OVERVIEW),
        template.apply(allTestNgReports));
}
 
Example #30
Source File: HandlebarsTemplateEngine.java    From spark-template-engines with Apache License 2.0 5 votes vote down vote up
@Override
public String render(ModelAndView modelAndView) {
    String viewName = modelAndView.getViewName();
    try {
        Template template = handlebars.compile(viewName);
        return template.apply(modelAndView.getModel());
    } catch (IOException e) {
        throw new RuntimeIOException(e);
    }
}