Search in sources :

Example 56 with ResourceResolver

use of org.apache.sling.api.resource.ResourceResolver in project sling by apache.

the class ResourceTypePickerTest method testClientModelCreateFromResource.

@Test
public void testClientModelCreateFromResource() throws LoginException {
    ResourceResolver resolver = null;
    try {
        resolver = rrFactory.getAdministrativeResourceResolver(null);
        final Resource baseComponentResource = resolver.getResource(baseComponentPath);
        Assert.assertNotNull(baseComponentResource);
        TestComponent baseModel = baseComponentResource.adaptTo(TestComponent.class);
        Assert.assertNotNull("Model should not be null", baseModel);
        Assert.assertTrue("Model should be a BaseComponent", baseModel instanceof BaseComponent);
        final Resource childComponentResource = resolver.getResource(childComponentPath);
        Assert.assertNotNull(childComponentResource);
        baseModel = childComponentResource.adaptTo(TestComponent.class);
        Assert.assertNotNull("Model should not be null", baseModel);
        Assert.assertTrue("Model should be a SubRTComponent", baseModel instanceof SubRTComponent);
    } finally {
        if (resolver != null && resolver.isLive()) {
            resolver.close();
        }
    }
}
Also used : ResourceResolver(org.apache.sling.api.resource.ResourceResolver) Resource(org.apache.sling.api.resource.Resource) Test(org.junit.Test)

Example 57 with ResourceResolver

use of org.apache.sling.api.resource.ResourceResolver in project sling by apache.

the class ResourceTypeBindingTest method setup.

@Before
public void setup() throws LoginException, PersistenceException {
    ResourceResolver adminResolver = null;
    try {
        adminResolver = rrFactory.getAdministrativeResourceResolver(null);
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put("sampleValue", "baseTESTValue");
        properties.put(SlingConstants.NAMESPACE_PREFIX + ":" + SlingConstants.PROPERTY_RESOURCE_TYPE, "sling/rt/base");
        ResourceUtil.getOrCreateResource(adminResolver, baseComponentPath, properties, null, false);
        properties.clear();
        properties.put("sampleValue", "childTESTValue");
        properties.put(SlingConstants.NAMESPACE_PREFIX + ":" + SlingConstants.PROPERTY_RESOURCE_TYPE, "sling/rt/child");
        properties.put(SlingConstants.NAMESPACE_PREFIX + ":" + SlingConstants.PROPERTY_RESOURCE_SUPER_TYPE, "sling/rt/base");
        ResourceUtil.getOrCreateResource(adminResolver, childComponentPath, properties, null, false);
        properties.clear();
        properties.put("sampleValue", "childTESTValue2");
        properties.put(SlingConstants.NAMESPACE_PREFIX + ":" + SlingConstants.PROPERTY_RESOURCE_TYPE, "sling/rt/child");
        ResourceUtil.getOrCreateResource(adminResolver, child2ComponentPath, properties, null, false);
        properties.clear();
        properties.put(SlingConstants.NAMESPACE_PREFIX + ":" + SlingConstants.PROPERTY_RESOURCE_SUPER_TYPE, "sling/rt/base");
        ResourceUtil.getOrCreateResource(adminResolver, "/apps/sling/rt/child", properties, null, false);
        properties.clear();
        properties.put("sampleValue", "extendedTESTValue");
        properties.put(SlingConstants.NAMESPACE_PREFIX + ":" + SlingConstants.PROPERTY_RESOURCE_TYPE, "sling/rt/extended");
        ResourceUtil.getOrCreateResource(adminResolver, extendedComponentPath, properties, null, false);
        properties.clear();
        properties.put(SlingConstants.NAMESPACE_PREFIX + ":" + SlingConstants.PROPERTY_RESOURCE_TYPE, "sling/rt/fromRequest");
        ResourceUtil.getOrCreateResource(adminResolver, fromRequestComponentPath, properties, null, false);
        adminResolver.commit();
    } finally {
        if (adminResolver != null && adminResolver.isLive()) {
            adminResolver.close();
        }
    }
}
Also used : HashMap(java.util.HashMap) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) Before(org.junit.Before)

Example 58 with ResourceResolver

use of org.apache.sling.api.resource.ResourceResolver in project sling by apache.

the class ResourceValidationModelProviderImplTest method setUp.

@Before
public void setUp() throws LoginException, PersistenceException, RepositoryException {
    primaryTypeUnstructuredMap = new HashMap<String, Object>();
    primaryTypeUnstructuredMap.put(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED);
    modelProvider = new ResourceValidationModelProviderImpl();
    // one default model
    modelBuilder = new ValidationModelBuilder();
    modelBuilder.setApplicablePath("/content/site1");
    ResourcePropertyBuilder propertyBuilder = new ResourcePropertyBuilder();
    propertyBuilder.validator("validatorId", 10, RegexValidator.REGEX_PARAM, "prefix.*");
    ResourceProperty property = propertyBuilder.build("field1");
    modelBuilder.resourceProperty(property);
    prefixBasedResultHandler = new MockQueryResultHandler() {

        @Override
        public MockQueryResult executeQuery(MockQuery query) {
            if (!"xpath".equals(query.getLanguage())) {
                return null;
            }
            String statement = query.getStatement();
            // @validatingResourceType="<some-resource-type>"]
            if (statement.startsWith("/jcr:root/")) {
                statement = statement.substring("/jcr:root/".length() - 1);
            }
            // extract the prefix from the statement
            String prefix = Text.getAbsoluteParent(statement, 0);
            // extract the resource type from the statement
            Matcher matcher = RESOURCE_TYPE_PATTERN.matcher(statement);
            if (!matcher.matches()) {
                throw new IllegalArgumentException("Can only process query statements which contain a validatedResourceType but the statement is: " + statement);
            }
            String resourceType = matcher.group(1);
            PrefixAndResourceType prefixAndResourceType = new PrefixAndResourceType(prefix, resourceType);
            if (validatorModelNodesPerPrefixAndResourceType.keySet().contains(prefixAndResourceType)) {
                return new MockQueryResult(validatorModelNodesPerPrefixAndResourceType.get(prefixAndResourceType));
            }
            return null;
        }
    };
    rr = context.resourceResolver();
    modelProvider.rrf = resourceResolverFactory;
    // create a wrapper resource resolver, which cannot be closed (as the SlingContext will take care of that)
    ResourceResolver nonClosableResourceResolverWrapper = Mockito.spy(rr);
    // intercept all close calls
    Mockito.doNothing().when(nonClosableResourceResolverWrapper).close();
    // always use the context's resource resolver (because we never commit)
    Mockito.when(resourceResolverFactory.getServiceResourceResolver(Mockito.anyObject())).thenReturn(nonClosableResourceResolverWrapper);
    MockJcr.addQueryResultHandler(rr.adaptTo(Session.class), prefixBasedResultHandler);
    validatorModelNodesPerPrefixAndResourceType = new HashMap<PrefixAndResourceType, List<Node>>();
    appsValidatorsRoot = ResourceUtil.getOrCreateResource(rr, APPS + "/" + VALIDATION_MODELS_RELATIVE_PATH, (Map<String, Object>) null, "sling:Folder", true);
    libsValidatorsRoot = ResourceUtil.getOrCreateResource(rr, LIBS + "/" + VALIDATION_MODELS_RELATIVE_PATH, (Map<String, Object>) null, "sling:Folder", true);
}
Also used : Matcher(java.util.regex.Matcher) ResourcePropertyBuilder(org.apache.sling.validation.impl.model.ResourcePropertyBuilder) MockQueryResultHandler(org.apache.sling.testing.mock.jcr.MockQueryResultHandler) ResourceProperty(org.apache.sling.validation.model.ResourceProperty) MockQueryResult(org.apache.sling.testing.mock.jcr.MockQueryResult) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) ArrayList(java.util.ArrayList) List(java.util.List) MockQuery(org.apache.sling.testing.mock.jcr.MockQuery) ValueMap(org.apache.sling.api.resource.ValueMap) HashMap(java.util.HashMap) Map(java.util.Map) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) ValidationModelBuilder(org.apache.sling.validation.impl.model.ValidationModelBuilder) Session(javax.jcr.Session) Before(org.junit.Before)

Example 59 with ResourceResolver

use of org.apache.sling.api.resource.ResourceResolver in project sling by apache.

the class ValidationServiceImplTest method testValidateResourceRecursively.

@Test()
public void testValidateResourceRecursively() throws Exception {
    modelBuilder.resourceProperty(propertyBuilder.build("field1"));
    final ValidationModel vm1 = modelBuilder.build("resourcetype1", "some source");
    modelBuilder = new ValidationModelBuilder();
    modelBuilder.resourceProperty(propertyBuilder.build("field2"));
    final ValidationModel vm2 = modelBuilder.build("resourcetype2", "some source");
    // set model retriever
    validationService.modelRetriever = new ValidationModelRetriever() {

        @Override
        @CheckForNull
        public ValidationModel getValidationModel(@Nonnull String resourceType, String resourcePath, boolean considerResourceSuperTypeModels) {
            if (resourceType.equals("resourcetype1")) {
                return vm1;
            } else if (resourceType.equals("resourcetype2")) {
                return vm2;
            } else {
                return null;
            }
        }
    };
    ResourceResolver rr = context.resourceResolver();
    // resource is lacking the required field (is invalid)
    Resource testResource = ResourceUtil.getOrCreateResource(rr, "/content/validation/1/resource", "resourcetype1", JcrConstants.NT_UNSTRUCTURED, true);
    // child1 is valid
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY, "resourcetype2");
    properties.put("field2", "test");
    rr.create(testResource, "child1", properties);
    // child2 is invalid
    properties.clear();
    properties.put(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY, "resourcetype2");
    rr.create(testResource, "child2", properties);
    // child3 has no model (but its resource type is ignored)
    properties.clear();
    properties.put(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY, "resourcetype3");
    rr.create(testResource, "child3", properties);
    final Predicate<Resource> ignoreResourceType3Filter = new Predicate<Resource>() {

        @Override
        public boolean test(final Resource resource) {
            return !"resourcetype3".equals(resource.getResourceType());
        }
    };
    ValidationResult vr = validationService.validateResourceRecursively(testResource, true, ignoreResourceType3Filter, false);
    Assert.assertFalse("resource should have been considered invalid", vr.isValid());
    Assert.assertThat(vr.getFailures(), Matchers.<ValidationFailure>contains(new DefaultValidationFailure("", 20, defaultResourceBundle, ValidationServiceImpl.I18N_KEY_MISSING_REQUIRED_PROPERTY_WITH_NAME, "field1"), new DefaultValidationFailure("child2", 20, defaultResourceBundle, ValidationServiceImpl.I18N_KEY_MISSING_REQUIRED_PROPERTY_WITH_NAME, "field2")));
}
Also used : HashMap(java.util.HashMap) ValidationModelRetriever(org.apache.sling.validation.model.spi.ValidationModelRetriever) 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) DefaultValidationResult(org.apache.sling.validation.spi.support.DefaultValidationResult) ValidationResult(org.apache.sling.validation.ValidationResult) Predicate(java.util.function.Predicate) ValidationModel(org.apache.sling.validation.model.ValidationModel) CheckForNull(javax.annotation.CheckForNull) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) DefaultValidationFailure(org.apache.sling.validation.spi.support.DefaultValidationFailure) ValidationModelBuilder(org.apache.sling.validation.impl.model.ValidationModelBuilder) Test(org.junit.Test)

Example 60 with ResourceResolver

use of org.apache.sling.api.resource.ResourceResolver in project sling by apache.

the class ValidationServiceImplTest method testSyntheticResource.

// see https://issues.apache.org/jira/browse/SLING-5749
@Test
public void testSyntheticResource() 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 SyntheticResource(rr, "someresource", "resourceType");
    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) 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) 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

ResourceResolver (org.apache.sling.api.resource.ResourceResolver)339 Resource (org.apache.sling.api.resource.Resource)168 Test (org.junit.Test)131 HashMap (java.util.HashMap)65 LoginException (org.apache.sling.api.resource.LoginException)53 PersistenceException (org.apache.sling.api.resource.PersistenceException)52 Session (javax.jcr.Session)31 ModifiableValueMap (org.apache.sling.api.resource.ModifiableValueMap)29 ValueMap (org.apache.sling.api.resource.ValueMap)27 SyntheticResource (org.apache.sling.api.resource.SyntheticResource)26 ArrayList (java.util.ArrayList)23 DistributionRequest (org.apache.sling.distribution.DistributionRequest)23 DistributionPackage (org.apache.sling.distribution.packaging.DistributionPackage)21 Map (java.util.Map)19 Before (org.junit.Before)19 IOException (java.io.IOException)17 NonExistingResource (org.apache.sling.api.resource.NonExistingResource)17 ChildResource (org.apache.sling.validation.model.ChildResource)17 HashSet (java.util.HashSet)16 ResourceResolverFactory (org.apache.sling.api.resource.ResourceResolverFactory)15