Java Code Examples for org.apache.sling.api.resource.Resource#getValueMap()

The following examples show how to use org.apache.sling.api.resource.Resource#getValueMap() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RatingsServiceImpl.java    From sling-samples with Apache License 2.0 7 votes vote down vote up
/**
 * @see org.apache.sling.sample.slingshot.ratings.RatingsService#getRating(org.apache.sling.api.resource.Resource)
 */
@Override
public double getRating(final Resource resource) {
    final String fullPath = getRatingsResourcePath(resource);
    float rating = 0;
    if ( fullPath != null ) {
        final Resource ratingsResource = resource.getChild(fullPath);
        if ( ratingsResource != null ) {
            int count = 0;
            for(final Resource r : ratingsResource.getChildren()) {
                final ValueMap vm = r.getValueMap();
                final double current = vm.get(RatingsUtil.PROPERTY_RATING, 0.0);
                rating += current;
                count++;
            }
            if ( count > 0 ) {
                rating = rating / count;
            }
        }
    }
    return rating;
}
 
Example 2
Source File: GraphqlResourceProviderTest.java    From commerce-cif-connector with Apache License 2.0 6 votes vote down vote up
@Test
public void testQueryLanguageProvider() throws IOException {
    Utils.setupHttpResponse("magento-graphql-categorylist-coats.json", httpClient, HttpStatus.SC_OK,
        "{categoryList(filters:{url_key:{eq:\"coats\"");
    Utils.setupHttpResponse("magento-graphql-products-search.json", httpClient, HttpStatus.SC_OK, "{product");

    // The search request coming from com.adobe.cq.commerce.impl.omnisearch.ProductsOmniSearchHandler is serialized in JSON
    String jsonRequest = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream(
        "commerce-products-omni-search-request.json"), StandardCharsets.UTF_8);

    QueryLanguageProvider queryLanguageProvider = provider.getQueryLanguageProvider();
    assertTrue(ArrayUtils.contains(queryLanguageProvider.getSupportedLanguages(null), VIRTUAL_PRODUCT_QUERY_LANGUAGE));

    Iterator<Resource> resources = queryLanguageProvider.findResources(resolveContext, jsonRequest, VIRTUAL_PRODUCT_QUERY_LANGUAGE);

    // We only check the first "meskwielt" product
    Resource resource = resources.next();
    assertEquals(PRODUCT_PATH, resource.getPath());

    ValueMap valueMap = resource.getValueMap();
    assertEquals(SKU, valueMap.get("sku", String.class));
    assertEquals(PRODUCT, valueMap.get(CommerceConstants.PN_COMMERCE_TYPE, String.class));
    assertEquals(MAGENTO_GRAPHQL_PROVIDER, valueMap.get(CommerceConstants.PN_COMMERCE_PROVIDER, String.class));
}
 
Example 3
Source File: AkismetServiceImpl.java    From publick-sling-blog with Apache License 2.0 6 votes vote down vote up
/**
 * Get an AkismetComment from a publick:comment resource.
 *
 * @param commentResource The publick:comment resource.
 * @return Akismet Comment created from the properties of the comment resource.
 */
private AkismetComment getAkismetComment(final Resource commentResource) {
    final AkismetComment akismetComment = new AkismetComment();

    if (commentResource != null) {
        final ValueMap properties = commentResource.getValueMap();

        // Get external link taking extensionless URLs into account
        String externalLink = StringUtils.removeEnd(getDomainName(), "/");
        externalLink = externalLink.concat(linkRewriter.rewriteLink(commentResource.getPath()));

        akismetComment.setUserIp(properties.get(PublickConstants.COMMENT_PROPERTY_USER_IP, String.class));
        akismetComment.setUserAgent(properties.get(PublickConstants.COMMENT_PROPERTY_USER_AGENT, String.class));
        akismetComment.setReferrer(properties.get(PublickConstants.COMMENT_PROPERTY_REFERRER, String.class));
        akismetComment.setPermalink(externalLink);
        akismetComment.setCommentType(AKISMET_COMMENT_TYPE);
        akismetComment.setCommentAuthor(properties.get(PublickConstants.COMMENT_PROPERTY_AUTHOR, String.class));
        akismetComment.setCommentContent(properties.get(PublickConstants.COMMENT_PROPERTY_COMMENT, String.class));
    }

    return akismetComment;
}
 
Example 4
Source File: CommerceTeaserImpl.java    From aem-core-cif-components with Apache License 2.0 5 votes vote down vote up
void populateActions() {
    Resource actionsNode = resource.getChild(CommerceTeaser.NN_ACTIONS);
    if (actionsNode != null) {
        for (Resource action : actionsNode.getChildren()) {

            ValueMap properties = action.getValueMap();
            String title = properties.get(PN_ACTION_TEXT, String.class);
            String productSlug = properties.get(PN_ACTION_PRODUCT_SLUG, String.class);
            String categoryId = properties.get(PN_ACTION_CATEGORY_ID, String.class);
            String selector = null;
            Page page;
            boolean isProduct = false;

            if (categoryId != null) {
                page = categoryPage;
                selector = categoryId;
            } else if (productSlug != null) {
                page = productPage;
                selector = productSlug;
                isProduct = true;
            } else {
                page = currentPage;

            }
            actions.add(new CommerceTeaserActionItem(title, selector, page, request, urlProvider, isProduct));
        }
    }
}
 
Example 5
Source File: ContentResourceShouldBeNullCheckedCheck.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
private ValueMap checkForNullWithObjectsNonNull(Resource resource) {
  ValueMap result = new ValueMapDecorator(new HashMap<>());
  Page page = resource.adaptTo(Page.class);
  Resource pageResource = page.getContentResource("test");
  if (Objects.nonNull(pageResource)) {
    result = pageResource.getValueMap();
  }
  return result;
}
 
Example 6
Source File: ContentResourceShouldBeNullCheckedCheck.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
private boolean contentResourceNullCheckWithImmediateReturn(Resource resource) {
  Page page = resource.adaptTo(Page.class);
  Resource contentResource = page.getContentResource();
  if (contentResource == null) {
    return false;
  }
  contentResource.getValueMap();
  return true;
}
 
Example 7
Source File: ContentResourceShouldBeNullCheckedCheck.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
private ValueMap checkForNullWithObjectsIsNull(Resource resource) {
  ValueMap result = new ValueMapDecorator(new HashMap<>());
  Page page = resource.adaptTo(Page.class);
  Resource pageResource = page.getContentResource("test");
  if (Objects.isNull(pageResource)) {
    return result;
  } else {
    return pageResource.getValueMap();
  }
}
 
Example 8
Source File: AuthenticatedRemoteResourceProviderTest.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
@Test
void testResourceReadingFromMetaFile() {
    Resource hey_bob = resourceProvider.getResource(bob, "/content/test-1/hey", resourceContext, null);
    assertNotNull(hey_bob, "Expected to find /content/test-1/hey for user bob.");
    assertEquals(ServletResolverConstants.DEFAULT_RESOURCE_TYPE, hey_bob.getResourceType(),
            () -> "Expected that /content/test-1/hey's resource type is " + ServletResolverConstants.DEFAULT_RESOURCE_TYPE);
    ValueMap heyProperties = hey_bob.getValueMap();
    assertEquals(1, heyProperties.size());
    assertEquals(ServletResolverConstants.DEFAULT_RESOURCE_TYPE, heyProperties.get(ResourceResolver.PROPERTY_RESOURCE_TYPE,
            String.class));
    assertEquals(ServletResolverConstants.DEFAULT_RESOURCE_TYPE, hey_bob.getResourceType(),
            () -> "Expected that /content/test-1/hey's resource type is " + ServletResolverConstants.DEFAULT_RESOURCE_TYPE);

    Resource joe_bob = resourceProvider.getResource(bob, "/content/test-1/hey/joe", resourceContext, null);
    assertNotNull(joe_bob, "Expected to find /content/test-1/hey/joe");
    assertEquals(ServletResolverConstants.DEFAULT_RESOURCE_TYPE, joe_bob.getResourceType(),
            () -> "Expected that /content/test-1/hey/joe's resource type is " + ServletResolverConstants.DEFAULT_RESOURCE_TYPE);

    ValueMap joeProperties = joe_bob.getValueMap();
    assertEquals(2, joeProperties.size());
    assertEquals(ServletResolverConstants.DEFAULT_RESOURCE_TYPE, joeProperties.get(ResourceResolver.PROPERTY_RESOURCE_TYPE,
            String.class));
    Calendar joelastModified = joeProperties.get("lastModifiedDate", Calendar.class);
    assertNotNull(joelastModified, String.format("Expected a lastModifiedDate property on %s", joe_bob.getPath()));
    assertEquals(1407421980000L, joelastModified.getTimeInMillis());

    assertTrue(wrapsSameResource(joe_bob, getChild(bob, hey_bob, "joe")), "Expected to get a cached " +
            "representation of /content/test-1/hey/joe");

    Iterator<Resource> joeChildren = resourceProvider.listChildren(bob, joe_bob);
    assertNull(joeChildren, String.format("Did not expect children resources for %s", joe_bob.getPath()));

    Resource hey_alice = resourceProvider.getResource(alice, "/content/test-1/hey", resourceContext, null);
    assertNull(hey_alice, "Did not expect user alice to have access to /content/test-1/hey.");
}
 
Example 9
Source File: RatingsServiceImpl.java    From sling-samples with Apache License 2.0 5 votes vote down vote up
/**
 * @see org.apache.sling.sample.slingshot.ratings.RatingsService#getRating(org.apache.sling.api.resource.Resource, java.lang.String)
 */
@Override
public double getRating(final Resource resource, final String userId) {
    final String fullPath = getRatingsResourcePath(resource);
    double rating = 0;

    final Resource r = resource.getResourceResolver().getResource(fullPath + "/" + userId);
    if ( r != null ) {
        final ValueMap vm = r.getValueMap();
        rating = vm.get(RatingsUtil.PROPERTY_RATING, 0.0);
    }
    return rating;
}
 
Example 10
Source File: children.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
@Override
public boolean evaluate(Resource resource) {
    ValueMap valueMap = resource.getValueMap();

    if (!valueMap.containsKey("sling:resourceType") || !valueMap.containsKey("cq:commerceType"))
        return false;

    final boolean ret = resource.isResourceType("sling:Folder") &&
            "category".equals(valueMap.get("cq:commerceType", String.class));

    return ret;
}
 
Example 11
Source File: ContentResourceShouldBeNullCheckedCheck.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
private ValueMap checkForNonNullWithCommonsObjectUtilsAllNotNullMultipleResources(Resource resource) {
  ValueMap result = new ValueMapDecorator(new HashMap<>());
  Page page = resource.adaptTo(Page.class);
  Resource pageResource = page.getContentResource("test");
  Resource pageResource2 = page.getContentResource("test");
  Resource pageResource3 = page.getContentResource("test");
  if (ObjectUtils.allNotNull(pageResource, pageResource2)) {
    result = pageResource.getValueMap();
    result = pageResource2.getValueMap();
    result = pageResource3.getValueMap(); // Noncompliant
  }
  return result;
}
 
Example 12
Source File: CIFCategoryFieldHelper.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
public boolean hasChildren() {
    Resource resource = getResource();
    ValueMap valueMap = resource.getValueMap();
    if (valueMap != null && valueMap.containsKey("isLeaf") && valueMap.get("isLeaf").equals(true)) {
        return false;
    }
    return true;
}
 
Example 13
Source File: MultiFieldDropTargetPostProcessorTest.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
@Test
public void testDropTargetWithSkuSelection() throws Exception {
    Map<String, Object> map = new HashMap<>();
    map.put("./multiDropTarget->@items", "/var/commerce/products/a");
    map.put("./selectionId", "sku");
    map.put("./multiple", Boolean.FALSE);
    map.put("./@CopyFrom", "/does/not/matter");

    // During an AEM drag and drop, the Sling POST will contain a COPY modification with the target component
    // In this test, we mock that something is copied to /content/postprocessor/jcr:content/noExistingMultiValue
    List<Modification> modifications = new ArrayList<>();
    modifications.add(Modification.onCopied("/does/not/matter", "/content/postprocessor/jcr:content/noExistingMultiValue"));

    // During an AEM drag and drop, the Sling POST is typically sent to the responsivegrid
    // In this test, we just set to any location, we'll just have to check that the dropped properties are not added there
    MockSlingHttpServletRequest request = new MockSlingHttpServletRequest(context.resourceResolver());
    request.setResource(context.resourceResolver().resolve("/content/postprocessor/jcr:content/noExistingComposite"));
    request.setParameterMap(map);

    MultiFieldDropTargetPostProcessor dropTargetPostProcessor = new MultiFieldDropTargetPostProcessor();
    dropTargetPostProcessor.process(request, modifications);

    assertThat(modifications).hasSize(2); // there is an extra modification to /content/postprocessor/jcr:content/noExistingMultiValue

    // The target resource of the POST should NOT have the new property
    Resource resource = request.getResource();
    assertThat(resource.getValueMap()).hasSize(1); // just {"jcr:primaryType"="nt:unstructured"}

    // The "copy" resource of the POST MUST contain the new property
    Resource dropTargetResource = resource.getResourceResolver().getResource("/content/postprocessor/jcr:content/noExistingMultiValue");
    ValueMap targetValueMap = dropTargetResource.getValueMap();
    assertThat(targetValueMap.get("items", String.class)).isEqualTo("a");
}
 
Example 14
Source File: ChildrenDataSourceServlet.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
private static Predicate createProductPredicate(String commerceType) {
    return object -> {
        final Resource resource = (Resource) object;
        ValueMap valueMap = resource.getValueMap();

        return valueMap.containsKey("sling:resourceType") &&
            resource.isResourceType("commerce/components/product") &&
            valueMap.containsKey("cq:commerceType") &&
            commerceType.equals(valueMap.get("cq:commerceType", String.class));
    };
}
 
Example 15
Source File: ConfigurationColumnPreview.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
@PostConstruct
protected void initModel() {

    Config cfg = new Config(request.getResource());

    final SlingScriptHelper sling = ((SlingBindings) request.getAttribute(SlingBindings.class.getName())).getSling();
    ExpressionResolver expressionResolver = sling.getService(ExpressionResolver.class);
    final ExpressionHelper ex = new ExpressionHelper(expressionResolver, request);

    String itemResourcePath = ex.getString(cfg.get("path", String.class));
    LOG.debug("Item in preview is at path {}", itemResourcePath);

    itemResource = request.getResourceResolver().getResource(itemResourcePath);
    if (itemResource == null) {
        return;
    }
    isFolder = itemResource.isResourceType(JcrConstants.NT_FOLDER) || itemResource.isResourceType(JcrResourceConstants.NT_SLING_FOLDER)
        || itemResource
            .isResourceType(JcrResourceConstants.NT_SLING_ORDERED_FOLDER);

    if (isFolder) {
        properties = itemResource.getValueMap();
    } else {
        Resource jcrContent = itemResource.getChild(JcrConstants.JCR_CONTENT);
        properties = jcrContent != null ? jcrContent.getValueMap() : itemResource.getValueMap();
    }
}
 
Example 16
Source File: ContentResourceShouldBeNullCheckedCheck.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
private ValueMap checkForNullWithCommonsObjectUtilsAllNotNull(Resource resource) {
  ValueMap result = new ValueMapDecorator(new HashMap<>());
  Page page = resource.adaptTo(Page.class);
  Resource pageResource = page.getContentResource("test");
  if (ObjectUtils.allNotNull(pageResource)) {
    result = pageResource.getValueMap();
  }
  return result;
}
 
Example 17
Source File: ProductBindingCreator.java    From commerce-cif-connector with Apache License 2.0 4 votes vote down vote up
private void processAddition(ResourceChange change) {
    resolver.refresh();
    String path = change.getPath();
    LOG.debug("Process resource addition at path {}", path);

    Resource changedResource = resolver.getResource(path);
    if (changedResource == null) {
        LOG.warn("Cannot retrieve resource at {}. Does the user have the require privileges?", path);
        return;
    }
    Resource contentResource = changedResource.getChild(JcrConstants.JCR_CONTENT);

    ValueMap properties;
    if (contentResource != null) {
        properties = contentResource.getValueMap();
    } else {
        properties = changedResource.getValueMap();
    }

    String storeView = properties.get(Constants.PN_MAGENTO_STORE, "");
    if (StringUtils.isEmpty(storeView)) {
        LOG.warn("The configuration at path {} doesn't have a '{}' property", path, Constants.PN_MAGENTO_STORE);
        return;
    }

    String configRoot = path.substring(0, path.indexOf(Constants.COMMERCE_BUCKET_PATH) - 1);
    String configName = configRoot.substring(configRoot.lastIndexOf("/") + 1);

    String bindingName = configName + "-" + storeView;
    LOG.debug("New binding name: {}", bindingName);

    Map<String, Object> mappingProperties = new HashMap<>();
    mappingProperties.put(JcrConstants.JCR_PRIMARYTYPE, "sling:Folder");
    mappingProperties.put(JcrConstants.JCR_TITLE, bindingName);
    mappingProperties.put(Constants.PN_CONF, configRoot);

    Resource parent = resolver.getResource(BINDINGS_PARENT_PATH);
    if (parent == null) {
        LOG.warn("Binding parent path not found at {}. Nothing to do here...", BINDINGS_PARENT_PATH);
        return;
    }

    String bindingPath = parent.getPath() + "/" + bindingName;
    LOG.debug("Check if we already have a binding at {}", bindingPath);

    try {
        LOG.debug("Creating a new resource at {}", bindingPath);
        ResourceUtil.getOrCreateResource(resolver, bindingPath, mappingProperties, "", true);

        if (contentResource != null) {
            LOG.debug("Adding {} property at {}", Constants.PN_CATALOG_PATH, contentResource.getPath());
            ModifiableValueMap map = contentResource.adaptTo(ModifiableValueMap.class);
            map.put(Constants.PN_CATALOG_PATH, bindingPath);
            resolver.commit();
        }
    } catch (PersistenceException e) {
        LOG.error(e.getMessage(), e);
    }

}
 
Example 18
Source File: ModelPersistTest.java    From sling-whiteboard with Apache License 2.0 4 votes vote down vote up
@Test
public void testMappedNames() throws RepositoryException, PersistenceException, IllegalArgumentException, IllegalAccessException, JsonProcessingException {
    // Create test beans
    BeanWithMappedNames.ChildBean child1 = new BeanWithMappedNames.ChildBean();
    BeanWithMappedNames.ChildBean child2 = new BeanWithMappedNames.ChildBean();
    BeanWithMappedNames.ChildBean child3 = new BeanWithMappedNames.ChildBean();
    child1.setName("child-1");
    child2.setName("child-2");
    child3.setName("child-3");

    BeanWithMappedNames bean = new BeanWithMappedNames();
    bean.setWrong1("Name");
    bean.setWrong2(new String[]{"foo", "bar", "baz"});
    bean.setWrong3(child1);
    bean.setWrong4(Arrays.asList(child1, child2, child3));
    bean.setWrong5(new HashMap<String, BeanWithMappedNames.ChildBean>() {
        {
            put("child1", child1);
            put("child2", child2);
            put("child3", child3);
        }
    });
    bean.setWrong6(Boolean.TRUE);

    // Persist values
    jcrPersist.persist("/test/mapped", bean, rr);

    // Check that everything stored correctly
    Resource res = rr.getResource("/test/mapped");
    ValueMap properties = res.getValueMap();
    // Part 1: Simple property
    assertEquals("Name", properties.get("prop-1", String.class));
    assertNull(properties.get("wrong1"));
    // Part 2: Array property
    String[] prop2 = properties.get("prop-2", String[].class);
    assertArrayEquals(prop2, new String[]{"foo", "bar", "baz"});
    assertNull(properties.get("wrong2"));
    // Part 3: Object property
    assertNull(rr.getResource("/test/mapped/wrong3"));
    Resource childRes1 = rr.getResource("/test/mapped/child-1");
    assertNotNull(childRes1);
    assertEquals("child-1", childRes1.getValueMap().get("name"));
    // Part 4: Object list property
    assertNull(rr.getResource("/test/mapped/wrong4"));
    Resource childRes2 = rr.getResource("/test/mapped/child-2");
    assertNotNull(childRes2);
    assertEquals(StreamSupport
            .stream(childRes2.getChildren().spliterator(), false)
            .count(), 3L);
    // Part 5: Map-of-objects property
    assertNull(rr.getResource("/test/mapped/wrong5"));
    Resource childRes3 = rr.getResource("/test/mapped/child-3");
    assertNotNull(childRes3);
    assertEquals(StreamSupport
            .stream(childRes3.getChildren().spliterator(), false)
            .count(), 3L);
    // Part 6: Boolean property
    assertNull(properties.get("wrong6"));
    assertNull(properties.get("isWrong6"));
    assertTrue(properties.get("prop-3", Boolean.class));

    // Now confirm Jackson respects its mappings too
    ObjectMapper mapper = new ObjectMapper();
    String json = mapper.writeValueAsString(bean);
    assertFalse("Should not have wrong property names: " + json, json.contains("wrong"));
    assertTrue("Should have prop-1" + json, json.contains("prop-1"));
    assertTrue("Should have prop-2" + json, json.contains("prop-2"));
    assertTrue("Should have prop-3" + json, json.contains("prop-3"));
    assertTrue("Should have child-1" + json, json.contains("child-1"));
    assertTrue("Should have child-2" + json, json.contains("child-2"));
    assertTrue("Should have child-3" + json, json.contains("child-3"));
}
 
Example 19
Source File: PropertyPredicates.java    From sling-whiteboard with Apache License 2.0 4 votes vote down vote up
private ValueMap valueMapOf(Resource resource) {
    if (resource == null || ResourceUtil.isNonExistingResource(resource)) {
        return ValueMap.EMPTY;
    }
    return resource.getValueMap();
}
 
Example 20
Source File: ConfigurationColumnViewItem.java    From commerce-cif-connector with Apache License 2.0 4 votes vote down vote up
public String getTitle() {
    Resource jcrContent = resource.getChild(JcrConstants.JCR_CONTENT);
    ValueMap properties = jcrContent != null ? jcrContent.getValueMap() : resource.getValueMap();
    return properties.get(JcrConstants.JCR_TITLE, resource.getName());
}