com.mitchellbosecke.pebble.template.PebbleTemplate Java Examples

The following examples show how to use com.mitchellbosecke.pebble.template.PebbleTemplate. 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: CMSURLHandler.java    From fenixedu-cms with GNU Lesser General Public License v3.0 7 votes vote down vote up
private void handleLeadingSlash(final HttpServletRequest req, HttpServletResponse res, Site sites) throws PebbleException,
        IOException, ServletException {
    if (req.getMethod().equals("GET")) {
        res.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
        res.setHeader("Location", rewritePageUrl(req));
        return;
    } else if (req.getMethod().equals("POST")) {
        if (CoreConfiguration.getConfiguration().developmentMode()) {
            PebbleEngine engine = new PebbleEngine.Builder().loader(new StringLoader()).extension(new CMSExtensions()).build();
            PebbleTemplate compiledTemplate =
                    engine.getTemplate("<html><head></head><body><h1>POST action with backslash</h1><b>You posting data with a URL with a backslash. Alter the form to post with the same URL without the backslash</body></html>");
            res.setStatus(500);
            res.setContentType("text/html");
            compiledTemplate.evaluate(res.getWriter(), I18N.getLocale());
        } else {
            renderer.errorPage(req, res, sites, 500);
        }
    }
}
 
Example #2
Source File: QueryTemplater.java    From feast with Apache License 2.0 6 votes vote down vote up
/**
 * Generate the query for point in time correctness join of data for a single feature set to the
 * entity dataset.
 *
 * @param featureSetInfo Information about the feature set necessary for the query templating
 * @param projectId google project ID
 * @param datasetId feast bigquery dataset ID
 * @param leftTableName entity dataset name
 * @param minTimestamp earliest allowed timestamp for the historical data in feast
 * @param maxTimestamp latest allowed timestamp for the historical data in feast
 * @return point in time correctness join BQ SQL query
 */
public static String createFeatureSetPointInTimeQuery(
    FeatureSetQueryInfo featureSetInfo,
    String projectId,
    String datasetId,
    String leftTableName,
    String minTimestamp,
    String maxTimestamp)
    throws IOException {

  PebbleTemplate template = engine.getTemplate(FEATURESET_TEMPLATE_NAME);
  Map<String, Object> context = new HashMap<>();
  context.put("featureSet", featureSetInfo);
  context.put("projectId", projectId);
  context.put("datasetId", datasetId);
  context.put("minTimestamp", minTimestamp);
  context.put("maxTimestamp", maxTimestamp);
  context.put("leftTableName", leftTableName);

  Writer writer = new StringWriter();
  template.evaluate(writer, context);
  return writer.toString();
}
 
Example #3
Source File: PebbleTemplateEngine.java    From pippo with Apache License 2.0 6 votes vote down vote up
private PebbleTemplate getTemplate(String templateName, String localePart) throws PebbleException {
    PebbleTemplate template = null;
    try {
        if (StringUtils.isNullOrEmpty(localePart)) {
            template = engine.getTemplate(templateName);
        } else {
            String localizedName = StringUtils.removeEnd(templateName, "." +
                getFileExtension()) + "_" + localePart;
            template = engine.getTemplate(localizedName);
        }
    } catch (LoaderException e) {
        log.debug(e.getMessage());
    }

    return template;
}
 
Example #4
Source File: PebbleTemplateEngine.java    From pippo with Apache License 2.0 6 votes vote down vote up
@Override
public void renderString(String templateContent, Map<String, Object> model, Writer writer) {
    String language = (String) model.get(PippoConstants.REQUEST_PARAMETER_LANG);

    if (StringUtils.isNullOrEmpty(language)) {
        language = getLanguageOrDefault(language);
    }
    Locale locale = (Locale) model.get(PippoConstants.REQUEST_PARAMETER_LOCALE);
    if (locale == null) {
        locale = getLocaleOrDefault(language);
    }

    try {
        PebbleEngine stringEngine = new PebbleEngine.Builder()
            .loader(new StringLoader())
            .strictVariables(engine.isStrictVariables())
            .templateCache(null)
            .build();

        PebbleTemplate template = stringEngine.getTemplate(templateContent);
        template.evaluate(writer, model, locale);
        writer.flush();
    } catch (Exception e) {
        throw new PippoRuntimeException(e);
    }
}
 
Example #5
Source File: ClasspathResourceFunction.java    From pippo with Apache License 2.0 6 votes vote down vote up
@Override
public Object execute(Map<String, Object> args, PebbleTemplate self, EvaluationContext context, int lineNumber) {
    if (patternRef.get() == null) {
        String pattern = router.uriPatternFor(resourceHandlerClass);
        if (pattern == null) {
            throw new PippoRuntimeException("You must register a route for {}", resourceHandlerClass.getSimpleName());
        }
        patternRef.set(pattern);
    }

    String path = (String) args.get(ClasspathResourceHandler.PATH_PARAMETER);
    Map<String, Object> parameters = new HashMap<>();
    parameters.put(ClasspathResourceHandler.PATH_PARAMETER, path);

    return router.uriFor(patternRef.get(), parameters);
}
 
Example #6
Source File: I18nExtension.java    From pippo with Apache License 2.0 6 votes vote down vote up
@Override
public Object execute(Map<String, Object> args, PebbleTemplate self, EvaluationContext context, int lineNumber) {
    String messageKey = (String) args.get("key");

    Locale locale = context.getLocale();
    String requestLang = locale.toLanguageTag();

    List<Object> messageArgs = new ArrayList<>();
    for (int i = 1; i <= 5; i++) {
        if (args.containsKey("arg" + i)) {
            Object object = args.get("arg" + i);
            messageArgs.add(object);
        }
    }

    String messageValue = messages.get(messageKey, requestLang, messageArgs.toArray());

    return new SafeString(messageValue);
}
 
Example #7
Source File: PebbleTemplateEngineImpl.java    From vertx-web with Apache License 2.0 6 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<PebbleTemplate> template = getTemplate(src);
    if (template == null) {
      // real compile
      synchronized (this) {
        template = new TemplateHolder<>(pebbleEngine.getTemplate(adjustLocation(src)));
      }
      putTemplate(src, template);
    }

    // special key for lang selection
    final String lang = (String) context.get("lang");
    // rendering
    final StringWriter stringWriter = new StringWriter();
    template.template().evaluate(stringWriter, context, lang == null ? Locale.getDefault() : Locale.forLanguageTag(lang));
    handler.handle(Future.succeededFuture(Buffer.buffer(stringWriter.toString())));
  } catch (final Exception ex) {
    handler.handle(Future.failedFuture(ex));
  }
}
 
Example #8
Source File: CMSRenderer.java    From fenixedu-cms with GNU Lesser General Public License v3.0 6 votes vote down vote up
void errorPage(final HttpServletRequest req, HttpServletResponse res, Site site, int errorCode)
        throws ServletException, IOException {
    CMSTheme cmsTheme = site.getTheme();
    if (cmsTheme != null && cmsTheme.definesPath(errorCode + ".html")) {
        try {
            PebbleTemplate compiledTemplate = engine.getTemplate(cmsTheme.getType() + "/" + errorCode + ".html");
            TemplateContext global = new TemplateContext();
            populateSiteInfo(req, null, site, global);
            res.setStatus(errorCode);
            res.setContentType("text/html");
            compiledTemplate.evaluate(res.getWriter(), global, I18N.getLocale());
        } catch (PebbleException e) {
            throw new ServletException("Could not render error page for " + errorCode);
        }
    } else {
        res.sendError(errorCode, req.getRequestURI());
    }
}
 
Example #9
Source File: PebbleTemplateEngine.java    From spark-template-engines with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
@SuppressWarnings("unchecked")
public String render(ModelAndView modelAndView) {
    Object model = modelAndView.getModel();

    if (model == null || model instanceof Map) {
        try {
            StringWriter writer = new StringWriter();

            PebbleTemplate template = engine.getTemplate(modelAndView.getViewName());
            if (model == null) {
                template.evaluate(writer);
            } else {
                template.evaluate(writer, (Map<String, Object>) modelAndView.getModel());
            }

            return writer.toString();
        } catch (PebbleException | IOException e) {
            throw new IllegalArgumentException(e);
        }
    } else {
        throw new IllegalArgumentException("Invalid model, model must be instance of Map.");
    }
}
 
Example #10
Source File: PebbleTemplateService.java    From spring-boot-email-tools with Apache License 2.0 6 votes vote down vote up
@Override
public
@NonNull
String mergeTemplateIntoString(final @NonNull String templateReference,
                               final @NonNull Map<String, Object> model)
        throws IOException, TemplateException {
    final String trimmedTemplateReference = templateReference.trim();
    checkArgument(!isNullOrEmpty(trimmedTemplateReference), "The given templateName is null, empty or blank");
    if (trimmedTemplateReference.contains("."))
        checkArgument(Objects.equals(getFileExtension(trimmedTemplateReference), expectedTemplateExtension()),
                "Expected a Pebble template file with extension '%s', while '%s' was given. To check " +
                        "the default extension look at 'pebble.suffix' in your application.properties file",
                expectedTemplateExtension(), getFileExtension(trimmedTemplateReference));

    try {
        final PebbleTemplate template = pebbleEngine.getTemplate(normalizeTemplateReference(trimmedTemplateReference));
        final Writer writer = new StringWriter();
        template.evaluate(writer, model);
        return writer.toString();
    } catch (Exception e) {
        throw new TemplateException(e);
    }
}
 
Example #11
Source File: NotificationSender.java    From herd-mdl with Apache License 2.0 6 votes vote down vote up
protected String getFormatChangeMsg( FormatChange change, int version, JobDefinition job,
									 HiveTableSchema existing, HiveTableSchema newColumns )
		throws PebbleException, IOException {
	PebbleTemplate template = engine.getTemplate( "templates/formatChangeNotificationTemplate.txt" );

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

	context.put( "changes", change );
	context.put( "nameSpace", job.getObjectDefinition().getNameSpace() );
	context.put( "tableName", job.getTableName() );
	context.put( "version", version );

	context.put( "existing", existing );
	context.put( "new", newColumns );

	StringWriter writer = new StringWriter();
	template.evaluate( writer, context );
	return writer.toString();
}
 
Example #12
Source File: QueryTemplater.java    From feast with Apache License 2.0 6 votes vote down vote up
/**
 * @param featureSetInfos List of FeatureSetInfos containing information about the feature set
 *     necessary for the query templating
 * @param entityTableColumnNames list of column names in entity table
 * @param leftTableName entity dataset name
 * @return query to join temporary feature set tables to the entity table
 */
public static String createJoinQuery(
    List<FeatureSetQueryInfo> featureSetInfos,
    List<String> entityTableColumnNames,
    String leftTableName)
    throws IOException {
  PebbleTemplate template = engine.getTemplate(JOIN_TEMPLATE_NAME);
  Map<String, Object> context = new HashMap<>();
  context.put("entities", entityTableColumnNames);
  context.put("featureSets", featureSetInfos);
  context.put("leftTableName", leftTableName);

  Writer writer = new StringWriter();
  template.evaluate(writer, context);
  return writer.toString();
}
 
Example #13
Source File: PebbleEngineProducerTest.java    From ozark with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotSetCachesWhenCachingIsOff() {
  properties.put(PebbleProperty.CACHE_ACTIVE.key(), "false");
  properties.put(PebbleProperty.TAG_CACHE_MAX.key(), "123");
  properties.put(PebbleProperty.TEMPLATE_CACHE_MAX.key(), "126");

  Cache<BaseTagCacheKey, Object> tagCache = pebbleEngineProducer.pebbleEngine().getTagCache();
  IntStream.range(0, 200).forEach(i -> tagCache.put(new BaseTagCacheKey(String.valueOf(i)) {
  }, i));

  Cache<Object, PebbleTemplate> templateCache = pebbleEngineProducer.pebbleEngine().getTemplateCache();
  IntStream.range(0, 200).forEach(i -> templateCache.put(i, new PebbleTemplateImpl(null, null, String.valueOf(i))));

  assertEquals(0, tagCache.size());
  assertEquals(0, templateCache.size());
}
 
Example #14
Source File: StatsQueryTemplater.java    From feast with Apache License 2.0 5 votes vote down vote up
/**
 * Generate the query for getting histograms for given set of features
 *
 * @param features Information about the features necessary for the query templating
 * @param statsDataset query selecting subset of data to compute statistics over
 * @return point in time correctness join BQ SQL query
 * @throws IOException
 */
public static String createGetFeaturesHistQuery(
    List<FeatureStatisticsQueryInfo> features, StatsDataset statsDataset) throws IOException {

  PebbleTemplate template = engine.getTemplate(HIST_STATS_TEMPLATE_NAME);
  Map<String, Object> context = new HashMap<>();
  context.put("features", features);
  context.put("dataset", generateDataSubsetQuery(statsDataset));

  Writer writer = new StringWriter();
  template.evaluate(writer, context);
  return writer.toString();
}
 
Example #15
Source File: AbstractWebhookPublisher.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
public void publish(final String publisherName, final PebbleTemplate template, final Notification notification, final JsonObject config) {
    final Logger logger = Logger.getLogger(this.getClass());
    logger.debug("Preparing to publish notification");
    if (config == null) {
        logger.warn("No configuration found. Skipping notification.");
        return;
    }
    final String destination = config.getString("destination");
    final String content = prepareTemplate(notification, template);
    if (destination == null || content == null) {
        logger.warn("A destination or template was not found. Skipping notification");
        return;
    }

    final UnirestInstance ui = UnirestFactory.getUnirestInstance();
    final HttpResponse<JsonNode> response = ui.post(destination)
            .header("content-type", "application/json")
            .header("accept", "application/json")
            .body(content)
            .asJson();

    if (response.getStatus() < 200 || response.getStatus() > 299) {
        logger.error("An error was encountered publishing notification to " + publisherName);
        logger.error("HTTP Status : " + response.getStatus() + " " + response.getStatusText());
        logger.error("Destination: " + destination);
        logger.debug(content);
    }
}
 
Example #16
Source File: Badger.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
private String writeSvg(PebbleTemplate template, Map<String, Object> context) {
    try (Writer writer = new StringWriter()) {
        template.evaluate(writer, context);
        return writer.toString();
    } catch (IOException e) {
        Logger.getLogger(this.getClass()).error("An error was encountered evaluating template", e);
        return null;
    }
}
 
Example #17
Source File: PrettyTimeExtension.java    From pippo with Apache License 2.0 5 votes vote down vote up
@Override
public Object apply(Object input, Map<String, Object> args, PebbleTemplate self, EvaluationContext context, int lineNumber) throws PebbleException {
    if (input == null) {
        return null;
    }

    Locale locale = context.getLocale();

    String result = getPrettyTime(locale).format(getFormattableObject(input));

    return new SafeString(result);
}
 
Example #18
Source File: PebbleTemplateEngine.java    From pippo with Apache License 2.0 5 votes vote down vote up
@Override
public void renderResource(String templateName, Map<String, Object> model, Writer writer) {
    String language = (String) model.get(PippoConstants.REQUEST_PARAMETER_LANG);

    if (StringUtils.isNullOrEmpty(language)) {
        language = getLanguageOrDefault(language);
    }

    Locale locale = (Locale) model.get(PippoConstants.REQUEST_PARAMETER_LOCALE);
    if (locale == null) {
        locale = getLocaleOrDefault(language);
    }

    try {
        PebbleTemplate template = null;

        if (locale != null) {
            // try the complete Locale
            template = getTemplate(templateName, locale.toString());
            if (template == null) {
                // try only the language
                template = getTemplate(templateName, locale.getLanguage());
            }
        }

        if (template == null) {
            // fallback to the template without any language or locale
            template = engine.getTemplate(templateName);
        }

        template.evaluate(writer, model, locale);
        writer.flush();
    } catch (Exception e) {
        throw new PippoRuntimeException(e);
    }
}
 
Example #19
Source File: StatsQueryTemplater.java    From feast with Apache License 2.0 5 votes vote down vote up
/**
 * Generate the query for getting basic statistics for a given set of features
 *
 * @param features Information about the features necessary for the query templating
 * @param statsDataset query selecting subset of data to compute statistics over
 * @return point in time correctness join BQ SQL query
 * @throws IOException
 */
public static String createGetFeaturesStatsQuery(
    List<FeatureStatisticsQueryInfo> features, StatsDataset statsDataset) throws IOException {

  PebbleTemplate template = engine.getTemplate(BASIC_STATS_TEMPLATE_NAME);
  Map<String, Object> context = new HashMap<>();
  context.put("features", features);
  context.put("dataset", generateDataSubsetQuery(statsDataset));

  Writer writer = new StringWriter();
  template.evaluate(writer, context);
  return writer.toString();
}
 
Example #20
Source File: RouteExtension.java    From pippo with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Object execute(Map<String, Object> args, PebbleTemplate self, EvaluationContext context, int lineNumber) {
    String nameOrUriPattern = (String) args.get("nameOrUriPattern");
    Map<String, Object> parameters = (Map<String, Object>) args.get("parameters");
    if (parameters == null) {
        parameters = Collections.emptyMap();
    }

    return router.uriFor(nameOrUriPattern, parameters);
}
 
Example #21
Source File: StatsQueryTemplater.java    From feast with Apache License 2.0 5 votes vote down vote up
/**
 * generate the query to subset the data to compute statistics over
 *
 * @param statsDataset {@link StatsDataset} describing the subset of data
 * @return BigQuery query selecting the data
 * @throws IOException
 */
private static String generateDataSubsetQuery(StatsDataset statsDataset) throws IOException {
  PebbleTemplate template = engine.getTemplate(DATA_SUBSET_TEMPLATE_NAME);

  Writer writer = new StringWriter();
  template.evaluate(writer, statsDataset.getMap());
  return writer.toString();
}
 
Example #22
Source File: CMSRenderer.java    From fenixedu-cms with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void renderPage(final HttpServletRequest req, String reqPagePath, HttpServletResponse res, Site site, Page page,
                        String[] requestContext) throws PebbleException, IOException {

    TemplateContext global = new TemplateContext();
    global.setRequestContext(requestContext);
    for (String key : req.getParameterMap().keySet()) {
        global.put(key, req.getParameter(key));
    }

    global.put("page", makePageWrapper(page));
    populateSiteInfo(req, page, site, global);

    List<TemplateContext> components = new ArrayList<TemplateContext>();

    for (Component component : page.getComponentsSet()) {
        TemplateContext local = new TemplateContext();
        component.handle(page, local, global);
        components.add(local);
    }

    global.put("components", components);

    for (RenderingPageHandler handler : HANDLERS){
        handler.accept(page,global);
    }

    CMSTheme theme = site.getTheme();

    PebbleTemplate compiledTemplate = engine.getTemplate(theme.getType() + "/" + page.getTemplate().getFilePath());

    res.setStatus(200);
    res.setContentType("text/html");
    compiledTemplate.evaluate(res.getWriter(), global, I18N.getLocale());
}
 
Example #23
Source File: PebbleEngineProducerTest.java    From ozark with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCorrectlySetTemplateCache() {
  properties.put(PebbleProperty.TEMPLATE_CACHE_MAX.key(), "126");
  Cache<Object, PebbleTemplate> templateCache = pebbleEngineProducer.pebbleEngine().getTemplateCache();

  IntStream.range(0, 200).forEach(i -> templateCache.put(i, new PebbleTemplateImpl(null, null, String.valueOf(i))));

  assertEquals(126, templateCache.size());
}
 
Example #24
Source File: AngularJSExtension.java    From pippo with Apache License 2.0 4 votes vote down vote up
@Override
public Object execute(Map<String, Object> args, PebbleTemplate self, EvaluationContext context, int lineNumber) {
    String content = (String) args.get("content");
    return "{{ " + content + " }}";
}
 
Example #25
Source File: TestExtension.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
@Override
public Object execute(Map<String, Object> map, PebbleTemplate pebbleTemplate, EvaluationContext evaluationContext, int i) {
  return "TEST";
}
 
Example #26
Source File: PebbleViewEngine.java    From krazo with Apache License 2.0 4 votes vote down vote up
@Override
public void processView(ViewEngineContext context) throws ViewEngineException {

    Charset charset = resolveCharsetAndSetContentType(context);

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

        PebbleTemplate template = pebbleEngine.getTemplate(resolveView(context));

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

        template.evaluate(writer, model);

    } catch (PebbleException | IOException ex) {
        throw new ViewEngineException(String.format("Could not process view %s.", context.getView()), ex);
    }
}
 
Example #27
Source File: PebbleViewEngine.java    From ozark with Apache License 2.0 4 votes vote down vote up
@Override
public void processView(ViewEngineContext context) throws ViewEngineException {

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

    PebbleTemplate template = pebbleEngine.getTemplate(resolveView(context));
    
    Map<String, Object> model = new HashMap<>(context.getModels().asMap());
    model.put("request", context.getRequest(HttpServletRequest.class));
    
    template.evaluate(writer, model);
    
  } catch (PebbleException | IOException ex) {
    throw new ViewEngineException(String.format("Could not process view %s.", context.getView()), ex);
  }
}