use of org.apache.sling.validation.ValidationResult in project sling by apache.
the class ValidationServiceImplTest method testNonExistingResource.
// see https://issues.apache.org/jira/browse/SLING-5674
@Test
public void testNonExistingResource() throws Exception {
// accept any digits
propertyBuilder.validator(REGEX_VALIDATOR_ID, 0, RegexValidator.REGEX_PARAM, "\\d");
ResourceProperty property = propertyBuilder.build("field1");
modelBuilder.resourceProperty(property);
ChildResource modelChild = new ChildResourceImpl("child", null, true, Collections.singletonList(property), Collections.emptyList());
modelBuilder.childResource(modelChild);
modelChild = new ChildResourceImpl("optionalChild", null, false, Collections.singletonList(property), Collections.emptyList());
modelBuilder.childResource(modelChild);
ValidationModel vm = modelBuilder.build("sometype", "some source");
ResourceResolver rr = context.resourceResolver();
Resource nonExistingResource = new NonExistingResource(rr, "non-existing-resource");
ValidationResult vr = validationService.validate(nonExistingResource, vm);
Assert.assertFalse("resource should have been considered invalid", vr.isValid());
Assert.assertThat(vr.getFailures(), Matchers.<ValidationFailure>containsInAnyOrder(new DefaultValidationFailure("", 20, defaultResourceBundle, ValidationServiceImpl.I18N_KEY_MISSING_REQUIRED_PROPERTY_WITH_NAME, "field1"), new DefaultValidationFailure("", 20, defaultResourceBundle, ValidationServiceImpl.I18N_KEY_MISSING_REQUIRED_CHILD_RESOURCE_WITH_NAME, "child")));
}
use of org.apache.sling.validation.ValidationResult in project sling by apache.
the class ValidationServiceImplTest method testResourceWithNestedChildren.
@Test
public void testResourceWithNestedChildren() 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", null, true, Collections.singletonList(property), Collections.<ChildResource>emptyList());
ChildResource modelChild = new ChildResourceImpl("child", null, true, Collections.singletonList(property), Collections.singletonList(modelGrandChild));
modelBuilder.childResource(modelChild);
ValidationModel vm = modelBuilder.build("sometype", "some source");
// create a resource
ResourceResolver rr = context.resourceResolver();
Resource testResource = ResourceUtil.getOrCreateResource(rr, "/content/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, "child", properties);
rr.create(resourceChild, "grandchild", properties);
ValidationResult vr = validationService.validate(testResource, vm);
Assert.assertThat(vr.getFailures(), Matchers.hasSize(0));
Assert.assertTrue(vr.isValid());
}
use of org.apache.sling.validation.ValidationResult in project sling by apache.
the class ModifyUserServlet method doPost.
@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
ValueMap requestParameters = request.adaptTo(ValueMap.class);
String[] resourceTypeValues = requestParameters.get("sling:resourceType", String[].class);
String resourceType = null;
if (resourceTypeValues != null && resourceTypeValues.length > 0) {
resourceType = resourceTypeValues[0];
}
if (resourceType != null && !"".equals(resourceType)) {
String resourcePath = request.getRequestPathInfo().getResourcePath();
ValidationModel vm = validationService.getValidationModel(resourceType, resourcePath, false);
if (vm != null) {
ValidationResult vr = validationService.validate(requestParameters, vm);
if (vr.isValid()) {
RequestDispatcherOptions options = new RequestDispatcherOptions();
options.setReplaceSelectors(" ");
request.getRequestDispatcher(request.getResource(), options).forward(request, response);
} else {
response.setContentType("application/json");
JSONWriter writer = new JSONWriter(response.getWriter());
writer.object();
writer.key("success").value(false);
writer.key("failures").array();
for (ValidationFailure failure : vr.getFailures()) {
writer.object();
writer.key("message").value(failure.getMessage(request.getResourceBundle(Locale.US)));
writer.key("location").value(failure.getLocation());
writer.endObject();
}
writer.endArray();
writer.endObject();
response.setStatus(400);
}
}
}
}
use of org.apache.sling.validation.ValidationResult in project sling by apache.
the class ValidationServiceImplTest method testResourceWithPropertyPatternMatching.
@Test
public void testResourceWithPropertyPatternMatching() throws Exception {
// accept any digits
propertyBuilder.validator(REGEX_VALIDATOR_ID, 1, RegexValidator.REGEX_PARAM, "\\d");
propertyBuilder.nameRegex("field.*");
modelBuilder.resourceProperty(propertyBuilder.build("field"));
propertyBuilder.nameRegex("otherfield.*");
modelBuilder.resourceProperty(propertyBuilder.build("otherfield"));
propertyBuilder.nameRegex("optionalfield.*").optional();
modelBuilder.resourceProperty(propertyBuilder.build("optionalfield"));
ValidationModel vm = modelBuilder.build("type", "some source");
// create a resource
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("field1", "1");
mvm.put("field2", "1");
// does not validate
mvm.put("field3", "abc");
// otherfield.* property is missing
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("field3", 1, defaultResourceBundle, RegexValidator.I18N_KEY_PATTERN_DOES_NOT_MATCH, "\\d"), new DefaultValidationFailure("", 20, defaultResourceBundle, ValidationServiceImpl.I18N_KEY_MISSING_REQUIRED_PROPERTY_MATCHING_PATTERN, "otherfield.*")));
}
use of org.apache.sling.validation.ValidationResult 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