Search in sources :

Example 11 with ValidationResult

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")));
}
Also used : ResourceProperty(org.apache.sling.validation.model.ResourceProperty) ValidationModel(org.apache.sling.validation.model.ValidationModel) NonExistingResource(org.apache.sling.api.resource.NonExistingResource) 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)

Example 12 with ValidationResult

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());
}
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) DefaultValidationResult(org.apache.sling.validation.spi.support.DefaultValidationResult) ValidationResult(org.apache.sling.validation.ValidationResult) Test(org.junit.Test)

Example 13 with ValidationResult

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);
            }
        }
    }
}
Also used : JSONWriter(org.apache.felix.utils.json.JSONWriter) ValidationModel(org.apache.sling.validation.model.ValidationModel) RequestDispatcherOptions(org.apache.sling.api.request.RequestDispatcherOptions) ValueMap(org.apache.sling.api.resource.ValueMap) ValidationResult(org.apache.sling.validation.ValidationResult) ValidationFailure(org.apache.sling.validation.ValidationFailure)

Example 14 with ValidationResult

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.*")));
}
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 15 with ValidationResult

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);
}
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)

Aggregations

ValidationResult (org.apache.sling.validation.ValidationResult)25 ValidationModel (org.apache.sling.validation.model.ValidationModel)22 Test (org.junit.Test)19 DefaultValidationResult (org.apache.sling.validation.spi.support.DefaultValidationResult)18 Resource (org.apache.sling.api.resource.Resource)14 ResourceResolver (org.apache.sling.api.resource.ResourceResolver)13 NonExistingResource (org.apache.sling.api.resource.NonExistingResource)12 SyntheticResource (org.apache.sling.api.resource.SyntheticResource)12 ChildResource (org.apache.sling.validation.model.ChildResource)12 HashMap (java.util.HashMap)11 DefaultValidationFailure (org.apache.sling.validation.spi.support.DefaultValidationFailure)11 ValueMapDecorator (org.apache.sling.api.wrappers.ValueMapDecorator)8 ChildResourceImpl (org.apache.sling.validation.impl.model.ChildResourceImpl)6 ResourceProperty (org.apache.sling.validation.model.ResourceProperty)6 ModifiableValueMap (org.apache.sling.api.resource.ModifiableValueMap)5 Nonnull (javax.annotation.Nonnull)3 ValueMap (org.apache.sling.api.resource.ValueMap)3 Validator (org.apache.sling.validation.spi.Validator)3 ValidatorContext (org.apache.sling.validation.spi.ValidatorContext)3 LinkedHashMap (java.util.LinkedHashMap)2