org.apache.sling.api.resource.Resource

Here are the examples of the java api class org.apache.sling.api.resource.Resource taken from open source projects.

1. ResourceModelClassesTest#testChildResource()

Project: sling
File: ResourceModelClassesTest.java
@Test
public void testChildResource() {
    Resource child = mock(Resource.class);
    Resource secondChild = mock(Resource.class);
    Resource emptyChild = mock(Resource.class);
    Resource firstGrandChild = mock(Resource.class);
    Resource secondGrandChild = mock(Resource.class);
    when(secondChild.listChildren()).thenReturn(Arrays.asList(firstGrandChild, secondGrandChild).iterator());
    when(emptyChild.listChildren()).thenReturn(Collections.<Resource>emptySet().iterator());
    Resource res = mock(Resource.class);
    when(res.getChild("firstChild")).thenReturn(child);
    when(res.getChild("secondChild")).thenReturn(secondChild);
    when(res.getChild("emptyChild")).thenReturn(emptyChild);
    ChildResourceModel model = factory.getAdapter(res, ChildResourceModel.class);
    assertNotNull(model);
    assertEquals(child, model.getFirstChild());
    assertEquals(2, model.getGrandChildren().size());
    assertEquals(firstGrandChild, model.getGrandChildren().get(0));
    assertEquals(secondGrandChild, model.getGrandChildren().get(1));
    assertEquals(0, model.getEmptyGrandChildren().size());
}

2. JsonPipeTest#testPipedArray()

Project: sling
File: JsonPipeTest.java
@Test
public void testPipedArray() throws Exception {
    Resource resource = context.resourceResolver().getResource(ARRAY);
    ContainerPipe pipe = (ContainerPipe) plumber.getPipe(resource);
    Iterator<Resource> outputs = pipe.getOutput();
    Resource first = outputs.next();
    Resource second = outputs.next();
    Resource third = outputs.next();
    assertFalse("there should be only three elements", outputs.hasNext());
    assertEquals("first resource should be one", "/content/json/array/one", first.getPath());
    assertEquals("second resource should be two", "/content/json/array/two", second.getPath());
    assertEquals("third resource should be three", "/content/json/array/three", third.getPath());
}

3. MergedResourceProviderTestForOverridingPicker#testOverriddenIncludesChildFromSuper()

Project: sling
File: MergedResourceProviderTestForOverridingPicker.java
@Test
public void testOverriddenIncludesChildFromSuper() {
    final Resource rsrcA2 = this.provider.getResource(ctx, "/override/apps/a/2", ResourceContext.EMPTY_CONTEXT, null);
    Resource d = getChildResource(rsrcA2, "d");
    assertNotNull(d);
    Resource d1 = getChildResource(d, "1");
    assertNotNull(d1);
    Resource d1a = getChildResource(d1, "a");
    assertNotNull(d1a);
}

4. ResourceResolverControlTest#getParent_differentProviders()

Project: sling
File: ResourceResolverControlTest.java
/**
     * Test parent from a different provider
     */
@Test
public void getParent_differentProviders() {
    final Resource childResource = mock(Resource.class);
    when(childResource.getPath()).thenReturn("/some/path");
    when(subProvider.getResource((ResolveContext<Object>) Mockito.anyObject(), Mockito.eq("/some/path"), (ResourceContext) Mockito.anyObject(), (Resource) Mockito.eq(null))).thenReturn(childResource);
    final Resource parentResource = mock(Resource.class);
    when(parentResource.getPath()).thenReturn("/some");
    when(rootProvider.getResource((ResolveContext<Object>) Mockito.anyObject(), Mockito.eq("/some"), (ResourceContext) Mockito.anyObject(), (Resource) Mockito.eq(null))).thenReturn(parentResource);
    Resource child = crp.getResource(context, "/some/path", null, null, false);
    assertNotNull(child);
    assertTrue(childResource == child);
    Resource parent = crp.getParent(context, ResourceUtil.getParent(child.getPath()), child);
    assertNotNull(parent);
    assertTrue(parentResource == parent);
}

5. KryoContentSerializer#persistResource()

Project: sling
File: KryoContentSerializer.java
private void persistResource(@Nonnull ResourceResolver resourceResolver, Resource resource) throws PersistenceException {
    String path = resource.getPath().trim();
    String name = path.substring(path.lastIndexOf('/') + 1);
    String substring = path.substring(0, path.lastIndexOf('/'));
    String parentPath = substring.length() == 0 ? "/" : substring;
    Resource existingResource = resourceResolver.getResource(path);
    if (existingResource != null) {
        resourceResolver.delete(existingResource);
    }
    Resource parent = resourceResolver.getResource(parentPath);
    if (parent == null) {
        parent = createParent(resourceResolver, parentPath);
    }
    Resource createdResource = resourceResolver.create(parent, name, resource.getValueMap());
    log.info("created resource {}", createdResource);
}

6. ResourceConfigurationManager#getConfigs()

Project: sling
File: ResourceConfigurationManager.java
@Override
public List<DistributionConfiguration> getConfigs(ResourceResolver resolver, DistributionComponentKind kind) {
    List<DistributionConfiguration> configurations = new ArrayList<DistributionConfiguration>();
    Resource configRoot = resolver.getResource(configRootPath);
    if (configRoot == null) {
        return new ArrayList<DistributionConfiguration>();
    }
    for (Resource configResource : configRoot.getChildren()) {
        Map<String, Object> configMap = getFilteredMap(configResource);
        configurations.add(new DistributionConfiguration(kind, configResource.getName(), configMap));
    }
    return configurations;
}

7. BundleContentLoaderTest#dumpRepo0()

Project: sling
File: BundleContentLoaderTest.java
private void dumpRepo0(String startPath, int maxDepth, int currentDepth) {
    Resource resource = context.resourceResolver().getResource(startPath);
    StringBuilder format = new StringBuilder();
    for (int i = 0; i < currentDepth; i++) {
        format.append("  ");
    }
    format.append("%s [%s]%n");
    String name = resource.getName().length() == 0 ? "/" : resource.getName();
    System.out.format(format.toString(), name, resource.getResourceType());
    currentDepth++;
    if (currentDepth > maxDepth) {
        return;
    }
    for (Resource child : resource.getChildren()) {
        dumpRepo0(child.getPath(), maxDepth, currentDepth);
    }
}

8. WritePipeTest#testVariablePiped()

Project: sling
File: WritePipeTest.java
@Test
public void testVariablePiped() throws Exception {
    String pipePath = PATH_PIPE + "/" + NN_VARIABLE_PIPED;
    Resource confResource = context.resourceResolver().getResource(pipePath);
    Pipe pipe = plumber.getPipe(confResource);
    assertNotNull("pipe should be found", pipe);
    Iterator<Resource> it = pipe.getOutput();
    Resource resource = it.next();
    assertEquals("path should be the one configured in first pipe", pipePath + "/conf/fruit/conf/apple", resource.getPath());
    context.resourceResolver().commit();
    ValueMap properties = resource.adaptTo(ValueMap.class);
    assertEquals("Configured value should be written", "apple is a fruit and its color is green", properties.get("jcr:description", ""));
    assertEquals("Worm has been removed", "", properties.get("worm", ""));
    Resource archive = resource.getChild("archive/wasthereworm");
    assertNotNull("there is an archive of the worm value", archive);
    assertEquals("Worm value has been written at the same time", "true", archive.adaptTo(String.class));
}

9. ContainerPipeTest#testOtherTree()

Project: sling
File: ContainerPipeTest.java
@Test
public void testOtherTree() throws Exception {
    Resource resource = context.resourceResolver().getResource(PATH_PIPE + "/" + NN_OTHERTREE);
    ContainerPipe pipe = (ContainerPipe) plumber.getPipe(resource);
    Iterator<Resource> resourceIterator = pipe.getOutput();
    assertTrue("There should be some results", resourceIterator.hasNext());
    Resource firstResource = resourceIterator.next();
    assertNotNull("First resource should not be null", firstResource);
    assertEquals("First resource should be instantiated path with apple & pea", PATH_FRUITS + "/apple/isnota/pea/buttheyhavesamecolor", firstResource.getPath());
    assertTrue("There should still be another item", resourceIterator.hasNext());
    Resource secondResource = resourceIterator.next();
    assertNotNull("Second resource should not be null", secondResource);
    assertEquals("Second resource should be instantiated path with banana & pea", PATH_FRUITS + "/banana/isnota/pea/andtheircolorisdifferent", secondResource.getPath());
    assertFalse("There should be no more items", resourceIterator.hasNext());
}

10. ResourceResolverControlTest#move_differentProvider()

Project: sling
File: ResourceResolverControlTest.java
/**
     * Verifies moving resources between different ResourceProviders
     *
     * @throws PersistenceException persistence exception
     */
@Test
public void move_differentProvider() throws PersistenceException {
    Resource newRes = newMockResource("/object");
    when(rootProvider.create(mockContext(), Mockito.eq("/object"), Mockito.anyMap())).thenReturn(newRes);
    Resource resource = crp.move(context, "/some/path/object", "/");
    assertThat(resource, not(nullValue()));
    verify(subProvider).delete(mockContext(), Mockito.eq(subProviderResource));
}

11. ResourceResolverImpl#getAbsoluteResourceInternal()

Project: sling
File: ResourceResolverImpl.java
/**
     * Creates a resource with the given path if existing
     */
private Resource getAbsoluteResourceInternal(@CheckForNull final Resource parent, @CheckForNull final String path, final Map<String, String> parameters, final boolean isResolve) {
    if (path == null || path.length() == 0 || path.charAt(0) != '/') {
        logger.debug("getResourceInternal: Path must be absolute {}", path);
        // path must be absolute
        return null;
    }
    final Resource parentToUse;
    if (parent != null && path.startsWith(parent.getPath())) {
        parentToUse = parent;
    } else {
        parentToUse = null;
    }
    final Resource resource = this.control.getResource(this.context, path, parentToUse, parameters, isResolve);
    if (resource != null) {
        resource.getResourceMetadata().setResolutionPath(path);
        resource.getResourceMetadata().setParameterMap(parameters);
        return resource;
    }
    logger.debug("getResourceInternal: Cannot resolve path '{}' to a resource", path);
    return null;
}

12. ResourceAccessSecurityImplTests#testCannotUpdateAccidentallyUsingReadableResourceIfCannotUpdate()

Project: sling
File: ResourceAccessSecurityImplTests.java
@Test
public void testCannotUpdateAccidentallyUsingReadableResourceIfCannotUpdate() {
    initMocks("/content", new String[] { "read", "update" });
    Resource resource = mock(Resource.class);
    when(resource.getPath()).thenReturn("/content");
    ModifiableValueMap valueMap = mock(ModifiableValueMap.class);
    when(resource.adaptTo(ModifiableValueMap.class)).thenReturn(valueMap);
    when(resourceAccessGate.canRead(resource)).thenReturn(ResourceAccessGate.GateResult.GRANTED);
    when(resourceAccessGate.canUpdate(resource)).thenReturn(ResourceAccessGate.GateResult.DENIED);
    Resource readableResource = resourceAccessSecurity.getReadableResource(resource);
    ValueMap resultValueMap = readableResource.adaptTo(ValueMap.class);
    resultValueMap.put("modified", "value");
    verify(valueMap, times(0)).put("modified", "value");
}

13. ResourceAccessSecurityImplTests#testCannotUpdateUsingReadableResourceIfCannotUpdate()

Project: sling
File: ResourceAccessSecurityImplTests.java
@Test
public void testCannotUpdateUsingReadableResourceIfCannotUpdate() {
    initMocks("/content", new String[] { "read", "update" });
    Resource resource = mock(Resource.class);
    when(resource.getPath()).thenReturn("/content");
    ModifiableValueMap valueMap = mock(ModifiableValueMap.class);
    when(resource.adaptTo(ModifiableValueMap.class)).thenReturn(valueMap);
    when(resourceAccessGate.canRead(resource)).thenReturn(ResourceAccessGate.GateResult.GRANTED);
    when(resourceAccessGate.canUpdate(resource)).thenReturn(ResourceAccessGate.GateResult.DENIED);
    Resource readableResource = resourceAccessSecurity.getReadableResource(resource);
    ModifiableValueMap resultValueMap = readableResource.adaptTo(ModifiableValueMap.class);
    assertNull(resultValueMap);
}

14. ResourceAccessSecurityImplTests#testCannotUpdateUsingReadableResourceIfCannotRead()

Project: sling
File: ResourceAccessSecurityImplTests.java
@Test
public void testCannotUpdateUsingReadableResourceIfCannotRead() {
    initMocks("/content", new String[] { "read", "update" });
    Resource resource = mock(Resource.class);
    when(resource.getPath()).thenReturn("/content");
    ModifiableValueMap valueMap = mock(ModifiableValueMap.class);
    when(resource.adaptTo(ModifiableValueMap.class)).thenReturn(valueMap);
    when(resourceAccessGate.canRead(resource)).thenReturn(ResourceAccessGate.GateResult.DENIED);
    when(resourceAccessGate.canUpdate(resource)).thenReturn(ResourceAccessGate.GateResult.GRANTED);
    Resource readableResource = resourceAccessSecurity.getReadableResource(resource);
    assertNull(readableResource);
}

15. ResourceAccessSecurityImplTests#testCanUpdateUsingReadableResource()

Project: sling
File: ResourceAccessSecurityImplTests.java
@Test
public void testCanUpdateUsingReadableResource() {
    // one needs to have also read rights to obtain the resource
    initMocks("/content", new String[] { "read", "update" });
    Resource resource = mock(Resource.class);
    when(resource.getPath()).thenReturn("/content");
    ModifiableValueMap valueMap = mock(ModifiableValueMap.class);
    when(resource.adaptTo(ModifiableValueMap.class)).thenReturn(valueMap);
    when(resourceAccessGate.canRead(resource)).thenReturn(ResourceAccessGate.GateResult.GRANTED);
    when(resourceAccessGate.canUpdate(resource)).thenReturn(ResourceAccessGate.GateResult.GRANTED);
    Resource readableResource = resourceAccessSecurity.getReadableResource(resource);
    ModifiableValueMap resultValueMap = readableResource.adaptTo(ModifiableValueMap.class);
    resultValueMap.put("modified", "value");
    verify(valueMap, times(1)).put("modified", "value");
}

16. BundleContentLoaderTest#loadXmlAsIs()

Project: sling
File: BundleContentLoaderTest.java
@Test
@Ignore("TODO - unregister or somehow ignore the XmlReader component for this test")
public void loadXmlAsIs() throws Exception {
    dumpRepo("/", 2);
    Bundle mockBundle = newBundleWithInitialContent("SLING-INF/libs/app;path:=/libs/app;ignoreImportProviders:=xml");
    contentLoader.registerBundle(context.resourceResolver().adaptTo(Session.class), mockBundle, false);
    Resource imported = context.resourceResolver().getResource("/libs/app");
    assertThat("Resource was not imported", imported, notNullValue());
    assertThat("sling:resourceType was not properly set", imported.getResourceType(), equalTo("sling:Folder"));
    Resource xmlFile = context.resourceResolver().getResource("/libs/app.xml");
    dumpRepo("/", 2);
    assertThat("XML file was was not imported", xmlFile, notNullValue());
}

17. ValidationServiceImplTest#testResourceWithNestedChildren()

Project: sling
File: ValidationServiceImplTest.java
@Test
public void testResourceWithNestedChildren() throws Exception {
    // accept any digits
    propertyBuilder.validator(new RegexValidator(), 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");
    // 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());
}

18. ResourceValidationModelProviderImplTest#createValidationModelChildResource()

Project: sling
File: ResourceValidationModelProviderImplTest.java
private Resource createValidationModelChildResource(Resource parentResource, ChildResource child) throws PersistenceException {
    ResourceResolver rr = parentResource.getResourceResolver();
    Resource modelChildren = rr.create(parentResource, ResourceValidationModelProviderImpl.CHILDREN, primaryTypeUnstructuredMap);
    Resource modelResource = rr.create(modelChildren, child.getName(), primaryTypeUnstructuredMap);
    ModifiableValueMap mvm = modelResource.adaptTo(ModifiableValueMap.class);
    if (child.getNamePattern() != null) {
        mvm.put(ResourceValidationModelProviderImpl.NAME_REGEX, child.getNamePattern());
    }
    mvm.put(ResourceValidationModelProviderImpl.OPTIONAL, !child.isRequired());
    createValidationModelProperties(modelResource, child.getProperties());
    // recursion for all childs
    for (ChildResource grandChild : child.getChildren()) {
        createValidationModelChildResource(modelResource, grandChild);
    }
    return modelResource;
}

19. ResourceBuilderImpl#ensureResourceExists()

Project: sling
File: ResourceBuilderImpl.java
/** Create a Resource at the specified path if none exists yet,
     *  using the current intermediate primary type. "Stolen" from
     *  the sling-mock module's ContentBuilder class.
     *  @param path Resource path
     *  @return Resource at path (existing or newly created)
     */
protected final Resource ensureResourceExists(String path) {
    if (path == null || path.length() == 0 || path.equals("/")) {
        return resourceResolver.getResource("/");
    }
    Resource resource = resourceResolver.getResource(path);
    if (resource != null) {
        return resource;
    }
    String parentPath = ResourceUtil.getParent(path);
    String name = ResourceUtil.getName(path);
    Resource parentResource = ensureResourceExists(parentPath);
    try {
        resource = resourceResolver.create(parentResource, name, MapArgsConverter.toMap(JCR_PRIMARYTYPE, intermediatePrimaryType));
        return resource;
    } catch (PersistenceException ex) {
        throw new RuntimeException("Unable to create intermediate resource at " + path, ex);
    }
}

20. ResourceModelInterfacesTest#testChildValueMap()

Project: sling
File: ResourceModelInterfacesTest.java
@Test
public void testChildValueMap() {
    ValueMap map = ValueMapDecorator.EMPTY;
    Resource child = mock(Resource.class);
    when(child.adaptTo(ValueMap.class)).thenReturn(map);
    Resource res = mock(Resource.class);
    when(res.getChild("firstChild")).thenReturn(child);
    ChildValueMapModel model = factory.getAdapter(res, ChildValueMapModel.class);
    assertNotNull(model);
    assertEquals(map, model.getFirstChild());
}

21. ResourceModelClassesTest#testChildValueMap()

Project: sling
File: ResourceModelClassesTest.java
@Test
public void testChildValueMap() {
    ValueMap map = ValueMapDecorator.EMPTY;
    Resource child = mock(Resource.class);
    when(child.adaptTo(ValueMap.class)).thenReturn(map);
    Resource res = mock(Resource.class);
    when(res.getChild("firstChild")).thenReturn(child);
    ChildValueMapModel model = factory.getAdapter(res, ChildValueMapModel.class);
    assertNotNull(model);
    assertEquals(map, model.getFirstChild());
}

22. InjectorSpecificAnnotationTest#testChildResourceConstructor()

Project: sling
File: InjectorSpecificAnnotationTest.java
@Test
public void testChildResourceConstructor() {
    Resource res = mock(Resource.class);
    Resource child = mock(Resource.class);
    when(res.getChild("child1")).thenReturn(child);
    when(request.getResource()).thenReturn(res);
    org.apache.sling.models.testmodels.classes.constructorinjection.InjectorSpecificAnnotationModel model = factory.getAdapter(request, org.apache.sling.models.testmodels.classes.constructorinjection.InjectorSpecificAnnotationModel.class);
    assertNotNull("Could not instanciate model", model);
    assertEquals(child, model.getChildResource());
}

23. ProcessorConfigurationImplTest#testMatchAtLeastOneResourceTypeWithResourceWrapper_UnwrapEnabled()

Project: sling
File: ProcessorConfigurationImplTest.java
@Test
public void testMatchAtLeastOneResourceTypeWithResourceWrapper_UnwrapEnabled() {
    Resource resource = context.create().resource("/content/test", ImmutableMap.<String, Object>of("sling:resourceType", "type/1"));
    // overwrite resource type via ResourceWrapper
    Resource resourceWrapper = new ResourceWrapper(resource) {

        @Override
        public String getResourceType() {
            return "/type/override/1";
        }
    };
    context.currentResource(resourceWrapper);
    assertMatch(ImmutableMap.<String, Object>of(PROPERTY_RESOURCE_TYPES, new String[] { "type/1", "type/2" }, PROPERTY_UNWRAP_RESOURCES, true));
}

24. ProcessorConfigurationImplTest#testMatchAtLeastOneResourceTypeWithResourceWrapper_UnwrapDisabled()

Project: sling
File: ProcessorConfigurationImplTest.java
@Test
public void testMatchAtLeastOneResourceTypeWithResourceWrapper_UnwrapDisabled() {
    Resource resource = context.create().resource("/content/test", ImmutableMap.<String, Object>of("sling:resourceType", "type/1"));
    // overwrite resource type via ResourceWrapper
    Resource resourceWrapper = new ResourceWrapper(resource) {

        @Override
        public String getResourceType() {
            return "/type/override/1";
        }
    };
    context.currentResource(resourceWrapper);
    assertNoMatch(ImmutableMap.<String, Object>of(PROPERTY_RESOURCE_TYPES, new String[] { "type/1", "type/2" }));
}

25. ResourceConfigurationManager#deleteConfig()

Project: sling
File: ResourceConfigurationManager.java
@Override
public void deleteConfig(ResourceResolver resolver, DistributionComponentKind kind, String name) {
    Resource configRoot = resolver.getResource(configRootPath);
    Resource configResource = configRoot.getChild(name);
    if (configResource == null) {
        return;
    }
    try {
        resolver.delete(configResource);
        resolver.commit();
    } catch (PersistenceException e) {
        log.error("cannot delete config {}", name, e);
    }
}

26. ResourceConfigurationManager#getConfig()

Project: sling
File: ResourceConfigurationManager.java
@Override
public DistributionConfiguration getConfig(ResourceResolver resolver, DistributionComponentKind kind, String name) {
    Resource configRoot = resolver.getResource(configRootPath);
    if (configRoot == null) {
        return null;
    }
    Resource configResource = configRoot.getChild(name);
    if (configResource == null) {
        return null;
    }
    Map<String, Object> configMap = getFilteredMap(configResource);
    return new DistributionConfiguration(kind, configResource.getName(), configMap);
}

27. ResourceCollectionImplTest#testAddResourceWithProperties()

Project: sling
File: ResourceCollectionImplTest.java
@Test
public void testAddResourceWithProperties() throws Exception {
    final Map<String, Object> props = new HashMap<String, Object>();
    props.put("creator", "slingdev");
    final ResourceCollection collection = rcm.createCollection(resResolver.getResource("/"), "collection3");
    final Resource resource = resResolver.create(resResolver.getResource("/"), "res1", Collections.singletonMap(ResourceResolver.PROPERTY_RESOURCE_TYPE, (Object) "type"));
    collection.add(resource, props);
    final Resource collectionRes = resResolver.getResource("/collection3");
    Assert.assertNotNull(collectionRes);
    Assert.assertEquals(true, collection.contains(resource));
    ValueMap vm = collection.getProperties(resource);
    if (vm != null) {
        Assert.assertEquals("slingdev", vm.get("creator", ""));
    } else {
        Assert.fail("no resource entry in collection");
    }
}

28. ResourceCollectionImplTest#testCreateCollectionWithProperties()

Project: sling
File: ResourceCollectionImplTest.java
@Test
public void testCreateCollectionWithProperties() throws Exception {
    final Map<String, Object> props = new HashMap<String, Object>();
    props.put(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY, "some/type");
    props.put("creator", "slingdev");
    final ResourceCollection collection = rcm.createCollection(resResolver.getResource("/"), "collection3", props);
    final Resource resource = resResolver.create(resResolver.getResource("/"), "res1", Collections.singletonMap(ResourceResolver.PROPERTY_RESOURCE_TYPE, (Object) "type"));
    collection.add(resource, null);
    final Resource collectionRes = resResolver.getResource("/collection3");
    Assert.assertNotNull(collectionRes);
    Assert.assertEquals(true, collection.contains(resource));
    Assert.assertEquals(ResourceCollection.RESOURCE_TYPE, collectionRes.getResourceSuperType());
    ValueMap vm = collectionRes.adaptTo(ValueMap.class);
    Assert.assertEquals("slingdev", vm.get("creator", ""));
}

29. ResourceCollectionImplTest#testListCollection()

Project: sling
File: ResourceCollectionImplTest.java
@Test
public void testListCollection() throws Exception {
    final ResourceCollection collection = rcm.createCollection(resResolver.getResource("/"), "collection1");
    final Resource res1 = resResolver.create(resResolver.getResource("/"), "res1", Collections.singletonMap(ResourceResolver.PROPERTY_RESOURCE_TYPE, (Object) "type"));
    collection.add(res1, null);
    final Resource resource = resResolver.create(resResolver.getResource("/"), "res2", Collections.singletonMap(ResourceResolver.PROPERTY_RESOURCE_TYPE, (Object) "type"));
    collection.add(resource, null);
    Assert.assertEquals(true, collection.contains(resource));
    final Iterator<Resource> resources = collection.getResources();
    int numOfRes = 0;
    while (resources.hasNext()) {
        resources.next();
        numOfRes++;
    }
    Assert.assertEquals(2, numOfRes);
}

30. ResourceCollectionImplTest#testGetCollection()

Project: sling
File: ResourceCollectionImplTest.java
@Test
public void testGetCollection() throws Exception {
    ResourceCollection collection = rcm.createCollection(resResolver.getResource("/"), "test1");
    final Resource res1 = resResolver.create(resResolver.getResource("/"), "res1", Collections.singletonMap(ResourceResolver.PROPERTY_RESOURCE_TYPE, (Object) "type"));
    collection.add(res1, null);
    final Resource resource = resResolver.create(resResolver.getResource("/"), "res2", Collections.singletonMap(ResourceResolver.PROPERTY_RESOURCE_TYPE, (Object) "type"));
    collection.add(resource, null);
    collection = rcm.getCollection(resResolver.getResource(collection.getPath()));
    Assert.assertEquals(true, collection.contains(resource));
    Assert.assertNotNull(resResolver.getResource("/test1"));
    Assert.assertEquals(ResourceCollection.RESOURCE_TYPE, resResolver.getResource("/test1").getResourceType());
}

31. ResourceCollectionImplTest#testCreateCollection()

Project: sling
File: ResourceCollectionImplTest.java
@Test
public void testCreateCollection() throws Exception {
    final ResourceCollection collection = rcm.createCollection(resResolver.getResource("/"), "test1");
    final Resource res1 = resResolver.create(resResolver.getResource("/"), "res1", Collections.singletonMap(ResourceResolver.PROPERTY_RESOURCE_TYPE, (Object) "type"));
    collection.add(res1, null);
    final Resource resource = resResolver.create(resResolver.getResource("/"), "res2", Collections.singletonMap(ResourceResolver.PROPERTY_RESOURCE_TYPE, (Object) "type"));
    collection.add(resource, null);
    Assert.assertEquals(true, collection.contains(resource));
    Assert.assertNotNull(resResolver.getResource("/test1"));
    Assert.assertEquals(ResourceCollection.RESOURCE_TYPE, resResolver.getResource("/test1").getResourceType());
}

32. ResourceCollectionImplTest#testAddResource()

Project: sling
File: ResourceCollectionImplTest.java
@Test
public void testAddResource() throws Exception {
    final ResourceCollection collection = rcm.createCollection(resResolver.getResource("/"), "test1");
    final Resource res1 = resResolver.create(resResolver.getResource("/"), "res1", Collections.singletonMap(ResourceResolver.PROPERTY_RESOURCE_TYPE, (Object) "type"));
    collection.add(res1);
    final Resource resource = resResolver.create(resResolver.getResource("/"), "res2", Collections.singletonMap(ResourceResolver.PROPERTY_RESOURCE_TYPE, (Object) "type"));
    collection.add(resource);
    Assert.assertEquals(true, collection.contains(resource));
    Assert.assertEquals(true, collection.contains(resource));
    Assert.assertNotNull(resResolver.getResource("/test1"));
    Assert.assertEquals(ResourceCollection.RESOURCE_TYPE, resResolver.getResource("/test1").getResourceType());
}

33. MockedResourceResolverImplTest#testResourceResolverGetChildren()

Project: sling
File: MockedResourceResolverImplTest.java
/**
     * Tests listing children via the resource resolver getChildren call.
     * @throws LoginException
     */
@Test
public void testResourceResolverGetChildren() throws LoginException {
    ResourceResolver resourceResolver = resourceResolverFactory.getResourceResolver(null);
    buildResource("/single/test/withchildren", buildChildResources("/single/test/withchildren"), resourceResolver, resourceProvider);
    Resource resource = resourceResolver.getResource("/single/test/withchildren");
    Assert.assertNotNull(resource);
    // test via the resource list children itself, this really just tests this test case.
    Iterable<Resource> resourceIterator = resourceResolver.getChildren(resource);
    Assert.assertNotNull(resourceResolver);
    int i = 0;
    for (Resource r : resourceIterator) {
        Assert.assertEquals("m" + i, r.getName());
        i++;
    }
    Assert.assertEquals(5, i);
}

34. AbstractSlingCrudResourceResolverTest#testBinaryData()

Project: sling
File: AbstractSlingCrudResourceResolverTest.java
@Test
public void testBinaryData() throws IOException {
    Resource resource1 = context.resourceResolver().getResource(getTestRootResource().getPath() + "/node1");
    Resource binaryPropResource = resource1.getChild("binaryProp");
    InputStream is = binaryPropResource.adaptTo(InputStream.class);
    byte[] dataFromResource = IOUtils.toByteArray(is);
    is.close();
    assertArrayEquals(BINARY_VALUE, dataFromResource);
    // read second time to ensure not the original input stream was returned
    // and this time using another syntax
    InputStream is2 = ResourceUtil.getValueMap(resource1).get("binaryProp", InputStream.class);
    byte[] dataFromResource2 = IOUtils.toByteArray(is2);
    is2.close();
    assertArrayEquals(BINARY_VALUE, dataFromResource2);
}

35. AbstractSlingCrudResourceResolverTest#setUp()

Project: sling
File: AbstractSlingCrudResourceResolverTest.java
@Before
public final void setUp() throws IOException {
    // prepare some test data using Sling CRUD API
    Resource rootNode = getTestRootResource();
    Map<String, Object> props = new HashMap<String, Object>();
    props.put(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED);
    props.put("stringProp", STRING_VALUE);
    props.put("stringArrayProp", STRING_ARRAY_VALUE);
    props.put("integerProp", INTEGER_VALUE);
    props.put("doubleProp", DOUBLE_VALUE);
    props.put("booleanProp", BOOLEAN_VALUE);
    props.put("dateProp", DATE_VALUE);
    props.put("calendarProp", CALENDAR_VALUE);
    props.put("binaryProp", new ByteArrayInputStream(BINARY_VALUE));
    Resource node1 = context.resourceResolver().create(rootNode, "node1", props);
    context.resourceResolver().create(node1, "node11", ImmutableMap.<String, Object>builder().put("stringProp11", STRING_VALUE).build());
    context.resourceResolver().create(node1, "node12", ValueMap.EMPTY);
    context.resourceResolver().commit();
}

36. AbstractMultipleResourceResolverTest#testMultipleResourceResolver()

Project: sling
File: AbstractMultipleResourceResolverTest.java
@Test
public void testMultipleResourceResolver() throws Exception {
    ResourceResolverFactory factory = newResourceResolerFactory();
    ResourceResolver resolver1 = factory.getAdministrativeResourceResolver(null);
    ResourceResolver resolver2 = factory.getAdministrativeResourceResolver(null);
    // add a resource in resolver 1
    Resource root = resolver1.getResource("/");
    resolver1.create(root, "test", ImmutableMap.<String, Object>of());
    resolver1.commit();
    // try to get resource in resolver 2
    Resource testResource2 = resolver2.getResource("/test");
    assertNotNull(testResource2);
    // delete resource and make sure it is removed in resolver 1 as well
    resolver2.delete(testResource2);
    resolver2.commit();
    assertNull(resolver1.getResource("/test"));
}

37. AbstractContentLoaderJsonDamTest#testDamAssetMetadata()

Project: sling
File: AbstractContentLoaderJsonDamTest.java
@Test
public void testDamAssetMetadata() throws IOException {
    Resource assetMetadata = context.resourceResolver().getResource(path + "/sample/portraits/scott_reynolds.jpg/jcr:content/metadata");
    ValueMap props = ResourceUtil.getValueMap(assetMetadata);
    assertEquals("Canon", props.get("tiff:Make", String.class));
    assertEquals((Long) 807L, props.get("tiff:ImageWidth", Long.class));
    assertEquals((Integer) 595, props.get("tiff:ImageLength", Integer.class));
    assertEquals(4.64385986328125d, props.get("dam:ApertureValue", Double.class), 0.00000000001d);
    assertArrayEquals(new String[] { "stockphotography:business/business_people", "properties:style/color", "properties:orientation/landscape" }, props.get("app:tags", String[].class));
    // validate that a binary data node is present, but empty
    Resource binaryMetadata = context.resourceResolver().getResource(path + "/sample/portraits/scott_reynolds.jpg/jcr:content/renditions/original/jcr:content");
    ValueMap binaryProps = ResourceUtil.getValueMap(binaryMetadata);
    InputStream is = binaryProps.get(JcrConstants.JCR_DATA, InputStream.class);
    assertNotNull(is);
    byte[] binaryData = IOUtils.toByteArray(is);
    assertEquals(0, binaryData.length);
}

38. ContentBuilder#ensureResourceExists()

Project: sling
File: ContentBuilder.java
/**
     * Ensure that a resource exists at the given path. If not, it is created
     * using <code>nt:unstructured</code> node type.
     * @param path Resource path
     * @return Resource at path (existing or newly created)
     */
protected final Resource ensureResourceExists(String path) {
    if (StringUtils.isEmpty(path) || StringUtils.equals(path, "/")) {
        return resourceResolver.getResource("/");
    }
    Resource resource = resourceResolver.getResource(path);
    if (resource != null) {
        return resource;
    }
    String parentPath = ResourceUtil.getParent(path);
    String name = ResourceUtil.getName(path);
    Resource parentResource = ensureResourceExists(parentPath);
    try {
        resource = resourceResolver.create(parentResource, name, ImmutableMap.<String, Object>builder().put(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED).build());
        resourceResolver.commit();
        return resource;
    } catch (PersistenceException ex) {
        throw new RuntimeException("Unable to create resource at " + path, ex);
    }
}

39. SlingCrudResourceResolverTest#testBinaryData()

Project: sling
File: SlingCrudResourceResolverTest.java
@Test
public void testBinaryData() throws IOException {
    Resource resource1 = resourceResolver.getResource(testRoot.getPath() + "/node1");
    Resource binaryPropResource = resource1.getChild("binaryProp");
    InputStream is = binaryPropResource.adaptTo(InputStream.class);
    byte[] dataFromResource = IOUtils.toByteArray(is);
    is.close();
    assertArrayEquals(BINARY_VALUE, dataFromResource);
    // read second time to ensure not the original input stream was returned
    // and this time using another syntax
    InputStream is2 = ResourceUtil.getValueMap(resource1).get("binaryProp", InputStream.class);
    byte[] dataFromResource2 = IOUtils.toByteArray(is2);
    is2.close();
    assertArrayEquals(BINARY_VALUE, dataFromResource2);
}

40. NtFileResourceTest#testNtFile()

Project: sling
File: NtFileResourceTest.java
@Test
public void testNtFile() throws IOException {
    Resource file = resourceResolver.create(testRoot, "ntFile", ImmutableMap.<String, Object>builder().put(JCR_PRIMARYTYPE, NT_FILE).build());
    resourceResolver.create(file, JCR_CONTENT, ImmutableMap.<String, Object>builder().put(JCR_PRIMARYTYPE, NT_RESOURCE).put(JCR_DATA, new ByteArrayInputStream(BINARY_VALUE)).build());
    String path = testRoot.getPath() + "/ntFile";
    Resource resource = resourceResolver.getResource(path);
    InputStream is = resource.adaptTo(InputStream.class);
    assertNotNull(is);
    assertArrayEquals(BINARY_VALUE, IOUtils.toByteArray(is));
    is.close();
}

41. UrlFilter#findUrlFilterDefinitionResource()

Project: sling
File: UrlFilter.java
Resource findUrlFilterDefinitionResource(Resource resource, ResourceResolver resolver) {
    if (resource == null) {
        return null;
    }
    Resource contentResource = resource.getChild("jcr:content");
    if (contentResource != null) {
        resource = contentResource;
    }
    String resourceType = resource.getResourceType();
    Resource definitionResource = findUrlFilterDefinitionResource(resourceType, resolver);
    if (definitionResource == null) {
        return findUrlFilterDefinitionResource(resource.getResourceSuperType(), resolver);
    } else {
        return definitionResource;
    }
}

42. RatingsServiceImpl#setRating()

Project: sling
File: RatingsServiceImpl.java
/**
     * @see org.apache.sling.sample.slingshot.ratings.RatingsService#setRating(org.apache.sling.api.resource.Resource, java.lang.String, int)
     */
@Override
public void setRating(final Resource resource, final String userId, final int rating) throws PersistenceException {
    final String ratingsPath = getRatingsResourcePath(resource);
    final Map<String, Object> props = new HashMap<String, Object>();
    props.put(ResourceResolver.PROPERTY_RESOURCE_TYPE, RESOURCETYPE_RATINGS);
    final Resource ratingsResource = ResourceUtil.getOrCreateResource(resource.getResourceResolver(), ratingsPath, props, null, true);
    final Resource ratingRsrc = resource.getResourceResolver().getResource(ratingsResource, userId);
    if (ratingRsrc == null) {
        props.clear();
        props.put(ResourceResolver.PROPERTY_RESOURCE_TYPE, RatingsUtil.RESOURCETYPE_RATING);
        props.put(RatingsUtil.PROPERTY_RATING, rating);
        resource.getResourceResolver().create(ratingsResource, userId, props);
    } else {
        final ModifiableValueMap mvm = ratingRsrc.adaptTo(ModifiableValueMap.class);
        mvm.put(RatingsUtil.PROPERTY_RATING, rating);
    }
    resource.getResourceResolver().commit();
}

43. SimpleNoSqlResourceProviderQueryTest#setUp()

Project: sling
File: SimpleNoSqlResourceProviderQueryTest.java
@Before
public void setUp() throws Exception {
    context.registerInjectActivateService(new SimpleNoSqlResourceProviderFactory(), ImmutableMap.<String, Object>builder().put(ResourceProvider.ROOTS, "/nosql-simple").build());
    // prepare some test data using Sling CRUD API
    Map<String, Object> props = new HashMap<String, Object>();
    props.put(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED);
    final Resource root = context.resourceResolver().getResource("/");
    Resource noSqlRoot = context.resourceResolver().create(root, "nosql-simple", props);
    this.testRoot = context.resourceResolver().create(noSqlRoot, "test", props);
    context.resourceResolver().create(testRoot, "node1", ImmutableMap.<String, Object>of("prop1", "value1"));
    context.resourceResolver().create(testRoot, "node2", ImmutableMap.<String, Object>of("prop1", "value2"));
    context.resourceResolver().commit();
}

44. AbstractNoSqlResourceProviderTransactionalTest#testRecursiveDeleteWithoutCommit()

Project: sling
File: AbstractNoSqlResourceProviderTransactionalTest.java
@Test
public void testRecursiveDeleteWithoutCommit() throws PersistenceException {
    Resource node1 = context.resourceResolver().create(testRoot(), "node1", ImmutableMap.<String, Object>of());
    Resource node11 = context.resourceResolver().create(node1, "node11", ImmutableMap.<String, Object>of());
    context.resourceResolver().create(node11, "node111", ImmutableMap.<String, Object>of());
    assertNotNull(testRoot().getChild("node1"));
    assertNotNull(testRoot().getChild("node1/node11"));
    assertNotNull(testRoot().getChild("node1/node11/node111"));
    context.resourceResolver().delete(node1);
    assertNull(testRoot().getChild("node1"));
    assertNull(testRoot().getChild("node1/node11"));
    assertNull(testRoot().getChild("node1/node11/node111"));
}

45. AbstractNoSqlResourceProviderRootTest#testListChildren_RootNode()

Project: sling
File: AbstractNoSqlResourceProviderRootTest.java
@Test
public void testListChildren_RootNode() throws IOException {
    Resource testResource = ResourceUtil.getOrCreateResource(context.resourceResolver(), "/test", ImmutableMap.<String, Object>of(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED), JcrConstants.NT_UNSTRUCTURED, true);
    Resource root = context.resourceResolver().getResource("/");
    List<Resource> children = Lists.newArrayList(root.listChildren());
    assertFalse(children.isEmpty());
    assertTrue(containsResource(children, testResource));
    children = Lists.newArrayList(root.getChildren());
    assertFalse(children.isEmpty());
    assertTrue(containsResource(children, testResource));
    context.resourceResolver().delete(testResource);
}

46. AbstractNoSqlResourceProviderRootTest#testCreatePath()

Project: sling
File: AbstractNoSqlResourceProviderRootTest.java
@Test
public void testCreatePath() throws PersistenceException {
    ResourceUtil.getOrCreateResource(context.resourceResolver(), "/test/test1", ImmutableMap.<String, Object>of(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED), JcrConstants.NT_UNSTRUCTURED, true);
    Resource test = context.resourceResolver().getResource("/test");
    assertNotNull(test);
    Resource test1 = context.resourceResolver().getResource("/test/test1");
    assertNotNull(test1);
    context.resourceResolver().delete(test);
}

47. WritePipeTest#testSimpleTree()

Project: sling
File: WritePipeTest.java
@Test
public void testSimpleTree() throws Exception {
    Resource confResource = context.resourceResolver().getResource(PATH_PIPE + "/" + NN_SIMPLETREE);
    Pipe pipe = plumber.getPipe(confResource);
    assertNotNull("pipe should be found", pipe);
    assertTrue("this pipe should be marked as content modifier", pipe.modifiesContent());
    pipe.getOutput();
    context.resourceResolver().commit();
    Resource appleResource = context.resourceResolver().getResource("/content/fruits/apple");
    ValueMap properties = appleResource.adaptTo(ValueMap.class);
    assertTrue("There should be hasSeed set to true", properties.get("hasSeed", false));
    assertArrayEquals("Colors should be correctly set", new String[] { "green", "red" }, properties.get("colors", String[].class));
    Node appleNode = appleResource.adaptTo(Node.class);
    NodeIterator children = appleNode.getNodes();
    assertTrue("Apple node should have children", children.hasNext());
}

48. WritePipeTest#testPiped()

Project: sling
File: WritePipeTest.java
@Test
public void testPiped() throws Exception {
    Resource confResource = context.resourceResolver().getResource(PATH_PIPE + "/" + NN_PIPED);
    Pipe pipe = plumber.getPipe(confResource);
    assertNotNull("pipe should be found", pipe);
    assertTrue("this pipe should be marked as content modifier", pipe.modifiesContent());
    Iterator<Resource> it = pipe.getOutput();
    assertTrue("There should be one result", it.hasNext());
    Resource resource = it.next();
    assertNotNull("The result should not be null", resource);
    assertEquals("The result should be the configured one in the piped write pipe", "/content/fruits", resource.getPath());
    context.resourceResolver().commit();
    ValueMap properties = resource.adaptTo(ValueMap.class);
    assertArrayEquals("First fruit should have been correctly instantiated & patched from nothing", new String[] { "apple" }, properties.get("fruits", String[].class));
    assertTrue("There should be a second result awaiting", it.hasNext());
    resource = it.next();
    assertNotNull("The second result should not be null", resource);
    assertEquals("The second result should be the configured one in the piped write pipe", "/content/fruits", resource.getPath());
    context.resourceResolver().commit();
    assertPiped(resource);
}

49. RemovePipeTest#testComplexRemove()

Project: sling
File: RemovePipeTest.java
@Test
public void testComplexRemove() throws Exception {
    ResourceResolver resolver = context.resourceResolver();
    Resource resource = resolver.getResource(PATH_PIPE + "/" + NN_COMPLEX);
    Pipe pipe = plumber.getPipe(resource);
    assertTrue("resource should be solved", pipe.getOutput().hasNext());
    pipe.getOutput().next();
    resolver.commit();
    assertNull("isnota carrot should be removed", resolver.getResource(PATH_APPLE + "/isnota/carrot"));
    Resource isNotAPea = resolver.getResource(PATH_APPLE + "/isnota/pea");
    assertNotNull("isnota pea should not be removed", isNotAPea);
    assertFalse("isnota pea color property should not be here", isNotAPea.adaptTo(ValueMap.class).containsKey("color"));
}

50. MultiPropertyPipeTest#testMV()

Project: sling
File: MultiPropertyPipeTest.java
@Test
public void testMV() throws Exception {
    Resource conf = context.resourceResolver().getResource(PATH_PIPE + "/working");
    Pipe pipe = plumber.getPipe(conf);
    Iterator<Resource> outputs = pipe.getOutput();
    Resource resource = outputs.next();
    assertNotNull(resource);
    assertEquals("Resource path should be the input", PATH_FRUITS + PN_INDEX, resource.getPath());
    String fruit = (String) pipe.getOutputBinding();
    assertEquals("First resource binding should be apple", "apple", fruit);
    resource = outputs.next();
    assertNotNull(resource);
    assertEquals("Resource path should be the input", PATH_FRUITS + PN_INDEX, resource.getPath());
    fruit = (String) pipe.getOutputBinding();
    assertEquals("Second resource binding should be banana", "banana", fruit);
}

51. JsonPipeTest#testPipedJson()

Project: sling
File: JsonPipeTest.java
@Test
public void testPipedJson() throws Exception {
    Resource resource = context.resourceResolver().getResource(CONF);
    Pipe pipe = plumber.getPipe(resource);
    Iterator<Resource> outputs = pipe.getOutput();
    outputs.next();
    Resource result = outputs.next();
    context.resourceResolver().commit();
    ValueMap properties = result.adaptTo(ValueMap.class);
    assertTrue("There should be a Paris property", properties.containsKey("Paris"));
    assertTrue("There should be a Bucharest property", properties.containsKey("Bucharest"));
}

52. VotingView#getVote()

Project: sling
File: VotingView.java
/**
     * Get the vote of the instance with the given slingId
     * @param slingId
     * @return null if that instance did not vote yet (or the structure
     * is faulty), true if the instance voted yes, false if it voted no
     */
public Boolean getVote(String slingId) {
    Resource members = getResource().getChild("members");
    if (members == null) {
        return null;
    }
    final Resource memberResource = members.getChild(slingId);
    if (memberResource == null) {
        return null;
    }
    final ValueMap properties = memberResource.adaptTo(ValueMap.class);
    if (properties == null) {
        return null;
    }
    final Boolean vote = properties.get("vote", Boolean.class);
    return vote;
}

53. WorkflowInstanceFolderComparatorTest#testCompare_Simple()

Project: acs-aem-commons
File: WorkflowInstanceFolderComparatorTest.java
@Test
public void testCompare_Simple() throws Exception {
    Resource one = mock(Resource.class);
    Resource two = mock(Resource.class);
    when(one.getName()).thenReturn("1980-09-16");
    when(two.getName()).thenReturn("1980-09-16_1");
    List<Resource> actual = new ArrayList<Resource>();
    actual.add(two);
    actual.add(one);
    Collections.sort(actual, new WorkflowInstanceFolderComparator());
    assertEquals(actual.get(0).getName(), one.getName());
    assertEquals(actual.get(1).getName(), two.getName());
}

54. EnsureOakIndexJobHandlerTest#testUpdateWithRecreate()

Project: acs-aem-commons
File: EnsureOakIndexJobHandlerTest.java
@Test
public void testUpdateWithRecreate() throws RepositoryException, IOException {
    Map<String, Object> props = new HashMap<String, Object>();
    props.put(EnsureOakIndexJobHandler.PN_RECREATE_ON_UPDATE, true);
    Resource def = getEnsureOakDefinition(props);
    Resource index = mock(Resource.class);
    Assert.assertFalse(handler.handleLightWeightIndexOperations(def, index));
    handler.handleHeavyWeightIndexOperations(oakIndexResource, def, index);
    verify(handler, never()).disableIndex(any(Resource.class));
    verify(handler, times(1)).delete(any(Resource.class));
    verify(handler, times(1)).create(any(Resource.class), any(Resource.class));
    verify(handler, never()).update(eq(def), eq(oakIndexResource), eq(false));
    verify(handler, never()).forceRefresh(any(Resource.class));
}

55. EnsureOakIndexJobHandlerTest#testUpdate()

Project: acs-aem-commons
File: EnsureOakIndexJobHandlerTest.java
@Test
public void testUpdate() throws RepositoryException, IOException {
    Map<String, Object> props = new HashMap<String, Object>();
    props.put(EnsureOakIndexJobHandler.PN_FORCE_REINDEX, "true");
    Resource def = getEnsureOakDefinition(props);
    Resource index = mock(Resource.class);
    Assert.assertFalse(handler.handleLightWeightIndexOperations(def, index));
    handler.handleHeavyWeightIndexOperations(oakIndexResource, def, index);
    verify(handler, never()).disableIndex(any(Resource.class));
    verify(handler, never()).delete(any(Resource.class));
    verify(handler, never()).create(any(Resource.class), any(Resource.class));
    verify(handler, times(1)).update(eq(def), eq(oakIndexResource), eq(true));
    verify(handler, never()).forceRefresh(any(Resource.class));
}

56. EnsureOakIndexJobHandlerTest#testCreateWithForcedReindex()

Project: acs-aem-commons
File: EnsureOakIndexJobHandlerTest.java
@Test
public void testCreateWithForcedReindex() throws RepositoryException, IOException {
    Map<String, Object> props = new HashMap<String, Object>();
    props.put(EnsureOakIndexJobHandler.PN_FORCE_REINDEX, "true");
    Resource def = getEnsureOakDefinition(props);
    Resource index = null;
    Assert.assertFalse(handler.handleLightWeightIndexOperations(def, index));
    handler.handleHeavyWeightIndexOperations(oakIndexResource, def, index);
    verify(handler, never()).disableIndex(any(Resource.class));
    verify(handler, never()).delete(any(Resource.class));
    verify(handler, times(1)).create(eq(def), eq(oakIndexResource));
    verify(handler, times(1)).forceRefresh(any(Resource.class));
}

57. EnsureOakIndexJobHandlerTest#testCreate()

Project: acs-aem-commons
File: EnsureOakIndexJobHandlerTest.java
@Test
public void testCreate() throws RepositoryException, IOException {
    Map<String, Object> props = new HashMap<String, Object>();
    Resource def = getEnsureOakDefinition(props);
    Resource index = null;
    Assert.assertFalse(handler.handleLightWeightIndexOperations(def, index));
    handler.handleHeavyWeightIndexOperations(oakIndexResource, def, index);
    verify(handler, never()).disableIndex(any(Resource.class));
    verify(handler, never()).delete(any(Resource.class));
    verify(handler, times(1)).create(eq(def), eq(oakIndexResource));
    verify(handler, never()).forceRefresh(any(Resource.class));
}

58. EnsureOakIndexJobHandlerTest#testDeletePropertyWithoutExistingIndex()

Project: acs-aem-commons
File: EnsureOakIndexJobHandlerTest.java
@Test
public void testDeletePropertyWithoutExistingIndex() throws PersistenceException, RepositoryException {
    Map<String, Object> props = new HashMap<String, Object>();
    props.put(EnsureOakIndexJobHandler.PN_DELETE, "true");
    props.put(EnsureOakIndexJobHandler.PN_DISABLE, "true");
    Resource def = getEnsureOakDefinition(props);
    Resource r = null;
    Assert.assertTrue(handler.handleLightWeightIndexOperations(def, r));
    verify(handler, never()).disableIndex(any(Resource.class));
    verify(handler, never()).delete(any(Resource.class));
}

59. EnsureOakIndexJobHandlerTest#testDeleteProperty()

Project: acs-aem-commons
File: EnsureOakIndexJobHandlerTest.java
@Test
public void testDeleteProperty() throws PersistenceException, RepositoryException {
    Map<String, Object> props = new HashMap<String, Object>();
    props.put(EnsureOakIndexJobHandler.PN_DELETE, "true");
    props.put(EnsureOakIndexJobHandler.PN_DISABLE, "true");
    Resource def = getEnsureOakDefinition(props);
    Resource r = mock(Resource.class);
    Assert.assertTrue(handler.handleLightWeightIndexOperations(def, r));
    verify(handler, never()).disableIndex(any(Resource.class));
    verify(handler, times(1)).delete(any(Resource.class));
}

60. EnsureOakIndexJobHandlerTest#testDisablePropertyWithoutExistingIndex()

Project: acs-aem-commons
File: EnsureOakIndexJobHandlerTest.java
@Test
public void testDisablePropertyWithoutExistingIndex() throws PersistenceException, RepositoryException {
    Map<String, Object> props = new HashMap<String, Object>();
    props.put(EnsureOakIndexJobHandler.PN_DISABLE, "true");
    Resource def = getEnsureOakDefinition(props);
    Resource r = null;
    Assert.assertTrue(handler.handleLightWeightIndexOperations(def, r));
    verify(handler, never()).disableIndex(any(Resource.class));
    verify(handler, never()).delete(any(Resource.class));
}

61. EnsureOakIndexJobHandlerTest#testDisableProperty()

Project: acs-aem-commons
File: EnsureOakIndexJobHandlerTest.java
@Test
public void testDisableProperty() throws PersistenceException, RepositoryException {
    Map<String, Object> props = new HashMap<String, Object>();
    props.put(EnsureOakIndexJobHandler.PN_DISABLE, "true");
    Resource def = getEnsureOakDefinition(props);
    Resource r = mock(Resource.class);
    Assert.assertTrue(handler.handleLightWeightIndexOperations(def, r));
    verify(handler, times(1)).disableIndex(any(Resource.class));
    verify(handler, never()).delete(any(Resource.class));
}

62. SendTemplatedEmailUtilsTest#testGetPayloadProperties_Page()

Project: acs-aem-commons
File: SendTemplatedEmailUtilsTest.java
@Test
public void testGetPayloadProperties_Page() throws Exception {
    // set up jcr properties
    mockJcrProperties();
    Resource payloadRes = mock(Resource.class);
    Resource jcrRes = mock(Resource.class);
    when(DamUtil.isAsset(payloadRes)).thenReturn(false);
    Page payloadPage = mock(Page.class);
    when(payloadRes.adaptTo(Page.class)).thenReturn(payloadPage);
    when(payloadPage.getContentResource()).thenReturn(jcrRes);
    // mock valueMap
    when(jcrRes.getValueMap()).thenReturn(vmap);
    Map<String, String> props = SendTemplatedEmailUtils.getPayloadProperties(payloadRes, sdf);
    assertEquals(props.get(PN_CALENDAR), CALENDAR_TOSTRING);
    assertEquals(props.get(PN_TITLE), STR_TOSTRING);
    assertEquals(props.get(PN_LONG), LONG_TOSTRING);
    assertEquals(props.get(PN_STR_ARRAY), STR_ARRAY_TOSTRING);
}

63. SendTemplatedEmailUtilsTest#testGetPayloadProperties_Asset()

Project: acs-aem-commons
File: SendTemplatedEmailUtilsTest.java
@Test
public void testGetPayloadProperties_Asset() throws Exception {
    // set up jcr properties
    mockJcrProperties();
    Resource payloadRes = mock(Resource.class);
    Resource mdRes = mock(Resource.class);
    when(DamUtil.isAsset(payloadRes)).thenReturn(true);
    when(payloadRes.getChild(JcrConstants.JCR_CONTENT + "/" + DamConstants.METADATA_FOLDER)).thenReturn(mdRes);
    // mock valueMap
    when(mdRes.getValueMap()).thenReturn(vmap);
    Map<String, String> props = SendTemplatedEmailUtils.getPayloadProperties(payloadRes, sdf);
    assertEquals(props.get(PN_CALENDAR), CALENDAR_TOSTRING);
    assertEquals(props.get(PN_TITLE), STR_TOSTRING);
    assertEquals(props.get(PN_LONG), LONG_TOSTRING);
    assertEquals(props.get(PN_STR_ARRAY), STR_ARRAY_TOSTRING);
}

64. VotingView#hasNoVotes()

Project: sling
File: VotingView.java
/**
     * Checks whether there are any no votes on this voting
     * @return true if there are any no votes on this voting
     */
public boolean hasNoVotes() {
    Resource m = getResource().getChild("members");
    if (m == null) {
        // the vote is being created. wait.
        return false;
    }
    final Iterator<Resource> it = m.getChildren().iterator();
    while (it.hasNext()) {
        Resource aMemberRes = it.next();
        ValueMap properties = aMemberRes.adaptTo(ValueMap.class);
        if (properties == null) {
            continue;
        }
        Boolean vote = properties.get("vote", Boolean.class);
        if (vote != null && !vote) {
            return true;
        }
    }
    return false;
}

65. IdMapService#readIdMap()

Project: sling
File: IdMapService.java
private Map<Integer, String> readIdMap(ResourceResolver resourceResolver) throws PersistenceException {
    Resource resource = ResourceHelper.getOrCreateResource(resourceResolver, getIdMapPath());
    ValueMap idmapValueMap = resource.adaptTo(ValueMap.class);
    Map<Integer, String> idmap = new HashMap<Integer, String>();
    for (String slingId : idmapValueMap.keySet()) {
        Object value = idmapValueMap.get(slingId);
        if (value instanceof Number) {
            Number number = (Number) value;
            idmap.put(number.intValue(), slingId);
        }
    }
    return idmap;
}

66. Announcement#persistTo()

Project: sling
File: Announcement.java
/**
     * Persists this announcement using the given 'announcements' resource,
     * under which a node with the primary key is created
     **/
public void persistTo(Resource announcementsResource) throws PersistenceException, JSONException {
    Resource announcementChildResource = announcementsResource.getChild(getPrimaryKey());
    // SLING-2967 used to introduce 'resetting the created time' here
    // in order to become machine-clock independent.
    // With introduction of SLING-3389, where we dont store any
    // announcement-heartbeat-dates anymore at all, this resetting here
    // became unnecessary.
    final String announcementJson = asJSON();
    if (announcementChildResource == null) {
        final ResourceResolver resourceResolver = announcementsResource.getResourceResolver();
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put("topologyAnnouncement", announcementJson);
        resourceResolver.create(announcementsResource, getPrimaryKey(), properties);
    } else {
        final ModifiableValueMap announcementChildMap = announcementChildResource.adaptTo(ModifiableValueMap.class);
        announcementChildMap.put("topologyAnnouncement", announcementJson);
    }
}

67. DeepReadValueMapDecorator#getValueMap()

Project: sling
File: DeepReadValueMapDecorator.java
private ValueMap getValueMap(final String name) {
    final int pos = name.lastIndexOf("/");
    if (pos == -1) {
        return this.base;
    }
    final Resource rsrc = this.resolver.getResource(pathPrefix + name.substring(0, pos));
    if (rsrc != null) {
        final ValueMap vm = rsrc.adaptTo(ValueMap.class);
        if (vm != null) {
            return vm;
        }
    }
    // fall back
    return ValueMap.EMPTY;
}

68. TwitterAdapterFactory#createTwitterClient()

Project: acs-aem-commons
File: TwitterAdapterFactory.java
private TwitterClient createTwitterClient(com.day.cq.wcm.webservicesupport.Configuration config) {
    Resource oauthConfig = config.getContentResource().listChildren().next();
    ValueMap oauthProps = oauthConfig.getValueMap();
    String consumerKey = oauthProps.get("oauth.client.id", String.class);
    String consumerSecret = oauthProps.get("oauth.client.secret", String.class);
    if (consumerKey != null && consumerSecret != null) {
        Twitter t = factory.getInstance();
        log.debug("Creating client for key {}.", consumerKey);
        t.setOAuthConsumer(consumerKey, consumerSecret);
        try {
            t.getOAuth2Token();
            return new TwitterClientImpl(t, config);
        } catch (TwitterException e) {
            log.error("Unable to create Twitter client.", e);
            return null;
        }
    } else {
        log.warn("Key or Secret missing for configuration {}", config.getPath());
    }
    return null;
}

69. FileImporterTest#testImportToFileWhichIsNewer()

Project: acs-aem-commons
File: FileImporterTest.java
@Test
public void testImportToFileWhichIsNewer() throws Exception {
    Calendar latest = Calendar.getInstance();
    latest.add(Calendar.DATE, 2);
    Node file = JcrUtils.putFile(folder, "test.txt", "x-text/test", new ByteArrayInputStream("".getBytes()), latest);
    session.save();
    Resource resource = mock(Resource.class);
    when(resource.adaptTo(Node.class)).thenReturn(file);
    importer.importData("file", testFile.getAbsolutePath(), resource);
    assertFalse(session.hasPendingChanges());
    assertFalse(folder.hasNode(testFile.getName()));
    // this verifies the the file wasn't imported
    assertEquals("x-text/test", JcrUtils.getStringProperty(file, "jcr:content/jcr:mimeType", ""));
}

70. FileImporterTest#testImportToFile()

Project: acs-aem-commons
File: FileImporterTest.java
@Test
public void testImportToFile() throws Exception {
    Calendar earliest = Calendar.getInstance();
    earliest.setTimeInMillis(0L);
    Node file = JcrUtils.putFile(folder, "test.txt", "x-text/test", new ByteArrayInputStream("".getBytes()), earliest);
    session.save();
    Resource resource = mock(Resource.class);
    when(resource.adaptTo(Node.class)).thenReturn(file);
    importer.importData("file", testFile.getAbsolutePath(), resource);
    assertFalse(session.hasPendingChanges());
    assertFalse(folder.hasNode(testFile.getName()));
    assertEquals("text/plain", JcrUtils.getStringProperty(file, "jcr:content/jcr:mimeType", ""));
}

71. FileImporterTest#testImportToFolderHavingFileWhichIsNewer()

Project: acs-aem-commons
File: FileImporterTest.java
@Test
public void testImportToFolderHavingFileWhichIsNewer() throws Exception {
    Calendar latest = Calendar.getInstance();
    latest.add(Calendar.DATE, 2);
    Node file = JcrUtils.putFile(folder, testFile.getName(), "x-text/test", new ByteArrayInputStream("".getBytes()), latest);
    session.save();
    Resource resource = mock(Resource.class);
    when(resource.adaptTo(Node.class)).thenReturn(folder);
    importer.importData("file", testFile.getAbsolutePath(), resource);
    assertFalse(session.hasPendingChanges());
    assertTrue(folder.hasNode(testFile.getName()));
    // this verifies the the file wasn't imported
    assertEquals("x-text/test", JcrUtils.getStringProperty(file, "jcr:content/jcr:mimeType", ""));
}

72. FileImporterTest#testImportToFolderHavingFileWhichIsOlder()

Project: acs-aem-commons
File: FileImporterTest.java
@Test
public void testImportToFolderHavingFileWhichIsOlder() throws Exception {
    Calendar earliest = Calendar.getInstance();
    earliest.setTimeInMillis(0L);
    Node file = JcrUtils.putFile(folder, testFile.getName(), "x-text/test", new ByteArrayInputStream("".getBytes()), earliest);
    session.save();
    Resource resource = mock(Resource.class);
    when(resource.adaptTo(Node.class)).thenReturn(folder);
    importer.importData("file", testFile.getAbsolutePath(), resource);
    assertFalse(session.hasPendingChanges());
    assertTrue(folder.hasNode(testFile.getName()));
    assertEquals("text/plain", JcrUtils.getStringProperty(file, "jcr:content/jcr:mimeType", ""));
}

73. PackageHelperImplTest#testAddThumbnail()

Project: acs-aem-commons
File: PackageHelperImplTest.java
@Test
public void testAddThumbnail() throws Exception {
    PowerMockito.mockStatic(JcrUtil.class);
    Resource thumbnailResource = mock(Resource.class);
    Node thumbnailNode = mock(Node.class);
    when(thumbnailResource.adaptTo(Node.class)).thenReturn(thumbnailNode);
    when(thumbnailResource.isResourceType("nt:file")).thenReturn(true);
    when(packageOneDefNode.getSession()).thenReturn(mock(Session.class));
    packageHelper.addThumbnail(packageOne, thumbnailResource);
    // Verification
    PowerMockito.verifyStatic(times(1));
    JcrUtil.copy(thumbnailNode, packageOneDefNode, "thumbnail.png");
}

74. EnsureOakIndexJobHandlerTest#testIgnoreProperty()

Project: acs-aem-commons
File: EnsureOakIndexJobHandlerTest.java
@Test
public void testIgnoreProperty() throws PersistenceException, RepositoryException {
    Map<String, Object> props = new HashMap<String, Object>();
    props.put(EnsureOakIndexJobHandler.PN_IGNORE, "true");
    props.put(EnsureOakIndexJobHandler.PN_DISABLE, "true");
    props.put(EnsureOakIndexJobHandler.PN_DELETE, "true");
    Resource def = getEnsureOakDefinition(props);
    Assert.assertTrue(handler.handleLightWeightIndexOperations(def, null));
    verify(handler, never()).disableIndex(any(Resource.class));
    verify(handler, never()).delete(any(Resource.class));
}

75. SendTemplatedEmailUtilsTest#testGetEmailAddrs_User()

Project: acs-aem-commons
File: SendTemplatedEmailUtilsTest.java
@Test
public void testGetEmailAddrs_User() throws Exception {
    String userPath = "/home/users/a/admin";
    MockValue[] emailVal = new MockValue[] { new MockValue("[email protected]") };
    ResourceResolver resolver = mock(ResourceResolver.class);
    Resource userRes = mock(Resource.class);
    Authorizable adminUser = mock(Authorizable.class);
    when(resolver.getResource(userPath)).thenReturn(userRes);
    when(userRes.adaptTo(Authorizable.class)).thenReturn(adminUser);
    when(adminUser.isGroup()).thenReturn(false);
    when(adminUser.hasProperty(PN_EMAIL)).thenReturn(true);
    when(adminUser.getProperty(PN_EMAIL)).thenReturn(emailVal);
    String[] emails = SendTemplatedEmailUtils.getEmailAddrsFromUserPath(resolver, userPath);
    assertEquals(1, emails.length);
    assertEquals("[email protected]", emails[0]);
}

76. RenditionModifyingProcessTest#test_with_rendition_arg_getting_no_rendition_is_noop()

Project: acs-aem-commons
File: RenditionModifyingProcessTest.java
@Test
public void test_with_rendition_arg_getting_no_rendition_is_noop() throws Exception {
    String path = "/content/dam/some/path.ext";
    WorkItem workItem = mock(WorkItem.class);
    WorkflowData data = mock(WorkflowData.class);
    when(workItem.getWorkflowData()).thenReturn(data);
    when(data.getPayloadType()).thenReturn(AbstractAssetWorkflowProcess.TYPE_JCR_PATH);
    when(data.getPayload()).thenReturn(path);
    Resource resource = mock(Resource.class);
    Asset asset = mock(Asset.class);
    when(resource.adaptTo(Asset.class)).thenReturn(asset);
    when(resource.getResourceType()).thenReturn(DamConstants.NT_DAM_ASSET);
    when(resourceResolver.getResource(path)).thenReturn(resource);
    MetaDataMap metaData = new SimpleMetaDataMap();
    metaData.put("PROCESS_ARGS", "renditionName:test");
    process.execute(workItem, workflowSession, metaData);
    verifyZeroInteractions(harness);
}

77. WorkflowPackageManagerImpl#isWorkflowPackage()

Project: acs-aem-commons
File: WorkflowPackageManagerImpl.java
/**
     * {@inheritDoc}
     */
public final boolean isWorkflowPackage(final ResourceResolver resourceResolver, final String path) {
    final PageManager pageManager = resourceResolver.adaptTo(PageManager.class);
    final Page workflowPackagesPage = pageManager.getPage(path);
    if (workflowPackagesPage == null) {
        return false;
    }
    final Resource contentResource = workflowPackagesPage.getContentResource();
    if (contentResource == null) {
        return false;
    }
    if (!contentResource.isResourceType(WORKFLOW_PAGE_RESOURCE_TYPE)) {
        return false;
    }
    if (contentResource.getChild(NN_VLT_DEFINITION) == null) {
        return false;
    }
    return true;
}

78. WorkflowPackageManagerImpl#delete()

Project: acs-aem-commons
File: WorkflowPackageManagerImpl.java
/**
     * {@inheritDoc}
     */
public final void delete(final ResourceResolver resourceResolver, final String path) throws RepositoryException {
    final Resource resource = resourceResolver.getResource(path);
    if (resource == null) {
        log.error("Requesting to delete a non-existent Workflow Package [ {} ]", path);
        return;
    }
    final Node node = resource.adaptTo(Node.class);
    if (node != null) {
        node.remove();
        node.getSession().save();
    } else {
        log.error("Trying to delete a wf resource [ {} ] that does not resolve to a node.", resource.getPath());
    }
}

79. WorkflowInstanceRemoverImpl#getWorkflowInstanceFolders()

Project: acs-aem-commons
File: WorkflowInstanceRemoverImpl.java
private List<Resource> getWorkflowInstanceFolders(final ResourceResolver resourceResolver) {
    final List<Resource> folders = new ArrayList<Resource>();
    final Resource root = resourceResolver.getResource(WORKFLOW_INSTANCES_PATH);
    final Iterator<Resource> itr = root.listChildren();
    boolean addedRoot = false;
    while (itr.hasNext()) {
        Resource resource = itr.next();
        if (isWorkflowServerFolder(resource)) {
            folders.add(resource);
        } else if (!addedRoot && isWorkflowDatedFolder(resource)) {
            folders.add(root);
            addedRoot = true;
        }
    }
    if (folders.isEmpty()) {
        folders.add(root);
    }
    return folders;
}

80. BulkWorkflowEngineImpl#getCurrentBatch()

Project: acs-aem-commons
File: BulkWorkflowEngineImpl.java
/**
     * {@inheritDoc}
     */
@Override
public final Resource getCurrentBatch(final Resource resource) {
    final ValueMap properties = resource.adaptTo(ValueMap.class);
    final String currentBatch = properties.get(KEY_CURRENT_BATCH, "");
    final Resource currentBatchResource = resource.getResourceResolver().getResource(currentBatch);
    if (currentBatchResource == null) {
        log.error("Current batch resource [ {} ] could not be located. Cannot process Bulk workflow.", currentBatch);
    }
    return currentBatchResource;
}

81. WCMViewsFilter#getComponentViews()

Project: acs-aem-commons
File: WCMViewsFilter.java
/**
     * Get the WCM Views for the component; Looks at both the content resource for the special wcmViews property
     * and looks up to the resourceType's cq:Component properties for wcmViews.
     *
     * @param request the request
     * @return the WCM Views for the component
     */
private List<String> getComponentViews(final SlingHttpServletRequest request) {
    final Set<String> views = new HashSet<String>();
    final Resource resource = request.getResource();
    if (resource == null) {
        return new ArrayList<String>(views);
    }
    final Component component = WCMUtils.getComponent(resource);
    final ValueMap properties = resource.adaptTo(ValueMap.class);
    if (component != null) {
        views.addAll(Arrays.asList(component.getProperties().get(PN_WCM_VIEWS, new String[] {})));
    }
    if (properties != null) {
        views.addAll(Arrays.asList(properties.get(PN_WCM_VIEWS, new String[] {})));
    }
    return new ArrayList<String>(views);
}

82. SystemNotificationsImpl#accepts()

Project: acs-aem-commons
File: SystemNotificationsImpl.java
@Override
protected boolean accepts(final ServletRequest servletRequest, final ServletResponse servletResponse) {
    if (!(servletRequest instanceof SlingHttpServletRequest) || !(servletResponse instanceof SlingHttpServletResponse)) {
        return false;
    }
    final SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) servletRequest;
    if (StringUtils.startsWith(slingRequest.getResource().getPath(), PATH_NOTIFICATIONS)) {
        // Do NOT inject on the notifications Authoring pages
        return false;
    }
    final Resource notificationsFolder = slingRequest.getResourceResolver().getResource(PATH_NOTIFICATIONS);
    if (notificationsFolder == null || this.getNotifications(slingRequest, notificationsFolder).size() < 1) {
        // If no notifications folder or no active notifications; do not inject JS
        return false;
    }
    return super.accepts(servletRequest, servletResponse);
}

83. SiteMapServlet#writeAsset()

Project: acs-aem-commons
File: SiteMapServlet.java
private void writeAsset(Asset asset, XMLStreamWriter stream, ResourceResolver resolver) throws XMLStreamException {
    stream.writeStartElement(NS, "url");
    String loc = externalizer.externalLink(resolver, externalizerDomain, asset.getPath());
    writeElement(stream, "loc", loc);
    if (includeLastModified) {
        long lastModified = asset.getLastModified();
        if (lastModified > 0) {
            writeElement(stream, "lastmod", DATE_FORMAT.format(lastModified));
        }
    }
    Resource contentResource = asset.adaptTo(Resource.class).getChild("jcr:content");
    if (contentResource != null) {
        final ValueMap properties = contentResource.getValueMap();
        writeFirstPropertyValue(stream, "changefreq", changefreqProperties, properties);
        writeFirstPropertyValue(stream, "priority", priorityProperties, properties);
    }
    stream.writeEndElement();
}

84. PropertyMergePostProcessor#process()

Project: acs-aem-commons
File: PropertyMergePostProcessor.java
@Override
public final void process(final SlingHttpServletRequest request, final List<Modification> modifications) throws Exception {
    final List<PropertyMerge> propertyMerges = this.getPropertyMerges(request.getRequestParameterMap());
    final Resource resource = request.getResource();
    for (final PropertyMerge propertyMerge : propertyMerges) {
        if (this.merge(resource, propertyMerge.getDestination(), propertyMerge.getSources(), propertyMerge.getTypeHint(), propertyMerge.isAllowDuplicates())) {
            modifications.add(Modification.onModified(resource.getPath()));
            log.debug("Merged property values from {} into [ {} ]", propertyMerge.getSources(), propertyMerge.getDestination());
        }
    }
}

85. UrlFilter#findUrlFilterDefinitionComponent()

Project: acs-aem-commons
File: UrlFilter.java
private Component findUrlFilterDefinitionComponent(Resource resource, ComponentManager componentManager) {
    if (resource == null) {
        return null;
    }
    Resource contentResource = resource.getChild("jcr:content");
    if (contentResource != null) {
        resource = contentResource;
    }
    Component component = componentManager.getComponentOfResource(resource);
    return findUrlFilterDefinitionComponent(component);
}

86. PackageHelperImpl#createPackage()

Project: acs-aem-commons
File: PackageHelperImpl.java
/**
     * {@inheritDoc}
     */
public JcrPackage createPackage(final Collection<Resource> resources, final Session session, final String groupName, final String name, String version, final ConflictResolution conflictResolution, final Map<String, String> packageDefinitionProperties) throws IOException, RepositoryException {
    final List<PathFilterSet> pathFilterSets = new ArrayList<PathFilterSet>();
    for (final Resource resource : resources) {
        pathFilterSets.add(new PathFilterSet(resource.getPath()));
    }
    return this.createPackageFromPathFilterSets(pathFilterSets, session, groupName, name, version, conflictResolution, packageDefinitionProperties);
}

87. SocialImageImpl#getLayer()

Project: acs-aem-commons
File: SocialImageImpl.java
public Layer getLayer(boolean cropped, boolean resized, boolean rotated) throws IOException, RepositoryException {
    Layer layer = null;
    Session session = res.getResourceResolver().adaptTo(Session.class);
    Resource contentRes = res.getChild(JcrConstants.JCR_CONTENT);
    Node node = session.getNode(contentRes.getPath());
    Property data = node.getProperty(JcrConstants.JCR_DATA);
    if (data != null) {
        layer = ImageHelper.createLayer(data);
        if (layer != null && cropped) {
            crop(layer);
        }
        if (layer != null && resized) {
            resize(layer);
        }
        if (layer != null && rotated) {
            rotate(layer);
        }
    }
    return layer;
}

88. ContentFinderHitBuilder#addOtherData()

Project: acs-aem-commons
File: ContentFinderHitBuilder.java
/**
     * Derives and adds Other (non-Page, non-Asset) related information to the map representing the hit.
     *
     * @param hit
     * @param map
     * @return
     * @throws javax.jcr.RepositoryException
     */
private static Map<String, Object> addOtherData(final Hit hit, Map<String, Object> map) throws RepositoryException {
    final Resource resource = hit.getResource();
    final ValueMap properties = resource.adaptTo(ValueMap.class);
    map.put("path", resource.getPath());
    map.put("name", resource.getName());
    map.put("title", properties.get("jcr:title", resource.getName()));
    map.put("excerpt", hit.getExcerpt());
    map.put("lastModified", getLastModified(resource));
    map.put("type", "Data");
    return map;
}

89. ContentFinderHitBuilder#buildGenericResult()

Project: acs-aem-commons
File: ContentFinderHitBuilder.java
/**
     * Builds the result object that will representing a CF view record for the provided hit.
     * <p>
     * This method will generate the result object data points based on if the hit is:
     * 1) a Page
     * 2) an Asset
     * 3) Other
     *
     * @param hit a hit
     * @return a result object
     * @throws RepositoryException if something goes wrong
     */
public static Map<String, Object> buildGenericResult(final Hit hit) throws RepositoryException {
    Map<String, Object> map = new LinkedHashMap<String, Object>();
    final Resource resource = hit.getResource();
    /**
         * Apply custom properties based on the "type"
         */
    // Assets
    final Asset asset = DamUtil.resolveToAsset(resource);
    if (asset != null) {
        return addAssetData(asset, hit, map);
    }
    // Pages
    final Page page = getPage(resource);
    if (page != null) {
        return addPageData(page, hit, map);
    }
    // Other
    return addOtherData(hit, map);
}

90. LongFormTextComponentImpl#getOrCreateLastParagraphSystemResource()

Project: acs-aem-commons
File: LongFormTextComponentImpl.java
private Node getOrCreateLastParagraphSystemResource(final Resource resource, final int lastIndex) throws RepositoryException {
    final String resourceName = LONG_FORM_TEXT_PAR + lastIndex;
    final Resource lastResource = resource.getChild(resourceName);
    if (lastResource != null) {
        return lastResource.adaptTo(Node.class);
    }
    final Node parentNode = resource.adaptTo(Node.class);
    if (parentNode == null) {
        return null;
    }
    final Session session = parentNode.getSession();
    final Node node = JcrUtil.createPath(parentNode, resourceName, false, JcrConstants.NT_UNSTRUCTURED, JcrConstants.NT_UNSTRUCTURED, session, true);
    return node;
}

91. LongFormTextComponentImpl#moveChildrenToNode()

Project: acs-aem-commons
File: LongFormTextComponentImpl.java
private void moveChildrenToNode(Resource resource, Node targetNode) throws RepositoryException {
    for (Resource child : resource.getChildren()) {
        // Use this to create a unique node name; else existing components might get overwritten.
        final Node uniqueNode = JcrUtil.createUniqueNode(targetNode, child.getName(), JcrConstants.NT_UNSTRUCTURED, targetNode.getSession());
        // Once we have a unique node we made as a place holder, we can copy over it w the real component content
        JcrUtil.copy(child.adaptTo(Node.class), targetNode, uniqueNode.getName(), true);
    }
    // Remove the old long-form-text-par- node
    resource.adaptTo(Node.class).remove();
    // Save all changes
    targetNode.getSession().save();
}

92. MergedResourceProviderTestForOverridingPicker#testHideChildrenFromList()

Project: sling
File: MergedResourceProviderTestForOverridingPicker.java
@Test
public void testHideChildrenFromList() {
    final Resource rsrcA2 = this.provider.getResource(ctx, "/override/apps/a/2", ResourceContext.EMPTY_CONTEXT, null);
    final Iterator<Resource> children = this.provider.listChildren(ctx, rsrcA2);
    final List<String> names = new ArrayList<String>();
    while (children.hasNext()) {
        names.add(children.next().getName());
    }
    assertTrue(names.contains("a"));
    assertFalse(names.contains("b"));
    assertTrue(names.contains("c"));
}

93. MergedResourceProviderTestForMergingPicker#testListSubChildren()

Project: sling
File: MergedResourceProviderTestForMergingPicker.java
@Test
public void testListSubChildren() {
    final Resource rsrcY = this.provider.getResource(ctx, "/merged/a/Y", ResourceContext.EMPTY_CONTEXT, null);
    assertNotNull(rsrcY);
    final Iterator<Resource> i = this.provider.listChildren(ctx, rsrcY);
    assertNotNull(i);
    final List<String> names = new ArrayList<String>();
    while (i.hasNext()) {
        names.add(i.next().getName());
    }
    assertEquals(3, names.size());
    assertTrue(names.contains("a"));
    assertTrue(names.contains("b"));
    assertTrue(names.contains("c"));
}

94. MergedResourceProviderTestForMergingPicker#testListChildren()

Project: sling
File: MergedResourceProviderTestForMergingPicker.java
@Test
public void testListChildren() {
    final Resource rsrcA = this.provider.getResource(ctx, "/merged/a", ResourceContext.EMPTY_CONTEXT, null);
    assertNotNull(rsrcA);
    final Iterator<Resource> i = this.provider.listChildren(ctx, rsrcA);
    assertNotNull(i);
    final List<String> names = new ArrayList<String>();
    while (i.hasNext()) {
        names.add(i.next().getName());
    }
    assertEquals(6, names.size());
    assertTrue(names.contains("1"));
    assertTrue(names.contains("2"));
    assertTrue(names.contains("3"));
    assertTrue(names.contains("4"));
    assertTrue(names.contains("Y"));
    assertTrue(names.contains("X"));
}

95. CommonMergedResourceProviderTest#testOrderBeingModifiedThroughOrderBefore()

Project: sling
File: CommonMergedResourceProviderTest.java
@Test
public void testOrderBeingModifiedThroughOrderBefore() throws PersistenceException {
    // create new child nodes below base and overlay
    MockHelper.create(this.resolver).resource("/apps/base/child1").resource("/apps/base/child2").resource("/apps/overlay/child3").p(MergedResourceConstants.PN_ORDER_BEFORE, "child2").commit();
    Resource mergedResource = this.provider.getResource(ctx, "/merged", ResourceContext.EMPTY_CONTEXT, null);
    // convert the iterator returned by list children into an iterable (to be able to perform some tests)
    IteratorIterable<Resource> iterable = new IteratorIterable<Resource>(provider.listChildren(ctx, mergedResource), true);
    Assert.assertThat(iterable, Matchers.contains(ResourceMatchers.resourceWithName("child1"), ResourceMatchers.resourceWithName("child3"), ResourceMatchers.resourceWithName("child2")));
}

96. CommonMergedResourceProviderTest#testOrderOfNonOverlappingChildren()

Project: sling
File: CommonMergedResourceProviderTest.java
@Test
public void testOrderOfNonOverlappingChildren() throws PersistenceException {
    // create new child nodes below base and overlay
    MockHelper.create(this.resolver).resource("/apps/base/child1").resource("/apps/base/child2").resource("/apps/overlay/child3").resource("/apps/overlay/child4").commit();
    Resource mergedResource = this.provider.getResource(ctx, "/merged", ResourceContext.EMPTY_CONTEXT, null);
    // convert the iterator returned by list children into an iterable (to be able to perform some tests)
    IteratorIterable<Resource> iterable = new IteratorIterable<Resource>(provider.listChildren(ctx, mergedResource), true);
    Assert.assertThat(iterable, Matchers.contains(ResourceMatchers.resourceWithName("child1"), ResourceMatchers.resourceWithName("child2"), ResourceMatchers.resourceWithName("child3"), ResourceMatchers.resourceWithName("child4")));
}

97. CommonMergedResourceProviderTest#testOrderOfPartiallyOverwrittenChildren()

Project: sling
File: CommonMergedResourceProviderTest.java
@Test
public void testOrderOfPartiallyOverwrittenChildren() throws PersistenceException {
    // see https://issues.apache.org/jira/browse/SLING-4915
    // create new child nodes below base and overlay
    MockHelper.create(this.resolver).resource("/apps/base/child1").resource("/apps/base/child2").resource("/apps/base/child3").resource("/apps/overlay/child4").resource("/apps/overlay/child2").resource("/apps/overlay/child3").commit();
    Resource mergedResource = this.provider.getResource(ctx, "/merged", ResourceContext.EMPTY_CONTEXT, null);
    // convert the iterator returned by list children into an iterable (to be able to perform some tests)
    IteratorIterable<Resource> iterable = new IteratorIterable<Resource>(provider.listChildren(ctx, mergedResource), true);
    Assert.assertThat(iterable, Matchers.contains(ResourceMatchers.resourceWithName("child1"), ResourceMatchers.resourceWithName("child4"), ResourceMatchers.resourceWithName("child2"), ResourceMatchers.resourceWithName("child3")));
}

98. CommonMergedResourceProviderTest#testHideChildrenBeingSetOnParent()

Project: sling
File: CommonMergedResourceProviderTest.java
@Test
public void testHideChildrenBeingSetOnParent() throws PersistenceException {
    // create new child nodes below base and overlay
    MockHelper.create(this.resolver).resource("/apps/base/child").p("property1", "frombase").resource("grandchild").p("property1", "frombase").resource("/apps/base/child2").p("property1", "frombase").resource("/apps/overlay/child").p("property1", "fromoverlay").commit();
    ModifiableValueMap properties = overlay.adaptTo(ModifiableValueMap.class);
    properties.put(MergedResourceConstants.PN_HIDE_CHILDREN, "*");
    resolver.commit();
    Resource mergedResource = this.provider.getResource(ctx, "/merged", ResourceContext.EMPTY_CONTEXT, null);
    // the child was hidden on the parent (but only for the underlying resource), the local child from the overlay is still exposed
    Assert.assertThat(provider.getResource(ctx, "/merged/child", ResourceContext.EMPTY_CONTEXT, mergedResource), ResourceMatchers.resourceWithNameAndProps("child", Collections.singletonMap("property1", (Object) "fromoverlay")));
}

99. CommonMergedResourceProviderTest#testHideChildrenWithResourceNamesStartingWithExclamationMark()

Project: sling
File: CommonMergedResourceProviderTest.java
@Test
public void testHideChildrenWithResourceNamesStartingWithExclamationMark() throws PersistenceException {
    // create new child nodes below base and overlay
    MockHelper.create(this.resolver).resource("/apps/base/!child1").p("property1", "frombase").resource("/apps/overlay/!child1").p("property1", "fromoverlay").resource("/apps/overlay/!child3").p("property1", "fromoverlay").commit();
    ModifiableValueMap properties = overlay.adaptTo(ModifiableValueMap.class);
    // escape the resource name with another exclamation mark
    properties.put(MergedResourceConstants.PN_HIDE_CHILDREN, "!!child3");
    resolver.commit();
    Resource mergedResource = this.provider.getResource(ctx, "/merged", ResourceContext.EMPTY_CONTEXT, null);
    // convert the iterator returned by list children into an iterable (to be able to perform some tests)
    IteratorIterable<Resource> iterable = new IteratorIterable<Resource>(provider.listChildren(ctx, mergedResource), true);
    // the resource named "!child3" should be hidden
    Assert.assertThat(iterable, Matchers.contains(ResourceMatchers.resourceWithNameAndProps("!child1", Collections.singletonMap("property1", (Object) "fromoverlay"))));
}

100. StubResource#getParent()

Project: sling
File: StubResource.java
@Override
public Resource getParent() {
    final Resource parent = super.getParent();
    if (parent != null) {
        return parent;
    } else {
        final String absPath = getPath();
        final int lastIdx = absPath.lastIndexOf('/');
        if (lastIdx <= 0) {
            return null;
        } else {
            final String parentPath = absPath.substring(0, lastIdx);
            return new StubResource(getResourceResolver(), parentPath);
        }
    }
}