use of org.apache.sling.validation.model.ValidationModel 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.apache.sling.validation.model.ValidationModel in project sling by apache.
the class ValidationServiceImplTest method testResourceWithMultivalueProperties.
@Test
public void testResourceWithMultivalueProperties() throws Exception {
// accept any digits
propertyBuilder.validator(REGEX_VALIDATOR_ID, 0, RegexValidator.REGEX_PARAM, "\\d");
propertyBuilder.multiple();
modelBuilder.resourceProperty(propertyBuilder.build("field"));
ValidationModel vm = modelBuilder.build("type", "some source");
ResourceResolver rr = context.resourceResolver();
Resource testResource = ResourceUtil.getOrCreateResource(rr, "/content/validation/1/resource", JcrConstants.NT_UNSTRUCTURED, JcrConstants.NT_UNSTRUCTURED, true);
ModifiableValueMap mvm = testResource.adaptTo(ModifiableValueMap.class);
mvm.put("field", new String[] { "1", "abc", "2" });
ValidationResult vr = validationService.validate(testResource, vm);
Assert.assertFalse("resource should have been considered invalid", vr.isValid());
Assert.assertThat(vr.getFailures(), Matchers.<ValidationFailure>contains(new DefaultValidationFailure("field[1]", 0, defaultResourceBundle, RegexValidator.I18N_KEY_PATTERN_DOES_NOT_MATCH, "\\d")));
}
use of org.apache.sling.validation.model.ValidationModel in project sling by apache.
the class ValidationServiceImplTest method testValidateResourceRecursivelyWithMissingValidationModel.
@Test(expected = IllegalArgumentException.class)
public void testValidateResourceRecursivelyWithMissingValidationModel() throws Exception {
// set model retriever which never retrieves anything
validationService.modelRetriever = new ValidationModelRetriever() {
@Override
@CheckForNull
public ValidationModel getValidationModel(@Nonnull String resourceType, String resourcePath, boolean considerResourceSuperTypeModels) {
return null;
}
};
ResourceResolver rr = context.resourceResolver();
// resource is having no connected validation model
Resource testResource = ResourceUtil.getOrCreateResource(rr, "/content/validation/1/resource", "resourcetype1", JcrConstants.NT_UNSTRUCTURED, true);
validationService.validateResourceRecursively(testResource, true, null, false);
}
use of org.apache.sling.validation.model.ValidationModel in project sling by apache.
the class ValidationServiceImplTest method testValueMapWithWrongDataType.
@Test()
public void testValueMapWithWrongDataType() throws Exception {
propertyBuilder.validator(DATE_VALIDATOR_ID, 10);
modelBuilder.resourceProperty(propertyBuilder.build("field1"));
ValidationModel vm = modelBuilder.build("sling/validation/test", "some source");
HashMap<String, Object> hashMap = new HashMap<String, Object>();
hashMap.put("field1", "1");
ValidationResult vr = validationService.validate(new ValueMapDecorator(hashMap), vm);
Assert.assertThat(vr.getFailures(), Matchers.<ValidationFailure>contains(new DefaultValidationFailure("field1", 10, defaultResourceBundle, ValidationServiceImpl.I18N_KEY_WRONG_PROPERTY_TYPE, Date.class)));
}
use of org.apache.sling.validation.model.ValidationModel in project sling by apache.
the class ValidationServiceImplTest method testResourceWithNestedChildrenAndPatternMatching.
@Test
public void testResourceWithNestedChildrenAndPatternMatching() throws Exception {
// accept any digits
propertyBuilder.validator(REGEX_VALIDATOR_ID, 0, RegexValidator.REGEX_PARAM, "\\d");
ResourceProperty property = propertyBuilder.build("field1");
ChildResource modelGrandChild = new ChildResourceImpl("grandchild", "grandchild.*", true, Collections.singletonList(property), Collections.<ChildResource>emptyList());
ChildResource modelChild = new ChildResourceImpl("child", "child.*", true, Collections.singletonList(property), Collections.singletonList(modelGrandChild));
ChildResource siblingChild = new ChildResourceImpl("siblingchild", "siblingchild.*", true, Collections.singletonList(property), Collections.singletonList(modelGrandChild));
modelBuilder.childResource(modelChild);
modelBuilder.childResource(siblingChild);
ValidationModel vm = modelBuilder.build("sometype", "some source");
ResourceResolver rr = context.resourceResolver();
Resource testResource = ResourceUtil.getOrCreateResource(rr, "/apps/validation/1/resource", JcrConstants.NT_UNSTRUCTURED, JcrConstants.NT_UNSTRUCTURED, true);
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("field1", "1");
Resource resourceChild = rr.create(testResource, "child1", properties);
rr.create(resourceChild, "grandchild1", properties);
// child2 is lacking its mandatory sub resource
rr.create(testResource, "child2", properties);
rr.create(testResource, "child3", null);
// sibling child is not there at all (although mandatory)
ValidationResult vr = validationService.validate(testResource, vm);
Assert.assertFalse("resource should have been considered invalid", vr.isValid());
Assert.assertThat(vr.getFailures(), Matchers.<ValidationFailure>containsInAnyOrder(new DefaultValidationFailure("child2", 20, defaultResourceBundle, ValidationServiceImpl.I18N_KEY_MISSING_REQUIRED_CHILD_RESOURCE_MATCHING_PATTERN, "grandchild.*"), new DefaultValidationFailure("child3", 20, defaultResourceBundle, ValidationServiceImpl.I18N_KEY_MISSING_REQUIRED_CHILD_RESOURCE_MATCHING_PATTERN, "grandchild.*"), new DefaultValidationFailure("child3", 20, defaultResourceBundle, ValidationServiceImpl.I18N_KEY_MISSING_REQUIRED_PROPERTY_WITH_NAME, "field1"), new DefaultValidationFailure("", 20, defaultResourceBundle, ValidationServiceImpl.I18N_KEY_MISSING_REQUIRED_CHILD_RESOURCE_MATCHING_PATTERN, "siblingchild.*")));
}
Aggregations