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

The following examples show how to use org.apache.sling.api.resource.Resource#getResourceResolver() . 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: AEMDataLayerInterceptorFilter.java    From AEM-DataLayer with Apache License 2.0 6 votes vote down vote up
boolean resourceHierarchyHasACycle(Resource resource) {
	String resourceType = resource.getResourceType();
	Set<String> resourceTypeSet = new HashSet<>();

	ResourceResolver resolver = resource.getResourceResolver();

	while (resourceType != null) {
		if (resourceTypeSet.contains(resourceType)) {
			log.trace("Found a cycle in the resource type hierarchy for {}", resourceType);
			return true;
		}

		resourceTypeSet.add(resourceType);
		resourceType = resolver.getParentResourceType(resource.getResourceType());
	}

	return false;
}
 
Example 2
Source File: CommentServiceImpl.java    From publick-sling-blog with Apache License 2.0 6 votes vote down vote up
/**
 * Get the blog post associated with the given comment.
 *
 * There are only two levels of comments. You can reply to a post
 * and you can reply to a top level comment.
 *
 * @param comment The current comment
 * @return the number of replies to the given comment
 */
public Resource getParentPost(final Resource comment) {
    final ResourceResolver resolver = comment.getResourceResolver();
    Resource parent = comment.getParent();

    // Try one level up
    Resource post = resolver.getResource(parent.getPath().replace("/comments/", "/blog/"));

    if (post == null) {
        //try two levels up
        parent = parent.getParent();
        post = resolver.getResource(parent.getPath().replace("/comments/", "/blog/"));
    }

    return post;
}
 
Example 3
Source File: AdapterImplementations.java    From sling-org-apache-sling-models-impl with Apache License 2.0 5 votes vote down vote up
protected static Class<?> getModelClassForResource(final Resource resource, final Map<String, Class<?>> map) {
    if (resource == null) {
        return null;
    }
    ResourceResolver resolver = resource.getResourceResolver();
    final String originalResourceType = resource.getResourceType();
    Class<?> modelClass = getClassFromResourceTypeMap(originalResourceType, map, resolver);
    if (modelClass != null) {
        return modelClass;
    } else {
        String resourceType = resolver.getParentResourceType(resource);
        while (resourceType != null) {
            modelClass = getClassFromResourceTypeMap(resourceType, map, resolver);
            if (modelClass != null) {
                return modelClass;
            } else {
                resourceType = resolver.getParentResourceType(resourceType);
            }
        }
        Resource resourceTypeResource = resolver.getResource(originalResourceType);
        if (resourceTypeResource != null && !resourceTypeResource.getPath().equals(resource.getPath())) {
            return getModelClassForResource(resourceTypeResource, map);
        } else {
            return null;
        }
    }
}
 
Example 4
Source File: ModelPersistorImpl.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
private void persistComplexValue(Object obj, Boolean implicitCollection, final String fieldName, Resource resource) throws RepositoryException, IllegalAccessException, IllegalArgumentException, PersistenceException {
    ResourceResolver rr = resource.getResourceResolver();
    String childrenRoot = buildChildrenRoot(resource.getPath(), fieldName, rr, implicitCollection);
    boolean deleteRoot = true;
    if (obj != null) {
        if (Collection.class.isAssignableFrom(obj.getClass())) {
            Collection collection = (Collection) obj;
            if (!collection.isEmpty()) {
                persistCollection(childrenRoot, collection, rr);
                deleteRoot = false;
            }
        } else if (Map.class.isAssignableFrom(obj.getClass())) {
            Map map = (Map) obj;
            if (!map.isEmpty()) {
                persistMap(childrenRoot, map, rr);
                deleteRoot = false;
            }
        } else {
            // this is a single compound object
            // create a child node and persist all its values
            persist(resource.getPath() + "/" + fieldName, obj, rr, true);
            deleteRoot = false;
        }
        if (deleteRoot) {
            Resource rootNode = rr.getResource(childrenRoot);
            if (rootNode != null) {
                rr.delete(rootNode);
            }
        }
    }
}
 
Example 5
Source File: MultiFieldDropTargetPostProcessor.java    From commerce-cif-connector with Apache License 2.0 4 votes vote down vote up
private void processProperty(Resource resource, String target, String propertyValue, String originalKey, String selectionType,
    boolean multiple) throws Exception {

    String[] paths = target.split(SLASH);

    ResourceResolver resourceResolver = resource.getResourceResolver();

    // clean-up the dropTarget property or node
    ModifiableValueMap originalProperties = resource.adaptTo(ModifiableValueMap.class);
    originalProperties.remove(originalKey);

    String dropTargetNodeName = DROP_TARGET_PREFIX.replace(SLING_PROPERTY_PREFIX, StringUtils.EMPTY);
    Resource dropTargetResource = resource.getChild(dropTargetNodeName);
    if (dropTargetResource != null) {
        resourceResolver.delete(dropTargetResource);
    }

    if (selectionType != null) {
        if (SKU.equals(selectionType)) {
            propertyValue = StringUtils.substringAfterLast(propertyValue, "/");
        } else if (SLUG.equals(selectionType)) {
            Resource product = resourceResolver.getResource(propertyValue);
            if (product != null) {
                String slug = product.getValueMap().get(SLUG, String.class);
                if (slug != null) {
                    propertyValue = slug;
                }
            }
        }
    }

    // check all paths and create correct resources and properties
    boolean isArray = true;
    Resource currentResource = resource;
    for (String path : paths) {
        if (path.startsWith(PROPERTY_PREFIX)) {
            // this is the property
            String propertyName = path.replace(PROPERTY_PREFIX, StringUtils.EMPTY);
            ModifiableValueMap properties = currentResource.adaptTo(ModifiableValueMap.class);
            if (isArray && multiple) {
                List<String> childPages = new ArrayList<>(Arrays.asList(properties.get(propertyName, new String[0])));
                childPages.add(propertyValue);
                properties.remove(propertyName);
                properties.put(propertyName, childPages.toArray());
            } else {
                properties.put(propertyName, propertyValue);
            }
            // These properties are added by the drag and drop, they do not belong to the component configuration
            properties.remove(MULTIPLE.replace(PROPERTY_PREFIX, StringUtils.EMPTY));
            properties.remove(SELECTION_ID.replace(PROPERTY_PREFIX, StringUtils.EMPTY));
        } else if (path.equals(COMPOSITE_VARIABLE)) {
            // create new subNode
            int count = Iterators.size(currentResource.getChildren().iterator());
            String nodeName = "item" + count;
            currentResource = resourceResolver.create(currentResource, nodeName, new HashMap<>());
            isArray = false;
        } else if (StringUtils.isNotBlank(path)) {
            // get or create new node
            Resource subResource = currentResource.getChild(path);
            if (subResource == null) {
                currentResource = resourceResolver.create(currentResource, path, new HashMap<>());
            } else {
                currentResource = subResource;
            }
        }
    }
}
 
Example 6
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 7
Source File: SlingObjectInjector.java    From sling-org-apache-sling-models-impl with Apache License 2.0 4 votes vote down vote up
@Override
public Object getValue(final @NotNull Object adaptable, final String name, final @NotNull Type type, final @NotNull AnnotatedElement element,
        final @NotNull DisposalCallbackRegistry callbackRegistry) {

    // only class types are supported
    if (!(type instanceof Class<?>)) {
        return null;
    }
    Class<?> requestedClass = (Class<?>) type;

    // validate input
    if (adaptable instanceof SlingHttpServletRequest) {
        SlingHttpServletRequest request = (SlingHttpServletRequest) adaptable;
        if (requestedClass.equals(ResourceResolver.class)) {
            return request.getResourceResolver();
        }
        if (requestedClass.equals(Resource.class) && element.isAnnotationPresent(SlingObject.class)) {
            return request.getResource();
        }
        if (requestedClass.equals(SlingHttpServletRequest.class) || requestedClass.equals(HttpServletRequest.class)) {
            return request;
        }
        if (requestedClass.equals(SlingHttpServletResponse.class)
                || requestedClass.equals(HttpServletResponse.class)) {
            return getSlingHttpServletResponse(request);
        }
        if (requestedClass.equals(SlingScriptHelper.class)) {
            return getSlingScriptHelper(request);
        }
    } else if (adaptable instanceof ResourceResolver) {
        ResourceResolver resourceResolver = (ResourceResolver) adaptable;
        if (requestedClass.equals(ResourceResolver.class)) {
            return resourceResolver;
        }
    } else if (adaptable instanceof Resource) {
        Resource resource = (Resource) adaptable;
        if (requestedClass.equals(ResourceResolver.class)) {
            return resource.getResourceResolver();
        }
        if (requestedClass.equals(Resource.class) && element.isAnnotationPresent(SlingObject.class)) {
            return resource;
        }
    }

    return null;
}
 
Example 8
Source File: RenditionImpl.java    From jackalope with Apache License 2.0 4 votes vote down vote up
public RenditionImpl(Asset asset, Resource resource) {
    super(resource.getResourceResolver(), resource.adaptTo(Node.class));
    this.asset = asset;
}