use of org.thymeleaf.context.IContext in project sling by apache.
the class ThymeleafScriptEngine method eval.
@Override
public Object eval(final Reader reader, final ScriptContext scriptContext) throws ScriptException {
final Bindings bindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE);
final SlingScriptHelper helper = (SlingScriptHelper) bindings.get(SlingBindings.SLING);
if (helper == null) {
throw new ScriptException("SlingScriptHelper missing from bindings");
}
final SlingHttpServletRequest request = helper.getRequest();
final SlingHttpServletResponse response = helper.getResponse();
// only used by Thymeleaf's ServletContextResourceResolver (TODO check if still true for 3.0)
final ServletContext servletContext = null;
final Locale locale = helper.getResponse().getLocale();
final String scriptName = helper.getScript().getScriptResource().getPath();
final Writer writer = scriptContext.getWriter();
try {
final ResourceResolver resourceResolver = thymeleafScriptEngineFactory.getRequestScopedResourceResolver();
final IContext context = new SlingWebContext(request, response, servletContext, resourceResolver, locale, bindings);
thymeleafScriptEngineFactory.getTemplateEngine().process(scriptName, context, writer);
} catch (Exception e) {
logger.error("Failure rendering Thymeleaf template '{}': {}", scriptName, e.getMessage());
throw new ScriptException(e);
}
return null;
}
use of org.thymeleaf.context.IContext in project sling by apache.
the class FormServlet method doPost.
@Override
protected void doPost(@Nonnull SlingHttpServletRequest request, @Nonnull SlingHttpServletResponse response) throws ServletException, IOException {
final Map<String, Object> base = new LinkedHashMap<>();
final ValueMapDecorator parameters = new ValueMapDecorator(base);
final Enumeration<String> names = request.getParameterNames();
while (names.hasMoreElements()) {
final String name = names.nextElement();
parameters.put(name, request.getRequestParameter(name));
}
logger.debug("parameters: {}", parameters);
final String formType = request.getParameter("formType");
logger.debug("form type is '{}'", formType);
final Form form = FormFactory.build(formType, parameters);
if (form == null) {
fail(null, 400, request, response);
return;
}
final String resourcePath = request.getRequestPathInfo().getResourcePath();
final ValidationModel validationModel = validationService.getValidationModel(form.getResourceType(), resourcePath, false);
if (validationModel == null) {
logger.error("no validation model found");
fail(form, 500, request, response);
return;
}
final ValidationResult validationResult = validationService.validate(parameters, validationModel);
form.setValidationResult(validationResult);
if (!validationResult.isValid()) {
logger.debug("validation result not valid");
fail(form, 400, request, response);
return;
}
// render form with message template
// TODO
final String template = "/apps/fling/messaging/form/comment.txt";
final Map<String, Object> variables = Collections.singletonMap("form", form);
final String message;
try (final ResourceResolver resourceResolver = resourceResolverFactory.getServiceResourceResolver(null)) {
final IContext context = new DefaultSlingContext(resourceResolver, Locale.ENGLISH, variables);
logger.debug("rendering message template '{}' with variables: {}", template, variables);
message = templateEngine.process(template, context);
} catch (Exception e) {
// TODO
// TODO
logger.error("sending message failed: {}", e.getMessage(), e);
fail(form, 500, request, response);
return;
}
logger.debug("message: '{}'", message);
try {
final CompletableFuture<Result> future = messageService.send(message, recipient);
future.get(1, TimeUnit.SECONDS);
logger.debug("comment [{}] form sent to {}", message, recipient);
} catch (Exception e) {
logger.error("sending message failed: {}", e.getMessage(), e);
fail(form, 500, request, response);
return;
}
succeed(form, request, response);
}
use of org.thymeleaf.context.IContext in project contribution by checkstyle.
the class TemplateProcessor method generateWithThymeleaf.
/**
* Generates output file with release notes using Thymeleaf.
* @param variables the map which represents template variables.
* @param outputFile output file.
* @param templateFilename template name.
* @throws IOException if I/O error occurs.
*/
public static void generateWithThymeleaf(Map<String, Object> variables, String outputFile, String templateFilename) throws IOException {
final TemplateEngine engine = new TemplateEngine();
final AbstractConfigurableTemplateResolver resolver = new ClassLoaderTemplateResolver();
resolver.setPrefix(TEMPLATE_FOLDER_PATH);
engine.setTemplateResolver(resolver);
final IContext ctx = new Context(Locale.US, variables);
try (Writer fileWriter = new OutputStreamWriter(new FileOutputStream(outputFile), StandardCharsets.UTF_8)) {
engine.process(templateFilename, ctx, fileWriter);
}
}
use of org.thymeleaf.context.IContext in project thymeleaf by thymeleaf.
the class OGNLContextPropertyAccessor method getProperty.
public Object getProperty(final Map ognlContext, final Object target, final Object name) throws OgnlException {
if (!(target instanceof IContext)) {
throw new IllegalStateException("Wrong target type. This property accessor is only usable for " + IContext.class.getName() + " implementations, and " + "in this case the target object is " + (target == null ? "null" : ("of class " + target.getClass().getName())));
}
if (REQUEST_PARAMETERS_RESTRICTED_VARIABLE_NAME.equals(name) && ognlContext != null && ognlContext.containsKey(RESTRICT_REQUEST_PARAMETERS)) {
throw new OgnlException("Access to variable \"" + name + "\" is forbidden in this context. Note some restrictions apply to " + "variable access. For example, direct access to request parameters is forbidden in preprocessing and " + "unescaped expressions, in TEXT template mode, in fragment insertion specifications and " + "in some specific attribute processors.");
}
final String propertyName = (name == null ? null : name.toString());
// 'execInfo' translation from context variable to expression object - deprecated and to be removed in 3.1
final Object execInfoResult = checkExecInfo(propertyName, ognlContext);
if (execInfoResult != null) {
return execInfoResult;
}
/*
* NOTE we do not check here whether we are being asked for the 'locale', 'request', 'response', etc.
* because there already are specific expression objects for the most important of them, which should
* be used instead: #locale, #httpServletRequest, #httpSession, etc.
* The variables maps should just be used as a map, without exposure of its more-internal methods...
*/
final IContext context = (IContext) target;
return context.getVariable(propertyName);
}
use of org.thymeleaf.context.IContext in project stdlib by petergeneric.
the class ThymeleafTemplater method template.
public ThymeleafCall template(final String name) {
final IContext ctx = makeContext();
// Expose the service configuration
ctx.getVariables().put("config", configuration);
ctx.getVariables().putAll(data);
return new ThymeleafCall(engine, ctx, name, calls, failures);
}
Aggregations