org.apache.sling.api.resource.ResourceUtil Java Examples

The following examples show how to use org.apache.sling.api.resource.ResourceUtil. 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: SyntheticResourceFilter.java    From sling-org-apache-sling-dynamic-include with Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
        ServletException {
    final SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) request;
    final String resourceType = getResourceTypeFromSuffix(slingRequest);
    final Configuration config = configurationWhiteboard.getConfiguration(slingRequest, resourceType);

    if (config == null || !config.hasIncludeSelector(slingRequest)
            || !ResourceUtil.isSyntheticResource(slingRequest.getResource())
            || (config.hasExtensionSet() && !config.hasExtension(slingRequest))) {
        chain.doFilter(request, response);
        return;
    }

    final RequestDispatcherOptions options = new RequestDispatcherOptions();
    options.setForceResourceType(resourceType);
    String resourcePath = StringUtils.substringBefore(slingRequest.getRequestPathInfo().getResourcePath(), ".");
    Resource resource = slingRequest.getResourceResolver().resolve(resourcePath);
    final RequestDispatcher dispatcher = slingRequest.getRequestDispatcher(resource, options);
    dispatcher.forward(request, response);
}
 
Example #2
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 #3
Source File: RatingsServiceImpl.java    From sling-samples with Apache License 2.0 6 votes vote down vote up
/**
 * @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 double 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, String.valueOf(rating));

        resource.getResourceResolver().create(ratingsResource, userId, props);
    } else {
        final ModifiableValueMap mvm = ratingRsrc.adaptTo(ModifiableValueMap.class);
        mvm.put(RatingsUtil.PROPERTY_RATING, String.valueOf(rating));
    }
    resource.getResourceResolver().commit();
}
 
Example #4
Source File: ShallowReferenceTree.java    From sling-whiteboard with Apache License 2.0 6 votes vote down vote up
public boolean add(@NotNull ShallowReference reference) {
    if (references.containsValue(reference)) {
        return false;
    }
    String parentPath = ResourceUtil.getParent(reference.getPath());
    ShallowReference current = reference;
    while (parentPath != null) {
        String pPath = parentPath;
        ShallowReference parent = references.computeIfAbsent(parentPath, s -> new ShallowReference(pPath));
        references.put(current.getPath(), current);
        nodeParent.put(current, parent);
        current = parent;
        parentPath = ResourceUtil.getParent(parentPath);
    }
    return true;
}
 
Example #5
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 #6
Source File: ExampleOsgiHook.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
public void execute(InstallContext ctx) throws PackageException {
    String name = ResourceUtil.getName("/foo/test");
    log.info("Executing Hook in phase {}. Testing Resource Util: {}", ctx.getPhase(), name);
    if (ctx.getOptions().getListener() != null) {
        ctx.getOptions().getListener().onMessage(ProgressTrackerListener.Mode.TEXT, "H", "OSGi Hook Test - " + name);
    }
    if (ctx.getPhase() == InstallContext.Phase.INSTALLED) {
        try {
            ctx.getSession().getNode("/testroot").setProperty("TestHook", ctx.getPhase().toString());
            ctx.getSession().save();
        } catch (RepositoryException e) {
            throw new PackageException(e);
        }
    }
}
 
Example #7
Source File: LongSessionService.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
public String toRawPath(final String path) {
    String result = "";
    if (resolver != null) {
        final Resource loginPageResource = resolver.resolve(path);
        if (!ResourceUtil.isNonExistingResource(loginPageResource)) {
            result = resolver.map(loginPageResource.getPath());
        }
    }
    return result;
}
 
Example #8
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 #9
Source File: LongSessionService.java    From AEM-Rules-for-SonarQube with Apache License 2.0 5 votes vote down vote up
public String getLoginPage(final HttpServletRequest request) {
    final String loginPage = request.getParameter("loignPage");
    if (loginPage != null) {
        if (ResourceUtil.isNonExistingResource(resolver.resolve(loginPage))) {
            System.out.println("Login page " + loginPage);
        }
    }
    return loginPage;
}
 
Example #10
Source File: RemoteResourceProvider.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
RemoteResourceProvider(ThreadPoolManager threadPoolManager, ContentParser jsonParser, InMemoryResourceCache cache,
                       RemoteStorageProvider remoteStorageProvider,
                       boolean requiresAuthentication) {
    this.threadPoolManager = threadPoolManager;
    this.threadPool = threadPoolManager.get(remoteStorageProvider.getClass().getName() + "-" + System.currentTimeMillis());
    this.jsonParser = jsonParser;
    this.cache = cache;
    negativeHits = new ConcurrentHashMap<>();
    tree = new ShallowReferenceTree(removed -> {
        for (String resourceRemoved : removed.getProvidedResourcePaths()) {
            this.cache.remove(resourceRemoved);
            if (!requiresAuthentication) {
                this.cache.remove(ResourceUtil.getParent(resourceRemoved));
            }
        }
        String slingPath = remoteStorageProvider.slingPath(removed.getPath());
        int lastSlash = slingPath.lastIndexOf('/');
        if (lastSlash > 0) {
            String fileName = slingPath.substring(lastSlash + 1);
            if (SLING_META_FILE.equals(fileName)) {
                slingPath = ResourceUtil.getParent(slingPath);
            }
        }
        for (String negativeHit : negativeHits.keySet()) {
            if (negativeHit.startsWith(slingPath + "/")) {
                negativeHits.remove(negativeHit);
            }
        }
    });
    this.remoteStorageProvider = remoteStorageProvider;
    this.remoteStorageProvider.registerEventHandler(this);
    this.requiresAuthentication = requiresAuthentication;
    accessMappings = new ConcurrentHashMap<>();

}
 
Example #11
Source File: DropboxStorageProvider.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
@Override
public String storagePath(@NotNull String slingPath) {
    if (slingMountPoint.matches(slingPath)) {
        return ResourceUtil.normalize(dropboxRootPath.concat(slingPath.substring(slingMountPoint.getPath().length())));
    }
    return null;
}
 
Example #12
Source File: DropboxStorageProvider.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
@Override
public String slingPath(@NotNull String storagePath) {
    if (dropboxRootPath.equals(storagePath) ||
            storagePath.startsWith(dropboxRootPath.endsWith("/") ? dropboxRootPath : dropboxRootPath + "/")) {
        return ResourceUtil.normalize(slingMountPoint.getPath() + "/" + storagePath.substring(dropboxRootPath.length()));
    }
    return null;
}
 
Example #13
Source File: List.java    From sling-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the children.
 * 
 * <p>Get the children, convert them to a Java List, reverse them, 
 * and adapt the collection to a Post model</p>
 * 
 * @return the children
 */
@SuppressWarnings("unchecked")
public Iterator<Post> getChildren() {
    if(this.resource != null) {
        java.util.List<Resource> childrenList = IteratorUtils.toList(this.resource.getChildren().iterator());
        Iterator<Resource> reverseChildren = new ReverseListIterator(childrenList);
        return ResourceUtil.adaptTo(reverseChildren, Post.class);
    } else {
        return null;
    }
}
 
Example #14
Source File: PropertiesSupport.java    From sling-samples with Apache License 2.0 5 votes vote down vote up
protected ValueMap getProperties() {
    if ( this.properties == null ) {
        if ( this.resource == null ) {
            this.properties = ResourceUtil.getValueMap(null);
        } else {
            this.properties = resource.getValueMap();
        }
    }
    return this.properties;
}
 
Example #15
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 #16
Source File: ModelPersistorImpl.java    From sling-whiteboard with Apache License 2.0 4 votes vote down vote up
@Override
public void persist(final @NotNull String nodePath, final @NotNull Object instance,
        @NotNull ResourceResolver resourceResolver, boolean deepPersist)
        throws RepositoryException, PersistenceException, IllegalArgumentException, IllegalAccessException {
    if (StringUtils.isBlank(nodePath)) {
        throw new IllegalArgumentException("Node path cannot be null/empty");
    }

    if (instance == null) {
        throw new IllegalArgumentException("Object to save cannot be null");
    }

    if (resourceResolver == null) {
        throw new IllegalArgumentException("ResourceResolver cannot be null");
    }

    Resource resource;
    final ResourceTypeKey resourceType = ResourceTypeKey.fromObject(instance);

    // let's create the resource first
    LOGGER.debug("Creating node at: {} of type: {}", nodePath, resourceType.primaryType);
    boolean isUpdate = resourceResolver.getResource(nodePath) != null;
    resource = ResourceUtil.getOrCreateResource(resourceResolver, nodePath, resourceType.primaryType, NT_UNSTRUCTURED, true);
    if (StringUtils.isNotEmpty(resourceType.childType)) {
        LOGGER.debug("Needs a child node, creating node at: {} of type: {}", nodePath, resourceType.childType);
        resource = ResourceUtil.getOrCreateResource(resourceResolver, nodePath + "/" + JCR_CONTENT, resourceType.childType, NT_UNSTRUCTURED, true);
    }

    if (ReflectionUtils.isArrayOrCollection(instance)) {
        persistComplexValue(instance, true, "dunno", resource);
    } else {
        // find properties to be saved
        List<Field> fields = ReflectionUtils.getAllFields(instance.getClass());
        if (fields == null || fields.isEmpty()) {
            // TODO: remove all properties
        } else {
            Resource r = resource;
            fields.stream()
                    .filter(field -> ReflectionUtils.isNotTransient(field, isUpdate))
                    .filter(field -> ReflectionUtils.isSupportedType(field) || ReflectionUtils.isCollectionOfPrimitiveType(field))
                    .filter(f -> ReflectionUtils.hasNoTransientGetter(f.getName(), instance.getClass()))
                    .forEach(field -> persistField(r, instance, field, deepPersist));
        }
    }

    // save back
    resourceResolver.commit();
}
 
Example #17
Source File: CommentsServiceImpl.java    From sling-samples with Apache License 2.0 4 votes vote down vote up
/**
 * @see org.apache.sling.sample.slingshot.comments.CommentsService#addComment(org.apache.sling.api.resource.Resource, org.apache.sling.sample.slingshot.comments.Comment)
 */
@Override
public void addComment(final Resource resource, final Comment c)
throws PersistenceException {
    final String commentsPath = this.getCommentsResourcePath(resource);
    final Map<String, Object> props = new HashMap<String, Object>();
    props.put(ResourceResolver.PROPERTY_RESOURCE_TYPE, RESOURCETYPE_COMMENTS);
    final Resource ratingsResource = ResourceUtil.getOrCreateResource(resource.getResourceResolver(),
            commentsPath, props, null, true);

    final Map<String, Object> properties = new HashMap<String, Object>();
    properties.put(ResourceResolver.PROPERTY_RESOURCE_TYPE, CommentsUtil.RESOURCETYPE_COMMENT);
    properties.put(CommentsUtil.PROPERTY_TITLE, c.getTitle());
    properties.put(CommentsUtil.PROPERTY_TEXT, c.getText());
    properties.put(CommentsUtil.PROPERTY_USER, c.getCreatedBy());

    // we try it five times
    PersistenceException exception = null;
    Resource newResource = null;
    for(int i=0; i<5; i++) {
        try {
            exception = null;
            final String name = ResourceUtil.createUniqueChildName(ratingsResource, Util.filter(c.getTitle()));
            newResource = resource.getResourceResolver().create(ratingsResource, name, properties);

            resource.getResourceResolver().commit();
            break;
        } catch ( final PersistenceException pe) {
            resource.getResourceResolver().revert();
            resource.getResourceResolver().refresh();
            exception = pe;
        }
    }
    if ( exception != null ) {
        throw exception;
    }
    // order node at the top (if jcr based)
    final Node newNode = newResource.adaptTo(Node.class);
    if ( newNode != null ) {
        try {
            final Node parent = newNode.getParent();
            final Node firstNode = parent.getNodes().nextNode();
            if ( !firstNode.getName().equals(newNode.getName()) ) {
                parent.orderBefore(newNode.getName(), firstNode.getName());
                newNode.getSession().save();
            }
        } catch ( final RepositoryException re) {
            logger.error("Unable to order comment to the top", re);
        }
    }
}
 
Example #18
Source File: RenditionImpl.java    From jackalope with Apache License 2.0 4 votes vote down vote up
@Override
public ValueMap getProperties() {
    return ResourceUtil.getValueMap(this.getChild("jcr:content"));
}
 
Example #19
Source File: IncludeTagFilter.java    From sling-org-apache-sling-dynamic-include with Apache License 2.0 4 votes vote down vote up
private String buildUrl(Configuration config, SlingHttpServletRequest request) {
    final Resource resource = request.getResource();

    final boolean synthetic = ResourceUtil.isSyntheticResource(request.getResource());
    return UrlBuilder.buildUrl(config.getIncludeSelector(), resource.getResourceType(), synthetic, config, request.getRequestPathInfo());
}
 
Example #20
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);
    }

}