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

The following examples show how to use org.apache.sling.api.resource.Resource#adaptTo() . 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: AkismetServiceImpl.java    From publick-sling-blog with Apache License 2.0 6 votes vote down vote up
/**
 * Submit comment as ham to the Akismet servers.
 *
 * If a comment gets checked and incorrectly is reported as spam, this will
 * submit it back to the servers as ham to correct a false positive.
 *
 * @param commentResource The publick:comment resource to act upon.
 * @return true if submission was successful.
 */
public boolean submitHam(final Resource commentResource) {
    final boolean result = doAkismet(AkismetAction.SUBMIT_HAM, commentResource);

    if (result) {
        try {
            final ModifiableValueMap properties = commentResource.adaptTo(ModifiableValueMap.class);
            properties.put(PublickConstants.COMMENT_PROPERTY_SPAM, false);
            properties.put(PublickConstants.COMMENT_PROPERTY_DISPLAY, true);
            commentResource.getResourceResolver().commit();
        } catch (PersistenceException e) {
            LOGGER.error("Could not save spam properties", e);
        }
    }

    return result;
}
 
Example 2
Source File: MapOfChildResourcesInjectorTest.java    From sling-whiteboard with Apache License 2.0 6 votes vote down vote up
@Test
public void roundtripTestDirectChildren() throws RepositoryException, PersistenceException, IllegalArgumentException, IllegalAccessException {
    BeanWithDirectMappedChildren source = new BeanWithDirectMappedChildren();
    source.addPerson("joe", "schmoe");
    source.addPerson("john", "doe");
    source.addPerson("bob", "smith");
    jcrPersist.persist("/test/bean", source, rr);

    Resource targetResource = rr.getResource("/test/bean");
    assertNotNull("Bean should have been persisted");

    Resource personRes = rr.getResource("/test/bean/smith-bob");
    assertNotNull("Person should have persisted in repository", personRes);

    BeanWithDirectMappedChildren target = targetResource.adaptTo(BeanWithDirectMappedChildren.class);
    assertNotNull("Bean should deserialize", target);

    assertEquals("Should have 3 children", 3, target.people.size());
}
 
Example 3
Source File: GraphqlResourceProviderTest.java    From commerce-cif-connector with Apache License 2.0 6 votes vote down vote up
@Test
public void testMasterVariantResource() throws IOException, CommerceException {
    Utils.setupHttpResponse("magento-graphql-categorylist-empty.json", httpClient, HttpStatus.SC_OK,
        "{categoryList(filters:{url_key:{eq:\"meskwielt-Purple-XS\"");
    Utils.setupHttpResponse("magento-graphql-categorylist-empty.json", httpClient, HttpStatus.SC_OK,
        "{categoryList(filters:{url_key:{eq:\"meskwielt\"");
    Utils.setupHttpResponse("magento-graphql-categorylist-coats.json", httpClient, HttpStatus.SC_OK,
        "{categoryList(filters:{url_key:{eq:\"coats\"");
    Utils.setupHttpResponse("magento-graphql-product.json", httpClient, HttpStatus.SC_OK, "{product");

    Resource resource = provider.getResource(resolveContext, MASTER_VARIANT_PATH, null, null);
    assertTrue(resource instanceof ProductResource);
    assertFalse(resource.getValueMap().get("hasChildren", Boolean.class));
    assertEquals(MASTER_VARIANT_SKU, resource.getValueMap().get("sku", String.class));

    Product product = resource.adaptTo(Product.class);
    assertMasterVariant(product);

    // deep read sku
    assertEquals(MASTER_VARIANT_SKU, resource.getValueMap().get("./sku", String.class));
}
 
Example 4
Source File: MapOfChildResourcesInjectorTest.java    From sling-whiteboard with Apache License 2.0 6 votes vote down vote up
@Test
public void roundtripEmpytTest() throws RepositoryException, PersistenceException, IllegalArgumentException, IllegalAccessException {
    BeanWithMappedChildren source = new BeanWithMappedChildren();
    jcrPersist.persist("/test/empty-bean", source, rr);

    Resource targetResource = rr.getResource("/test/empty-bean");
    assertNotNull("Bean should have been persisted");

    Resource personRes = rr.getResource("/test/empty-bean/people");
    assertNull("Person should not have persisted in repository", personRes);

    BeanWithMappedChildren target = targetResource.adaptTo(BeanWithMappedChildren.class);
    assertNotNull("Bean should deserialize", target);

    assertEquals("Should have 0 children", 0, target.people.size());
}
 
Example 5
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 6
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 7
Source File: ModelPersistorImpl.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
private void persistField(@NotNull Resource resource, @NotNull Object instance, Field field, boolean deepPersist) {
    try {
        // read the existing resource map
        ModifiableValueMap values = resource.adaptTo(ModifiableValueMap.class);
        String nodePath = resource.getPath();

        // find the type of field
        final Class<?> fieldType = field.getType();
        final String fieldName = ReflectionUtils.getFieldName(field);

        // set accessible
        field.setAccessible(true);

        // handle the value as primitive first
        if (ReflectionUtils.isPrimitiveFieldType(fieldType) || ReflectionUtils.isCollectionOfPrimitiveType(field)) {

            Object value = ReflectionUtils.getStorableValue(field.get(instance));

            // remove the attribute that is null, or remove in case it changes type
            values.remove(fieldName);
            if (value != null) {
                values.put(fieldName, value);
            }
        } else if (deepPersist) {
            boolean directDescendents = field.getAnnotation(DirectDescendants.class) != null;
            persistComplexValue(field.get(instance), directDescendents, fieldName, resource);
        }
    } catch (IllegalAccessException | RepositoryException | PersistenceException ex) {
        LOGGER.error("Error when persisting content to " + resource.getPath(), ex);
    }
}
 
Example 8
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 9
Source File: PageIteratorImpl.java    From jackalope with Apache License 2.0 5 votes vote down vote up
private List<Page> getChildren(Resource resource, Filter<Page> filter, boolean deep) {
    List<Page> pages = new LinkedList<>();
    for (Resource next : Lists.newArrayList(resource.listChildren())) {
        Page page = next.adaptTo(Page.class);
        if (page == null || !filter.includes(page)) continue;
        pages.add(page);
        if (deep) {
            pages.addAll(getChildren(page.adaptTo(Resource.class), filter, true));
        }
    }
    return pages;
}
 
Example 10
Source File: ModelPersistTest.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
@Test
public void testComplexObjectGraph() throws RepositoryException, PersistenceException, IllegalArgumentException, IllegalAccessException {
    // First create a bean with a complex structure and various object types buried in it
    ComplexBean sourceBean = new ComplexBean();
    sourceBean.name = "Complex-bean-test";
    sourceBean.arrayOfStrings = new String[]{"Value 1", "Value 2", "Value 3"};
    sourceBean.listOfStrings = Arrays.asList(sourceBean.arrayOfStrings);
    sourceBean.level2.name = "Complex-bean-level2";
    ComplexBean.Level3Bean l31 = new ComplexBean.Level3Bean();
    l31.value1 = "L3-1";
    l31.value2 = 123;
    l31.valueList = new String[]{"L31a", "L31b", "L31c", "L31d"};
    ComplexBean.Level3Bean l32 = new ComplexBean.Level3Bean();
    l32.value1 = "L3-2";
    l32.value2 = 456;
    l32.valueList = new String[]{"L32a", "L32b", "L32c", "L32d"};
    l32.path = "/test/complex-beans/Complex-bean-test/level2/level3/child-2";
    sourceBean.level2.level3.add(l31);
    sourceBean.level2.level3.add(l32);

    // Persist the bean
    jcrPersist.persist(sourceBean.getPath(), sourceBean, rr);

    // Now retrieve that object from the repository
    rr.refresh();
    Resource createdResource = rr.getResource(sourceBean.getPath());
    ComplexBean targetBean = createdResource.adaptTo(ComplexBean.class);

    assertNotNull(targetBean);
    assertNotEquals(sourceBean, targetBean);
    assertTrue("Expecing children of object to have been deserialized", targetBean.level2.level3 != null && targetBean.level2.level3.size() > 0);
    targetBean.level2.level3.get(0).path = l31.path;
    assertThat(targetBean).isEqualToComparingFieldByFieldRecursively(sourceBean);
}
 
Example 11
Source File: ComponentsConfigurationAdapterFactory.java    From aem-core-cif-components with Apache License 2.0 5 votes vote down vote up
@Override
public <AdapterType> AdapterType getAdapter(Object adaptable, Class<AdapterType> type) {
    if (!(adaptable instanceof Resource)) {
        return null;
    }
    Resource res = serviceResolver.getResource(((Resource) adaptable).getPath());
    ConfigurationBuilder cfgBuilder = res.adaptTo(ConfigurationBuilder.class);
    ComponentsConfiguration configuration = new ComponentsConfiguration(cfgBuilder.name(CONFIGURATION_NAME).asValueMap());
    return (AdapterType) configuration;

}
 
Example 12
Source File: ContentResourceShouldBeNullCheckedCheck.java    From AEM-Rules-for-SonarQube with Apache License 2.0 4 votes vote down vote up
private void directlyCallMethodOnGetContentResourceReturn(Resource resource) {
  Page page = resource.adaptTo(Page.class);
  ValueMap map = page.getContentResource().getValueMap(); // Noncompliant
  ModifiableValueMap modifiableValueMap = page.getContentResource().adaptTo(ModifiableValueMap.class); // Noncompliant
}
 
Example 13
Source File: ModifiableValueMapUsageCheck.java    From AEM-Rules-for-SonarQube with Apache License 2.0 4 votes vote down vote up
public Resource removeProperty(Resource resource) {
    ModifiableValueMap resourcePropertiesToSet = resource.adaptTo(ModifiableValueMap.class);
    removePropertyFromMVM("testName", "testValue", resourcePropertiesToSet);
    return resource;
}
 
Example 14
Source File: SolrBulkUpdateHandler.java    From aem-solr-search with Apache License 2.0 4 votes vote down vote up
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("application/json");
    response.setCharacterEncoding("utf-8");

    JSONArray solrDocs = new JSONArray();

    final String slingResourceType = getSlingResourceType(request);

    if (StringUtils.isEmpty(slingResourceType)) {
        response.getWriter().write(solrDocs.toJSONString());
        return;
    }

    Map<String, String> params = new HashMap<String, String>();
    params.put("path", "/content/geometrixx-media");
    params.put("type", "cq:PageContent");
    params.put("property", "sling:resourceType");
    params.put("property.value", slingResourceType);
    params.put("p.offset", "0");
    params.put("p.limit", "50");

    Session session = null;

    try {
        session = repository.loginAdministrative(null);
        Query query = queryBuilder.createQuery(PredicateGroup.create(params), session);
        SearchResult results = query.getResult();

        LOG.info("Found '{}' matches for query", results.getTotalMatches());

        for (Hit hit: results.getHits()) {

            // The query returns the jcr:content node, so we need its parent.
            Resource page = hit.getResource().getParent();
            GeometrixxMediaContentType contentType = page.adaptTo(GeometrixxMediaPage.class);

            if (contentType != null) {
                solrDocs.add(contentType.getJson());
            }
        }

    } catch (RepositoryException e) {
        LOG.error("Error getting repository", e);
    } finally {
        if (session != null && session.isLive())  {
            session.logout();
        }
    }

    response.getWriter().write(solrDocs.toJSONString());
}
 
Example 15
Source File: MagentoGraphqlClient.java    From aem-core-cif-components with Apache License 2.0 4 votes vote down vote up
private MagentoGraphqlClient(Resource resource, Page page) {

        Resource configurationResource = page != null ? page.adaptTo(Resource.class) : resource;

        LOGGER.debug("Try to get a graphql client from the resource at {}", configurationResource.getPath());

        ComponentsConfiguration configuration = configurationResource.adaptTo(ComponentsConfiguration.class);
        if (configuration.size() == 0) {
            LOGGER.warn("Context configuration not found, attempt to read the configuration from the page");
            graphqlClient = configurationResource.adaptTo(GraphqlClient.class);
        } else {
            LOGGER.debug("Crafting a configuration resource and attempting to get a GraphQL client from it...");
            // The Context-Aware Configuration API does return a ValueMap with all the collected properties from /conf and /libs,
            // but if you ask it for a resource via ConfigurationResourceResolver#getConfigurationResource() you get the resource that
            // resolves first (e.g. /conf/.../settings/cloudonfigs/commerce). This resource might not contain the properties
            // we need to adapt it to a graphql client so we just craft our own resource using the value map provided above.
            Resource configResource = new ValueMapResource(configurationResource.getResourceResolver(),
                configurationResource.getPath(),
                configurationResource.getResourceType(),
                configuration.getValueMap());

            graphqlClient = configResource.adaptTo(GraphqlClient.class);
        }
        if (graphqlClient == null) {
            throw new RuntimeException("GraphQL client not available for resource " + configurationResource.getPath());
        }
        requestOptions = new RequestOptions().withGson(QueryDeserializer.getGson());

        CachingStrategy cachingStrategy = new CachingStrategy()
            .withCacheName(resource.getResourceType())
            .withDataFetchingPolicy(DataFetchingPolicy.CACHE_FIRST);
        requestOptions.withCachingStrategy(cachingStrategy);

        String storeCode;

        if (configuration.size() > 0) {
            storeCode = configuration.get(STORE_CODE_PROPERTY, String.class);
            if (storeCode == null) {
                storeCode = readFallBackConfiguration(configurationResource, STORE_CODE_PROPERTY);
            }
        } else {
            storeCode = readFallBackConfiguration(configurationResource, STORE_CODE_PROPERTY);
        }
        if (StringUtils.isNotEmpty(storeCode)) {
            Header storeHeader = new BasicHeader("Store", storeCode);
            requestOptions.withHeaders(Collections.singletonList(storeHeader));
        }
    }
 
Example 16
Source File: SlingWrappers.java    From sling-samples with Apache License 2.0 4 votes vote down vote up
public static Map<String, Object> resourceWrapper(Resource r) {
    // Add useful Resource properties to the ValueMap
    final Map<String, Object> addProps = new HashMap<>();
    addProps.put(PATH, r.getPath());
    return new ReadOnlyFallbackMap<>(r.adaptTo(ValueMap.class), addProps);
}
 
Example 17
Source File: ModifiableValueMapUsageCheck.java    From AEM-Rules-for-SonarQube with Apache License 2.0 4 votes vote down vote up
public Object getPropertyFromResource(Resource resource) {
    ModifiableValueMap createdResourceProperties = resource.adaptTo(ModifiableValueMap.class); // Noncompliant ValueMap should be used
    return createdResourceProperties.get("propName");
}
 
Example 18
Source File: CIFCategoryFieldHelper.java    From commerce-cif-connector with Apache License 2.0 4 votes vote down vote up
private boolean isVirtual(Resource resource) {
    Node node = resource.adaptTo(Node.class);
    return node == null;
}
 
Example 19
Source File: GraphqlResourceProviderTest.java    From commerce-cif-connector with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void testConfigurableProductResource() throws IOException, CommerceException {
    Utils.setupHttpResponse("magento-graphql-categorylist-empty.json", httpClient, HttpStatus.SC_OK,
        "{categoryList(filters:{url_key:{eq:\"meskwielt\"");
    Utils.setupHttpResponse("magento-graphql-categorylist-coats.json", httpClient, HttpStatus.SC_OK,
        "{categoryList(filters:{url_key:{eq:\"coats\"");
    Utils.setupHttpResponse("magento-graphql-product.json", httpClient, HttpStatus.SC_OK, "{product");
    Utils.setupHttpResponse("magento-graphql-categorylist-empty.json", httpClient, HttpStatus.SC_OK,
        "{categoryList(filters:{url_key:{eq:\"meskwielt-Purple-XS\"");

    Resource resource = provider.getResource(resolveContext, PRODUCT_PATH, null, null);
    assertTrue(resource instanceof ProductResource);
    assertTrue(MagentoProduct.isAProductOrVariant(resource));
    assertEquals(SKU, resource.getValueMap().get("sku", String.class));
    assertTrue(resource.getValueMap().get("hasChildren", Boolean.class));
    Date lastModified = resource.getValueMap().get(JcrConstants.JCR_LASTMODIFIED, Date.class);
    assertTrue(lastModified != null);

    Product product = resource.adaptTo(Product.class);
    assertEquals(product, product.getBaseProduct());
    assertEquals(product, product.getPIMProduct());
    assertEquals(SKU, product.getSKU());
    assertEquals(NAME, product.getTitle());
    assertEquals(DESCRIPTION, product.getDescription());
    assertEquals(IMAGE_URL, product.getImageUrl());
    assertEquals(IMAGE_URL, product.getThumbnailUrl());
    assertEquals(IMAGE_URL, product.getThumbnailUrl(123));
    assertEquals(IMAGE_URL, product.getThumbnailUrl("selector"));
    assertNull(product.getThumbnail());
    assertEquals(URL_KEY, product.getProperty("urlKey", String.class));
    assertNull(product.getProperty("whatever", String.class));

    assertEquals(IMAGE_URL, product.getAsset().getPath());
    assertEquals(IMAGE_URL, product.getAssets().get(0).getPath());

    assertEquals(PRODUCT_PATH + "/image", product.getImage().getPath());
    assertEquals(PRODUCT_PATH + "/image", product.getImages().get(0).getPath());
    assertNull(product.getImagePath());

    // We do not extract variant axes
    assertFalse(product.getVariantAxes().hasNext());
    assertFalse(product.axisIsVariant("whatever"));

    // Test master variant when fetched via Product API
    Product masterVariant = product.getVariants().next();
    assertMasterVariant(masterVariant);

    Iterator<Resource> it = provider.listChildren(resolveContext, resource);

    // First child is the image
    Resource imageResource = it.next();
    assertEquals(PRODUCT_PATH + "/image", imageResource.getPath());
    assertEquals(IMAGE_URL, imageResource.getValueMap().get(DownloadResource.PN_REFERENCE, String.class));

    // Test master variant when fetched via Resource API
    Resource firstVariant = it.next();
    assertEquals(MASTER_VARIANT_SKU, firstVariant.getValueMap().get("sku", String.class));

    // Test deep read firstVariantName/sku
    assertEquals(MASTER_VARIANT_SKU, resource.getValueMap().get(firstVariant.getName() + "/sku", String.class));
}
 
Example 20
Source File: PageImpl.java    From jackalope with Apache License 2.0 4 votes vote down vote up
@Override
public ValueMap getProperties() {
    Resource contentResource = getContentResource();
    return contentResource != null ? contentResource.adaptTo(ValueMap.class) : null;
}