Search in sources :

Example 1 with IContext

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;
}
Also used : SlingHttpServletResponse(org.apache.sling.api.SlingHttpServletResponse) Locale(java.util.Locale) IContext(org.thymeleaf.context.IContext) SlingScriptHelper(org.apache.sling.api.scripting.SlingScriptHelper) Bindings(javax.script.Bindings) SlingBindings(org.apache.sling.api.scripting.SlingBindings) SlingHttpServletRequest(org.apache.sling.api.SlingHttpServletRequest) ScriptException(javax.script.ScriptException) ScriptException(javax.script.ScriptException) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) ServletContext(javax.servlet.ServletContext) Writer(java.io.Writer)

Example 2 with IContext

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);
}
Also used : IContext(org.thymeleaf.context.IContext) Form(org.apache.sling.samples.fling.form.Form) ValueMapDecorator(org.apache.sling.api.wrappers.ValueMapDecorator) ValidationResult(org.apache.sling.validation.ValidationResult) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) LinkedHashMap(java.util.LinkedHashMap) Result(org.apache.sling.commons.messaging.Result) ValidationResult(org.apache.sling.validation.ValidationResult) ValidationModel(org.apache.sling.validation.model.ValidationModel) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) DefaultSlingContext(org.apache.sling.scripting.thymeleaf.DefaultSlingContext)

Example 3 with IContext

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);
    }
}
Also used : IContext(org.thymeleaf.context.IContext) Context(org.thymeleaf.context.Context) TemplateEngine(org.thymeleaf.TemplateEngine) ClassLoaderTemplateResolver(org.thymeleaf.templateresolver.ClassLoaderTemplateResolver) IContext(org.thymeleaf.context.IContext) FileOutputStream(java.io.FileOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) Writer(java.io.Writer) OutputStreamWriter(java.io.OutputStreamWriter) AbstractConfigurableTemplateResolver(org.thymeleaf.templateresolver.AbstractConfigurableTemplateResolver)

Example 4 with IContext

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);
}
Also used : OgnlException(ognl.OgnlException) IContext(org.thymeleaf.context.IContext)

Example 5 with IContext

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);
}
Also used : IContext(org.thymeleaf.context.IContext)

Aggregations

IContext (org.thymeleaf.context.IContext)5 Writer (java.io.Writer)2 ResourceResolver (org.apache.sling.api.resource.ResourceResolver)2 FileOutputStream (java.io.FileOutputStream)1 IOException (java.io.IOException)1 OutputStreamWriter (java.io.OutputStreamWriter)1 LinkedHashMap (java.util.LinkedHashMap)1 Locale (java.util.Locale)1 Bindings (javax.script.Bindings)1 ScriptException (javax.script.ScriptException)1 ServletContext (javax.servlet.ServletContext)1 ServletException (javax.servlet.ServletException)1 OgnlException (ognl.OgnlException)1 SlingHttpServletRequest (org.apache.sling.api.SlingHttpServletRequest)1 SlingHttpServletResponse (org.apache.sling.api.SlingHttpServletResponse)1 SlingBindings (org.apache.sling.api.scripting.SlingBindings)1 SlingScriptHelper (org.apache.sling.api.scripting.SlingScriptHelper)1 ValueMapDecorator (org.apache.sling.api.wrappers.ValueMapDecorator)1 Result (org.apache.sling.commons.messaging.Result)1 Form (org.apache.sling.samples.fling.form.Form)1