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

The following examples show how to use org.apache.sling.api.resource.Resource#getPath() . 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: GeometrixxMediaArticleBody.java    From aem-solr-search with Apache License 2.0 6 votes vote down vote up
public GeometrixxMediaArticleBody(Resource resource) throws SlingModelsException {

        if (null == resource) {
            LOG.info("Resource is null");
            throw new SlingModelsException("Resource is null");
        }

        if (ResourceUtil.isNonExistingResource(resource)) {
            LOG.warn("Can't adapt non existent resource: '{}'", resource.getPath());
            throw new SlingModelsException(
                "Can't adapt non existent resource." + resource.getPath());
        }

        this.resource = resource;

    }
 
Example 2
Source File: GeometrixxMediaPage.java    From aem-solr-search with Apache License 2.0 5 votes vote down vote up
public GeometrixxMediaPage(Resource resource) throws SlingModelsException {

        if (null == resource) {
            LOG.debug("resource is null");
            throw new SlingModelsException("Resource is null");
        }

        if (ResourceUtil.isNonExistingResource(resource)) {
            LOG.warn("Can't adapt non existent resource: '{}'", resource.getPath());
            throw new SlingModelsException(
                "Can't adapt non existent resource." + resource.getPath());
        }

    }
 
Example 3
Source File: ResourceMapper.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
Iterator<Resource> listCategoryChildren(ResourceResolver resolver, Resource parent) {
    String parentPath = parent.getPath();
    String parentCifId = parent.getValueMap().get(Constants.CIF_ID, String.class);
    boolean isRoot = parentPath.equals(root);
    String subPath = isRoot ? "" : parentPath.substring(root.length() + 1);
    List<Resource> children = new ArrayList<>();
    CategoryTree categoryTree;
    try {
        if (StringUtils.isNotBlank(subPath)) {
            categoryTree = graphqlDataService.getCategoryByPath(subPath, storeView);
        } else {
            categoryTree = graphqlDataService.getCategoryById(rootCategoryId, storeView);
        }
    } catch (Exception x) {
        List<Resource> list = new ArrayList<>();
        list.add(new ErrorResource(resolver, parent.getPath()));
        return list.iterator();
    }
    if (categoryTree != null) {
        List<CategoryTree> subChildren = categoryTree.getChildren();
        if (subChildren != null) {
            for (CategoryTree child : subChildren) {
                children.add(new CategoryResource(resolver, root + "/" + child.getUrlPath(), child));
            }
        }
    }

    if (children.isEmpty() && StringUtils.isNotBlank(parentCifId)) {
        try {
            return new CategoryProductsIterator(parent, graphqlDataService, 20, storeView);
        } catch (Exception e) {
            LOGGER.error("Error while fetching category products for " + parentPath + " (" + parentCifId + ")", e);
        }
    }

    return children.isEmpty() ? null : children.iterator();
}
 
Example 4
Source File: PageManagerImpl.java    From jackalope with Apache License 2.0 5 votes vote down vote up
@Override
public Page getContainingPage(Resource resource) {
    if (resource == null) return null;

    String path = resource.getPath();
    while (!Paths.isRoot(path)) {
        Page page = getPage(path);
        if (page != null) return page;
        path = path.substring(0, path.lastIndexOf("/"));
    }

    return null;
}
 
Example 5
Source File: MessageStoreImpl.java    From sling-samples with Apache License 2.0 5 votes vote down vote up
private boolean assertResource(ResourceResolver resolver, Resource parent, String name, Map<String, Object> newProps) 
        throws LoginException, PersistenceException {
    String checkPath = parent.getPath()+"/"+name;
    final Resource checkResource = resolver.getResource(checkPath);
    if (checkResource == null) {
        final Resource newResource = resolver.create(parent, name, newProps);
        resolver.commit();
        logger.debug(String.format("Resource created at %s .", newResource.getPath()));
        return true;
    } else {
        logger.debug(String.format("Resource at %s already exists.", checkResource.getPath()));
        return false;
    }
}
 
Example 6
Source File: SlingshotUtil.java    From sling-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Get the user content path for the resource
 * @param resource The resource
 * @return The user content path or {@code null}.
 */
public static String getContentPath(final Resource resource) {
    final String prefix = SlingshotConstants.APP_ROOT_PATH + "/users/" + getUserId(resource) + "/";

    final String path = resource.getPath();
    if ( path != null && path.startsWith(prefix) ) {
        return path.substring(prefix.length() - 1);
    }
    return null;
}
 
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: ResourceResolverImpl.java    From jackalope with Apache License 2.0 5 votes vote down vote up
@Override
public Resource create(@Nonnull Resource parent, @Nonnull String name, @Nullable Map<String, Object> properties) throws PersistenceException {
    //noinspection ConstantConditions
    if (parent == null)
        throw new IllegalArgumentException("Could not create a node for \"" + name + "\" because the parent is null");
    String parentPath = parent.getPath();

    // remove any trailing slash (or sole-slash if the root)
    if (parentPath.endsWith("/")) parentPath = parentPath.substring(0, parentPath.length() - 1);
    String path = parentPath + "/" + name;

    return createNodeResource(path, properties != null ? properties : Collections.<String, Object>emptyMap());
}
 
Example 9
Source File: ResourceResolverImpl.java    From jackalope with Apache License 2.0 5 votes vote down vote up
@Override
public void delete(Resource resource) throws PersistenceException {
    try {
        session.removeItem(resource.getPath());
    }
    catch (RepositoryException e) {
        throw new PersistenceException("Could not delete " + resource.getPath(), e);
    }
}
 
Example 10
Source File: LongSessionService.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
public String getPath(final HttpServletRequest request) {
    String path = request.getParameter("resource");
    final Resource mappedResource = resolver.resolve(request, path);
    if (!ResourceUtil.isNonExistingResource(mappedResource)) {
        path = mappedResource.getPath();
    }
    return path;
}
 
Example 11
Source File: ComplexBean.java    From sling-whiteboard with Apache License 2.0 4 votes vote down vote up
public Level3Bean(Resource resource) {
    if (resource != null) {
        path = resource.getPath();
    }
}
 
Example 12
Source File: HistoryEntryImpl.java    From APM with Apache License 2.0 4 votes vote down vote up
public HistoryEntryImpl(Resource resource) {
  this.path = resource.getPath();
}
 
Example 13
Source File: ScriptModel.java    From APM with Apache License 2.0 4 votes vote down vote up
public ScriptModel(Resource resource) {
  this.path = resource.getPath();
}
 
Example 14
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 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: ResourceMapper.java    From commerce-cif-connector with Apache License 2.0 4 votes vote down vote up
Iterator<Resource> listProductChildren(ResourceResolver resolver, Resource parent) {
    String sku = parent.getValueMap().get(Constants.SKU, String.class);
    String parentPath = parent.getPath();

    try {
        ProductInterface productInterface = graphqlDataService.getProductBySku(sku, storeView);
        if (productInterface == null) {
            return null;
        }

        String imageUrl = null;
        if (productInterface.getImage() != null) {
            imageUrl = productInterface.getImage().getUrl();
        }
        List<Resource> children = new ArrayList<>();

        if (productInterface instanceof ConfigurableProduct) {
            ConfigurableProduct product = (ConfigurableProduct) productInterface;
            List<ConfigurableVariant> variants = product.getVariants();
            if (variants != null && !variants.isEmpty()) {
                for (ConfigurableVariant variant : variants) {
                    SimpleProduct simpleProduct = variant.getProduct();
                    String path = parentPath + "/" + simpleProduct.getSku();
                    children.add(new ProductResource(resolver, path, simpleProduct, simpleProduct.getSku()));

                    if (imageUrl == null && simpleProduct.getImage() != null) {
                        imageUrl = simpleProduct.getImage().getUrl();
                    }
                }
            }
        }

        if (imageUrl != null) {
            String imagePath = parentPath + "/image";
            Resource imageResource = new SyntheticImageResource(resolver, imagePath, SyntheticImageResource.IMAGE_RESOURCE_TYPE,
                imageUrl);
            children.add(0, imageResource);
        }

        return children.iterator();
    } catch (Exception e) {
        LOGGER.error("Error while fetching variants for product " + sku, e);
        return null;
    }
}
 
Example 17
Source File: GraphqlResourceProviderFactory.java    From commerce-cif-connector with Apache License 2.0 4 votes vote down vote up
@Override
public GraphqlResourceProvider createResourceProvider(Resource root) {
    LOGGER.debug("Creating resource provider for resource at path {}", root.getPath());

    ConfigurationBuilder configurationBuilder = root.adaptTo(ConfigurationBuilder.class);
    ValueMap properties = configurationBuilder.name(CONFIGURATION_NAME)
        .asValueMap();

    Map<String, String> collectedProperties = new HashMap<>();
    if (properties.size() == 0) {
        collectedProperties = readFallbackConfiguration(root);
    } else {
        for (String key : properties.keySet()) {
            collectedProperties.put(key, properties.get(key, ""));
        }
    }

    String catalogIdentifier = collectedProperties.get(GraphqlDataServiceConfiguration.CQ_CATALOG_IDENTIFIER);
    if (StringUtils.isEmpty(catalogIdentifier)) {
        LOGGER.warn("Could not find cq:catalogIdentifier property for given resource at " + root.getPath());
        return null;
    }

    // Check Magento root category id
    String rootCategoryId = collectedProperties.get(Constants.MAGENTO_ROOT_CATEGORY_ID_PROPERTY);
    try {
        Integer.valueOf(rootCategoryId);
    } catch (NumberFormatException x) {
        LOGGER.warn("Invalid {} {} at {}", Constants.MAGENTO_ROOT_CATEGORY_ID_PROPERTY, rootCategoryId, root.getPath());
        return null;
    }

    GraphqlDataService client = clients.get(catalogIdentifier);
    if (client == null) {
        LOGGER.warn("No MagentoGraphqlClient instance available for catalog identifier " + catalogIdentifier);
        return null;
    }

    GraphqlResourceProvider resourceProvider = new GraphqlResourceProvider(root.getPath(), client, collectedProperties);
    return resourceProvider;
}