Search in sources :

Example 31 with ValidationModel

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);
}
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 32 with ValidationModel

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")));
}
Also used : ValidationModel(org.apache.sling.validation.model.ValidationModel) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) NonExistingResource(org.apache.sling.api.resource.NonExistingResource) Resource(org.apache.sling.api.resource.Resource) ChildResource(org.apache.sling.validation.model.ChildResource) SyntheticResource(org.apache.sling.api.resource.SyntheticResource) DefaultValidationFailure(org.apache.sling.validation.spi.support.DefaultValidationFailure) DefaultValidationResult(org.apache.sling.validation.spi.support.DefaultValidationResult) ValidationResult(org.apache.sling.validation.ValidationResult) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) Test(org.junit.Test)

Example 33 with ValidationModel

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);
}
Also used : ValidationModel(org.apache.sling.validation.model.ValidationModel) ValidationModelRetriever(org.apache.sling.validation.model.spi.ValidationModelRetriever) CheckForNull(javax.annotation.CheckForNull) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) NonExistingResource(org.apache.sling.api.resource.NonExistingResource) Resource(org.apache.sling.api.resource.Resource) ChildResource(org.apache.sling.validation.model.ChildResource) SyntheticResource(org.apache.sling.api.resource.SyntheticResource) Test(org.junit.Test)

Example 34 with ValidationModel

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)));
}
Also used : ValidationModel(org.apache.sling.validation.model.ValidationModel) HashMap(java.util.HashMap) ValueMapDecorator(org.apache.sling.api.wrappers.ValueMapDecorator) DefaultValidationFailure(org.apache.sling.validation.spi.support.DefaultValidationFailure) DefaultValidationResult(org.apache.sling.validation.spi.support.DefaultValidationResult) ValidationResult(org.apache.sling.validation.ValidationResult) Test(org.junit.Test)

Example 35 with ValidationModel

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.*")));
}
Also used : ResourceProperty(org.apache.sling.validation.model.ResourceProperty) ValidationModel(org.apache.sling.validation.model.ValidationModel) HashMap(java.util.HashMap) ChildResourceImpl(org.apache.sling.validation.impl.model.ChildResourceImpl) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) NonExistingResource(org.apache.sling.api.resource.NonExistingResource) Resource(org.apache.sling.api.resource.Resource) ChildResource(org.apache.sling.validation.model.ChildResource) SyntheticResource(org.apache.sling.api.resource.SyntheticResource) ChildResource(org.apache.sling.validation.model.ChildResource) DefaultValidationFailure(org.apache.sling.validation.spi.support.DefaultValidationFailure) DefaultValidationResult(org.apache.sling.validation.spi.support.DefaultValidationResult) ValidationResult(org.apache.sling.validation.ValidationResult) Test(org.junit.Test)

Aggregations

ValidationModel (org.apache.sling.validation.model.ValidationModel)53 Test (org.junit.Test)43 ValidationResult (org.apache.sling.validation.ValidationResult)22 Resource (org.apache.sling.api.resource.Resource)20 ChildResource (org.apache.sling.validation.model.ChildResource)20 DefaultValidationResult (org.apache.sling.validation.spi.support.DefaultValidationResult)17 ResourceResolver (org.apache.sling.api.resource.ResourceResolver)15 HashMap (java.util.HashMap)13 NonExistingResource (org.apache.sling.api.resource.NonExistingResource)12 SyntheticResource (org.apache.sling.api.resource.SyntheticResource)12 DefaultValidationFailure (org.apache.sling.validation.spi.support.DefaultValidationFailure)11 ModifiableValueMap (org.apache.sling.api.resource.ModifiableValueMap)9 ValueMapDecorator (org.apache.sling.api.wrappers.ValueMapDecorator)9 ResourcePropertyBuilder (org.apache.sling.validation.impl.model.ResourcePropertyBuilder)8 ChildResourceImpl (org.apache.sling.validation.impl.model.ChildResourceImpl)7 ResourceProperty (org.apache.sling.validation.model.ResourceProperty)7 ValidationModelBuilder (org.apache.sling.validation.impl.model.ValidationModelBuilder)6 CheckForNull (javax.annotation.CheckForNull)5 Nonnull (javax.annotation.Nonnull)5 ValueMap (org.apache.sling.api.resource.ValueMap)4