use of org.apache.sling.scripting.thymeleaf.DefaultSlingContext 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);
}
Aggregations