Java Code Examples for org.apache.sling.api.resource.ResourceResolver#getResource()
The following examples show how to use
org.apache.sling.api.resource.ResourceResolver#getResource() .
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: CommentServiceImpl.java From publick-sling-blog with Apache License 2.0 | 6 votes |
/** * Mark comment as spam, submit it to Akismet and delete it by setting * it's display property to false. * * @param request The current request to get session and Resource Resolver * @param id The comment UUID * @return true if the operation was successful */ public boolean markAsSpam(final SlingHttpServletRequest request, final String id) { boolean result = false; try { final ResourceResolver resolver = request.getResourceResolver(); final Session session = resolver.adaptTo(Session.class); final Node node = session.getNodeByIdentifier(id); if (node != null) { final Resource resource = resolver.getResource(node.getPath()); result = akismetService.submitSpam(resource); } } catch (RepositoryException e) { LOGGER.error("Could not submit spam.", e); } return result; }
Example 2
Source File: ScriptFinderImpl.java From APM with Apache License 2.0 | 6 votes |
@Override public Script find(String scriptPath, ResourceResolver resolver) { Script result = null; if (StringUtils.isNotEmpty(scriptPath)) { Resource resource; if (isAbsolute(scriptPath)) { resource = resolver.getResource(scriptPath); } else { resource = resolver.getResource(SCRIPT_PATH + "/" + scriptPath); } if (resource != null && ScriptModel.isScript(resource)) { result = resource.adaptTo(ScriptModel.class); } } return result; }
Example 3
Source File: BlogEdit.java From publick-sling-blog with Apache License 2.0 | 6 votes |
/** * Get the blog post properties if resource already exists otherwise * set the month and year properties to the current date. * * @param path The resource path to the blog post. */ private void getBlog(String path) { ResourceResolver resolver = resource.getResourceResolver(); Resource blog = resolver.getResource(path); if (blog != null) { ValueMap properties = blog.adaptTo(ValueMap.class); title = properties.get("title", String.class); month = properties.get("month", Long.class); year = properties.get("year", Long.class); url = properties.get("url", String.class); visible = Boolean.valueOf(properties.get("visible", false)); keywords = properties.get("keywords", String[].class); image = properties.get("image", String.class); content = properties.get("content", String.class); description = properties.get("description", String.class); url = blog.getName(); } else { /* Populate dropdowns with current date if creating new blog. */ month = ((long)Calendar.getInstance().get(Calendar.MONTH)) + 1; year = (long)Calendar.getInstance().get(Calendar.YEAR); } }
Example 4
Source File: ModelPersistorImpl.java From sling-whiteboard with Apache License 2.0 | 6 votes |
private static void deleteOrphanNodes(ResourceResolver resourceResolver, final String collectionRoot, Set<String> childNodes) { // Delete any children that are not in the list Resource collectionParent = resourceResolver.getResource(collectionRoot); if (collectionParent != null) { StreamSupport .stream(resourceResolver.getChildren(collectionParent).spliterator(), false) .filter(r -> !childNodes.contains(r.getPath())) .forEach(r -> { try { resourceResolver.delete(r); } catch (PersistenceException ex) { LOGGER.error("Unable to remove stale resource at " + r.getPath(), ex); } }); } }
Example 5
Source File: CommentServiceImpl.java From publick-sling-blog with Apache License 2.0 | 6 votes |
/** * 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 6
Source File: Edit.java From sling-samples with Apache License 2.0 | 5 votes |
/** * Instantiates a new Edit model. * * @param request the request */ public Edit(SlingHttpServletRequest request) { ResourceResolver resourceResolver = request.getResourceResolver(); try { String path = request.getParameter("post"); if (path != null) { Resource resource = resourceResolver.getResource(path); this.post = resource.adaptTo(Post.class); } LOGGER.info("Creating new post."); } catch (Exception e) { LOGGER.info("Couldn't get the post to edit.", e); } }
Example 7
Source File: HistoryImpl.java From APM with Apache License 2.0 | 5 votes |
@NotNull private Resource writeProperties(ResourceResolver resolver, Node historyEntry, HistoryEntryWriter historyEntryWriter) throws RepositoryException { Resource entryResource = resolver.getResource(historyEntry.getPath()); historyEntryWriter.writeTo(entryResource); return entryResource; }
Example 8
Source File: HistoryImpl.java From APM with Apache License 2.0 | 5 votes |
@Override public ScriptHistory findScriptHistory(ResourceResolver resourceResolver, Script script) { Resource resource = resourceResolver.getResource(getScriptHistoryPath(script)); if (resource != null) { return resource.adaptTo(ScriptHistoryImpl.class); } return ScriptHistoryImpl.empty(script.getPath()); }
Example 9
Source File: HistoryImpl.java From APM with Apache License 2.0 | 5 votes |
@Override public HistoryEntry findHistoryEntry(ResourceResolver resourceResolver, final String path) { Resource resource = resourceResolver.getResource(path); if (resource != null) { return resource.adaptTo(HistoryEntryImpl.class); } return null; }
Example 10
Source File: HistoryImpl.java From APM with Apache License 2.0 | 5 votes |
private HistoryEntryWriterBuilder createBuilder(ResourceResolver resolver, Script script, ExecutionMode mode, Progress progressLogger) { Resource source = resolver.getResource(script.getPath()); return HistoryEntryWriter.builder() .author(source.getValueMap().get(JcrConstants.JCR_CREATED_BY, StringUtils.EMPTY)) .executor(resolver.getUserID()) .fileName(source.getName()) .filePath(source.getPath()) .isRunSuccessful(progressLogger.isSuccess()) .mode(mode.toString()) .progressLog(ProgressHelper.toJson(progressLogger.getEntries())); }
Example 11
Source File: ModelPersistorImpl.java From sling-whiteboard with Apache License 2.0 | 5 votes |
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 12
Source File: CatalogDataResourceProviderManagerImpl.java From commerce-cif-connector with Apache License 2.0 | 5 votes |
/** * Find all existing virtual catalog data roots using all query defined in service configuration. * * @param resolver Resource resolver * @return all virtual catalog roots */ @SuppressWarnings("unchecked") private List<Resource> findDataRoots(ResourceResolver resolver) { List<Resource> allResources = new ArrayList<>(); for (String queryString : this.findAllQueries) { if (!StringUtils.contains(queryString, "|")) { throw new IllegalArgumentException("Query string does not contain query syntax seperated by '|': " + queryString); } String queryLanguage = StringUtils.substringBefore(queryString, "|"); String query = StringUtils.substringAfter(queryString, "|"); // data roots are JCR nodes, so we prefer JCR query because the resource resolver appears to be unreliable // when we are in the middle of registering/unregistering resource providers try { Session session = resolver.adaptTo(Session.class); Workspace workspace = session.getWorkspace(); QueryManager qm = workspace.getQueryManager(); Query jcrQuery = qm.createQuery(query, queryLanguage); QueryResult result = jcrQuery.execute(); NodeIterator nodes = result.getNodes(); while (nodes.hasNext()) { Node node = nodes.nextNode(); Resource resource = resolver.getResource(node.getPath()); if (resource != null) { allResources.add(resource); } } } catch (RepositoryException x) { log.error("Error finding data roots", x); } } dataRoots = allResources; return allResources; }
Example 13
Source File: CommentPostServlet.java From sling-samples with Apache License 2.0 | 5 votes |
@Override protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws ServletException, IOException { final String title = request.getParameter(CommentsUtil.PROPERTY_TITLE); final String text = request.getParameter(CommentsUtil.PROPERTY_TEXT); final String userId = request.getRemoteUser(); logger.debug("New comment from {} : {} - {}", new Object[] {userId, title, text}); // TODO - check values // save comment ResourceResolver resolver = null; try { resolver = factory.getServiceResourceResolver(null); final Resource reqResource = resolver.getResource(request.getResource().getPath()); final Comment c = new Comment(); c.setTitle(title); c.setText(text); c.setCreatedBy(userId); this.commentsService.addComment(reqResource, c); // send redirect at the end final String path = request.getResource().getPath(); response.sendRedirect(resolver.map(request.getContextPath() + path + ".html")); } catch ( final LoginException le ) { throw new ServletException("Unable to login", le); } finally { if ( resolver != null ) { resolver.close(); } } }
Example 14
Source File: MessageStoreImpl.java From sling-samples with Apache License 2.0 | 5 votes |
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 15
Source File: AdapterImplementations.java From sling-org-apache-sling-models-impl with Apache License 2.0 | 5 votes |
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 16
Source File: ResourcePathInjector.java From sling-org-apache-sling-models-impl with Apache License 2.0 | 5 votes |
private List<Resource> getResources(ResourceResolver resolver, String[] paths, String fieldName) { List<Resource> resources = new ArrayList<>(); for (String path : paths) { Resource resource = resolver.getResource(path); if (resource != null) { resources.add(resource); } else { LOG.warn("Could not retrieve resource at path {} for field {}. Since it is required it won't be injected.", path, fieldName); // all resources should've been injected. we stop return null; } } return resources; }
Example 17
Source File: MessageStoreImpl.java From sling-samples with Apache License 2.0 | 4 votes |
private Resource assertEachNode(ResourceResolver resolver, String archive, String domain, String list, String threadPath, String threadName) throws PersistenceException, LoginException { final String pathToMessage = archive+domain+"/"+list+"/"+threadPath; String path = pathToMessage; Resource resource = resolver.getResource(path); int cnt = 0; while (resource == null) { cnt++; path = path.substring(0, path.lastIndexOf("/")); resource = resolver.getResource(path); } if (cnt > 0) { int threadNodesNumber = threadPath.split("/").length; // bind paths List<String> nodePaths = new ArrayList<String>(); nodePaths.add(domain); nodePaths.add(list); for (String node : threadPath.split("/")) { nodePaths.add(node); } // bind props List<Map<String, Object>> nodeProps = new ArrayList<Map<String, Object>>(); nodeProps.add(setProperties(MailArchiveServerConstants.DOMAIN_RT, domain)); nodeProps.add(setProperties(MailArchiveServerConstants.LIST_RT, list)); for (int i = 0; i < threadNodesNumber-1; i++) { nodeProps.add(null); } nodeProps.add(setProperties(MailArchiveServerConstants.THREAD_RT, threadName)); // checking for (int i = nodePaths.size()-cnt; i < nodePaths.size(); i++) { String name = nodePaths.get(i); assertResource(resolver, resource, name, nodeProps.get(i)); resource = resolver.getResource(resource.getPath()+"/"+name); } } resource = resolver.getResource(pathToMessage); if (resource == null) { throw new RuntimeException("Parent resource cannot be null."); } else { return resource; } }
Example 18
Source File: MessageStoreImpl.java From sling-samples with Apache License 2.0 | 4 votes |
private void save(ResourceResolver resolver, Message msg) throws IOException, LoginException { // apply message processors for(MessageProcessor processor : getSortedMessageProcessors()) { logger.debug("Calling {}", processor); processor.processMessage(msg); } // into path: archive/domain/list/thread/message final Map<String, Object> msgProps = new HashMap<String, Object>(); final List<BodyPart> attachments = new ArrayList<BodyPart>(); msgProps.put(resourceTypeKey, MailArchiveServerConstants.MESSAGE_RT); StringBuilder plainBody = new StringBuilder(); StringBuilder htmlBody = new StringBuilder(); Boolean hasBody = false; if (!msg.isMultipart()) { plainBody = new StringBuilder(getTextPart(msg)); } else { Multipart multipart = (Multipart) msg.getBody(); recursiveMultipartProcessing(multipart, plainBody, htmlBody, hasBody, attachments); } msgProps.put(PLAIN_BODY, plainBody.toString().replaceAll("\r\n", "\n")); if (htmlBody.length() > 0) { msgProps.put(HTML_BODY, htmlBody.toString()); } msgProps.putAll(getMessagePropertiesFromHeader(msg.getHeader())); ByteArrayOutputStream baos = new ByteArrayOutputStream(); new DefaultMessageWriter().writeHeader(msg.getHeader(), baos); String origHdr = baos.toString(MailArchiveServerConstants.DEFAULT_ENCODER.charset().name()); msgProps.put(X_ORIGINAL_HEADER, origHdr); final Header hdr = msg.getHeader(); final String listIdRaw = hdr.getField(LIST_ID).getBody(); final String listId = listIdRaw.substring(1, listIdRaw.length()-1); // remove < and > final String list = getListNodeName(listId); final String domain = getDomainNodeName(listId); final String subject = (String) msgProps.get(SUBJECT); final String threadPath = threadKeyGen.getThreadKey(subject); final String threadName = removeRe(subject); Resource parentResource = assertEachNode(resolver, archivePath, domain, list, threadPath, threadName); String msgNodeName = makeJcrFriendly((String) msgProps.get(NAME)); boolean isMsgNodeCreated = assertResource(resolver, parentResource, msgNodeName, msgProps); if (isMsgNodeCreated) { Resource msgResource = resolver.getResource(parentResource, msgNodeName); for (BodyPart att : attachments) { if (!attachmentFilter.isEligible(att)) { continue; } final Map<String, Object> attProps = new HashMap<String, Object>(); parseHeaderToProps(att.getHeader(), attProps); Body body = att.getBody(); if (body instanceof BinaryBody) { attProps.put(CONTENT, ((BinaryBody) body).getInputStream()); } else if (body instanceof TextBody) { attProps.put(CONTENT, ((TextBody) body).getInputStream()); } String attNodeName = Text.escapeIllegalJcrChars(att.getFilename()); assertResource(resolver, msgResource, attNodeName, attProps); } updateThread(resolver, parentResource, msgProps); } }
Example 19
Source File: MultiFieldDropTargetPostProcessor.java From commerce-cif-connector with Apache License 2.0 | 4 votes |
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 20
Source File: List.java From sling-samples with Apache License 2.0 | 2 votes |
/** * Instantiates a new list model. * * @param request the request */ public List(final SlingHttpServletRequest request) { ResourceResolver resourceResolver = request.getResourceResolver(); this.resource = resourceResolver.getResource("/content/htlblog/posts"); }