org.apache.sling.api.resource.ResourceResolver Java Examples
The following examples show how to use
org.apache.sling.api.resource.ResourceResolver.
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: 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 #2
Source File: Activator.java From aem-password-reset with Apache License 2.0 | 6 votes |
@Activate public void start(ActivatorConfiguration config) { String[] authorizableIds = config.pwdreset_authorizables(); Session session = null; try { ResourceResolver resolver = resolverFactory.getAdministrativeResourceResolver(null); UserManager userManager = resolver.adaptTo(UserManager.class); session = resolver.adaptTo(Session.class); for (String authorizable : authorizableIds) { try { Authorizable user = userManager.getAuthorizable(authorizable); if (user != null) { ((User) user).changePassword(authorizable); if (!userManager.isAutoSave()) { session.save(); } log.info("Changed the password for {}", authorizable); } else { log.error("Could not find authorizable {}", authorizable); } } catch (RepositoryException repEx) { log.error("Could not change password for {}", authorizable, repEx); } } } catch (LoginException loginEx) { log.error("Could not login to the repository", loginEx); } finally { if(session != null) { session.logout(); } } }
Example #3
Source File: MagentoProduct.java From commerce-cif-connector with Apache License 2.0 | 6 votes |
/** * Creates an instance of a *variant* product and all its variants.<br> * All the methods that access properties (e.g. prices, descriptions, etc) defined in both the active variant * and the base product will first get the properties defined in the variant and will fallback to the * property of the base product if a variant property is null. * * @param resourceResolver The resource resolver for that resource. * @param path The resource path of this product. * @param product The Magento base product. * @param activeVariantSku The SKU of the "active" variant product or null if this product represents the base product. */ public MagentoProduct(ResourceResolver resourceResolver, String path, ProductInterface product, String activeVariantSku) { this.resourceResolver = resourceResolver; this.path = path; this.product = product; this.activeVariantSku = activeVariantSku; if (product instanceof ConfigurableProduct) { ConfigurableProduct cp = (ConfigurableProduct) product; if (cp.getVariants() != null && cp.getVariants().size() > 0) { if (activeVariantSku != null) { masterVariant = cp.getVariants() .stream() .map(cv -> cv.getProduct()) .filter(sp -> activeVariantSku.equals(sp.getSku())) .findFirst() .orElse(null); } // fallback + default if (masterVariant == null) { masterVariant = cp.getVariants().get(0).getProduct(); } } } }
Example #4
Source File: ResourceResolverConsumer.java From AEM-Rules-for-SonarQube with Apache License 2.0 | 6 votes |
public Tag findTag(String tagId, Asset asset, Session session) { Tag tag = null; ResourceResolver resourceResolver = null; try { resourceResolver = getResourceResolver(session); TagManager tagManager = resourceResolver.adaptTo(TagManager.class); tag = tagManager.resolve(tagId); } finally { if (null != resourceResolver && resourceResolver.isLive()) { resourceResolver.close(); } } return tag; }
Example #5
Source File: SlingHelper.java From APM with Apache License 2.0 | 6 votes |
/** * Retrieve values from repository with wrapped impersonated session (automatically opened and closed). */ @SuppressWarnings("unchecked") public static <T> T resolve(ResourceResolverFactory factory, String userId, ResolveCallback callback) throws ResolveException { ResourceResolver resolver = null; try { resolver = getResourceResolverForUser(factory, userId); return (T) callback.resolve(resolver); } catch (Exception e) { throw new ResolveException(RESOLVE_ERROR_MESSAGE, e); } finally { if (resolver != null && resolver.isLive()) { resolver.close(); } } }
Example #6
Source File: NavigationImplTest.java From aem-core-cif-components with Apache License 2.0 | 6 votes |
private void initCatalogPage(boolean catalogRoot, boolean showMainCategories, boolean useCaConfig) { Page catalogPage = mock(Page.class); Resource catalogPageContent = mock(Resource.class); when(catalogPageContent.isResourceType(RT_CATALOG_PAGE)).thenReturn(catalogRoot); Map<String, Object> catalogPageProperties = new HashMap<>(); catalogPageProperties.put(PN_SHOW_MAIN_CATEGORIES, showMainCategories); if (!useCaConfig) { catalogPageProperties.put(PN_MAGENTO_ROOT_CATEGORY_ID, 4); } when(catalogPageContent.adaptTo(ComponentsConfiguration.class)).thenReturn(new ComponentsConfiguration(new ValueMapDecorator( ImmutableMap.of(PN_MAGENTO_ROOT_CATEGORY_ID, 4)))); when(catalogPageContent.getValueMap()).thenReturn(new ValueMapDecorator(catalogPageProperties)); when(catalogPage.getContentResource()).thenReturn(catalogPageContent); when(catalogPage.getPath()).thenReturn("/content/catalog"); when(catalogPageContent.getPath()).thenReturn("/content/catalog/jcr:content"); ResourceResolver mockResourceResolver = mock(ResourceResolver.class); when(mockResourceResolver.getResource(any(String.class))).thenReturn(null); when(catalogPageContent.getResourceResolver()).thenReturn(mockResourceResolver); when(pageManager.getPage(CATALOG_PAGE_PATH)).thenReturn(catalogPage); ValueMap configProperties = new ValueMapDecorator(ImmutableMap.of(PN_MAGENTO_ROOT_CATEGORY_ID, 4)); when(catalogPage.adaptTo(ComponentsConfiguration.class)).thenReturn(new ComponentsConfiguration(configProperties)); }
Example #7
Source File: SlingHelper.java From APM with Apache License 2.0 | 6 votes |
/** * Do some operation on repository (delete or update resource etc) with wrapped impersonated session * (automatically opened and closed). */ public static void operate(ResourceResolverFactory factory, String userId, OperateCallback callback) throws OperateException { ResourceResolver resolver = null; try { resolver = getResourceResolverForUser(factory, userId); callback.operate(resolver); resolver.commit(); } catch (Exception e) { throw new OperateException(OPERATE_ERROR_MESSAGE, e); } finally { if (resolver != null && resolver.isLive()) { resolver.close(); } } }
Example #8
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 #9
Source File: HistoryImpl.java From APM with Apache License 2.0 | 6 votes |
private HistoryEntry createHistoryEntry(ResourceResolver resolver, Script script, ExecutionMode mode, HistoryEntryWriter historyEntryWriter, boolean remote) { try { Session session = resolver.adaptTo(Session.class); Node scriptHistoryNode = createScriptHistoryNode(script, session); Node historyEntryNode = createHistoryEntryNode(scriptHistoryNode, script, mode, remote); historyEntryNode.setProperty(HistoryEntryImpl.SCRIPT_CONTENT_PATH, versionService.getVersionPath(script)); writeProperties(resolver, historyEntryNode, historyEntryWriter); session.save(); resolver.commit(); return resolver.getResource(historyEntryNode.getPath()).adaptTo(HistoryEntryImpl.class); } catch (PersistenceException | RepositoryException e) { LOG.error("Issues with saving to repository while logging script execution", e); return null; } }
Example #10
Source File: ScriptRemoveServlet.java From APM with Apache License 2.0 | 6 votes |
private void removeSingleFile(ResourceResolver resolver, SlingHttpServletResponse response, String fileName) throws IOException { if (StringUtils.isEmpty(fileName)) { ServletUtils.writeMessage(response, "error", "File name to be removed cannot be empty"); } else { final Script script = scriptFinder.find(fileName, resolver); if (script == null) { ServletUtils .writeMessage(response, "error", String.format("Script not found: '%s'", fileName)); } else { final String scriptPath = script.getPath(); try { scriptStorage.remove(script, resolver); ServletUtils.writeMessage(response, "success", String.format("Script removed successfully: %s", scriptPath)); } catch (RepositoryException e) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); ServletUtils.writeJson(response, String.format("Cannot remove script: '%s'." + " Repository error: %s", scriptPath, e.getMessage())); } } } }
Example #11
Source File: SeeAlsoDataFetcher.java From sling-samples with Apache License 2.0 | 6 votes |
/** * For "see also", our articles have just the article name but no path or * section. This maps those names (which are Sling Resource names) to their * Resource, so we can use the full path + title to render links. */ private static Map<String, Object> toArticleRef(ResourceResolver resolver, String nodeName) { final String jcrQuery = String.format("/jcr:root%s//*[@filename='%s']", Constants.ARTICLES_ROOT, nodeName); final Iterator<Resource> it = resolver.findResources(jcrQuery, "xpath"); // We want exactly one result if (!it.hasNext()) { throw new RuntimeException("No Resource found:" + jcrQuery); } final Map<String, Object> result = SlingWrappers.resourceWrapper(it.next()); if (it.hasNext()) { throw new RuntimeException("More than one Resource found:" + jcrQuery); } return result; }
Example #12
Source File: AbstractLauncher.java From APM with Apache License 2.0 | 6 votes |
void processScript(Script script, ResourceResolver resolver, LauncherType launcherType) throws PersistenceException { final String scriptPath = script.getPath(); try { if (!script.isValid()) { getScriptManager().process(script, ExecutionMode.VALIDATION, resolver); } if (script.isValid()) { final ExecutionResult result = getScriptManager().process(script, ExecutionMode.AUTOMATIC_RUN, resolver); logStatus(scriptPath, result.isSuccess(), launcherType); } else { logger.warn("{} launcher cannot execute script which is not valid: {}", launcherType.toString(), scriptPath); } } catch (RepositoryException e) { logger.error("Script cannot be processed because of repository error: {}", scriptPath, e); } }
Example #13
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 #14
Source File: ScriptManagerImpl.java From APM with Apache License 2.0 | 6 votes |
@Override public Progress process(Script script, final ExecutionMode mode, final Map<String, String> customDefinitions, ResourceResolver resolver) throws RepositoryException, PersistenceException { Progress progress; try { progress = execute(script, mode, customDefinitions, resolver); } catch (ExecutionException e) { progress = new ProgressImpl(resolver.getUserID()); progress.addEntry(Status.ERROR, e.getMessage()); } updateScriptProperties(script, mode, progress.isSuccess()); versionService.updateVersionIfNeeded(resolver, script); saveHistory(script, mode, progress); eventManager.trigger(Event.AFTER_EXECUTE, script, mode, progress); return progress; }
Example #15
Source File: ResourceResolverInjectorTest.java From sling-org-apache-sling-models-impl with Apache License 2.0 | 5 votes |
@Test public void testFromSomethingElse() { SlingHttpServletResponse response = mock(SlingHttpServletResponse.class); Object result = injector.getValue(response, "resourceResolver", ResourceResolver.class, element, registry); assertNull(result); }
Example #16
Source File: ResourceResolverInjectorTest.java From sling-org-apache-sling-models-impl with Apache License 2.0 | 5 votes |
@Test public void testFromResource() { Resource resource = mock(Resource.class); ResourceResolver resourceResolver = mock(ResourceResolver.class); when(resource.getResourceResolver()).thenReturn(resourceResolver); Object result = injector.getValue(resource, "resourceResolver", ResourceResolver.class, element, registry); assertEquals(resourceResolver, result); }
Example #17
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 #18
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 #19
Source File: MockResource.java From sling-whiteboard with Apache License 2.0 | 5 votes |
public MockResource(ResourceResolver resolver, String path) { this.resolver = resolver; this.path = path; this.metadata = new ResourceMetadata(); metadata.put(ResourceMetadata.RESOLUTION_PATH, path); metadata.put(ResourceMetadata.RESOLUTION_PATH_INFO, path); }
Example #20
Source File: AuthenticatedRemoteResourceProviderTest.java From sling-whiteboard with Apache License 2.0 | 5 votes |
@Test void testResourceReadingFromMetaFile() { Resource hey_bob = resourceProvider.getResource(bob, "/content/test-1/hey", resourceContext, null); assertNotNull(hey_bob, "Expected to find /content/test-1/hey for user bob."); assertEquals(ServletResolverConstants.DEFAULT_RESOURCE_TYPE, hey_bob.getResourceType(), () -> "Expected that /content/test-1/hey's resource type is " + ServletResolverConstants.DEFAULT_RESOURCE_TYPE); ValueMap heyProperties = hey_bob.getValueMap(); assertEquals(1, heyProperties.size()); assertEquals(ServletResolverConstants.DEFAULT_RESOURCE_TYPE, heyProperties.get(ResourceResolver.PROPERTY_RESOURCE_TYPE, String.class)); assertEquals(ServletResolverConstants.DEFAULT_RESOURCE_TYPE, hey_bob.getResourceType(), () -> "Expected that /content/test-1/hey's resource type is " + ServletResolverConstants.DEFAULT_RESOURCE_TYPE); Resource joe_bob = resourceProvider.getResource(bob, "/content/test-1/hey/joe", resourceContext, null); assertNotNull(joe_bob, "Expected to find /content/test-1/hey/joe"); assertEquals(ServletResolverConstants.DEFAULT_RESOURCE_TYPE, joe_bob.getResourceType(), () -> "Expected that /content/test-1/hey/joe's resource type is " + ServletResolverConstants.DEFAULT_RESOURCE_TYPE); ValueMap joeProperties = joe_bob.getValueMap(); assertEquals(2, joeProperties.size()); assertEquals(ServletResolverConstants.DEFAULT_RESOURCE_TYPE, joeProperties.get(ResourceResolver.PROPERTY_RESOURCE_TYPE, String.class)); Calendar joelastModified = joeProperties.get("lastModifiedDate", Calendar.class); assertNotNull(joelastModified, String.format("Expected a lastModifiedDate property on %s", joe_bob.getPath())); assertEquals(1407421980000L, joelastModified.getTimeInMillis()); assertTrue(wrapsSameResource(joe_bob, getChild(bob, hey_bob, "joe")), "Expected to get a cached " + "representation of /content/test-1/hey/joe"); Iterator<Resource> joeChildren = resourceProvider.listChildren(bob, joe_bob); assertNull(joeChildren, String.format("Did not expect children resources for %s", joe_bob.getPath())); Resource hey_alice = resourceProvider.getResource(alice, "/content/test-1/hey", resourceContext, null); assertNull(hey_alice, "Did not expect user alice to have access to /content/test-1/hey."); }
Example #21
Source File: FileResource.java From sling-whiteboard with Apache License 2.0 | 5 votes |
public FileResource(final ResourceResolver resourceResolver, final String path, final File file) { this.resolver = resourceResolver; this.path = path; this.file = file; this.metadata = new ResourceMetadata(); this.metadata.setModificationTime(file.lastModified()); this.metadata.setResolutionPath(path); if (file.isFile()) { this.metadata.setContentLength(file.length()); } }
Example #22
Source File: RemoteResourceProvider.java From sling-whiteboard with Apache License 2.0 | 5 votes |
@NotNull private CacheableResource buildResource(@NotNull Map<String, Object> authenticationInfo, @NotNull String path, @NotNull RemoteResourceReference reference, @NotNull Directory directory) { Map<String, Object> properties = new HashMap<>(); properties.put(ResourceResolver.PROPERTY_RESOURCE_TYPE, "sling:Folder"); for (RemoteResourceReference remoteResourceReference : directory.getChildren()) { if (remoteResourceReference.getType() == RemoteResourceReference.Type.FILE && SLING_META_FILE.equals(remoteResourceReference.getName())) { try { File file = remoteStorageProvider.getFile(remoteResourceReference, authenticationInfo); if (file != null) { jsonParser.parse( (String parsedPath, Map<String, Object> propertiesMap) -> { if ("/".equals(parsedPath)) { propertiesMap.forEach(properties::put); } }, file.getInputStream(), JSON_PARSER_OPTIONS ); // special case - a meta-file augments the directory's properties ShallowReference shallowReference = tree.getReference(remoteResourceReference.getPath()); if (shallowReference == null) { shallowReference = new ShallowReference(remoteResourceReference.getPath()); tree.add(shallowReference); } shallowReference.markProvidedResource(path); } } catch (IOException e) { LOGGER.error(String.format("Unable to parse file %s.", remoteResourceReference.getPath()), e); } break; } } return new CacheableResource(remoteStorageProvider, reference, path, properties); }
Example #23
Source File: ScriptRemoveServlet.java From APM with Apache License 2.0 | 5 votes |
private void removeAllFiles(ResourceResolver resolver, SlingHttpServletResponse response, String all) throws IOException { if (!Boolean.parseBoolean(all)) { ServletUtils.writeMessage(response, "error", "Remove all scripts is not confirmed"); } else { final List<String> paths = new LinkedList<>(); final List<Script> scripts = scriptFinder.findAll(resolver); try { for (Script script : scripts) { final String path = script.getPath(); scriptStorage.remove(script, resolver); paths.add(path); } final Map<String, Object> context = new HashMap<>(); context.put("paths", paths); ServletUtils.writeMessage(response, "success", String.format("Scripts removed successfully, total: %d", scripts.size()), context); } catch (RepositoryException e) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); ServletUtils.writeJson(response, "Cannot save remove all scripts. Repository error: " + e.getMessage()); } } }
Example #24
Source File: AbstractLauncher.java From APM with Apache License 2.0 | 5 votes |
void processScripts(List<Script> scripts, ResourceResolver resolver, LauncherType launcherType) throws PersistenceException { if (!scripts.isEmpty()) { logger.info("Launcher will try to run following scripts: {}", scripts.size()); logger.info(MessagingUtils.describeScripts(scripts)); for (Script script : scripts) { processScript(script, resolver, launcherType); } } }
Example #25
Source File: HistoryAutocleanService.java From APM with Apache License 2.0 | 5 votes |
private void deleteItem(ResourceResolver resolver, Resource resource) { try { log.info("Deleting: {}", resource.getPath()); resolver.delete(resource); } catch (PersistenceException e) { throw new RuntimeException(e); } }
Example #26
Source File: AbstractInjector.java From sling-org-apache-sling-models-impl with Apache License 2.0 | 5 votes |
protected ResourceResolver getResourceResolver(Object adaptable) { ResourceResolver resolver = null; if (adaptable instanceof Resource) { resolver = ((Resource) adaptable).getResourceResolver(); } else if (adaptable instanceof SlingHttpServletRequest) { resolver = ((SlingHttpServletRequest) adaptable).getResourceResolver(); } return resolver; }
Example #27
Source File: HistoryAutocleanService.java From APM with Apache License 2.0 | 5 votes |
private void deleteHistoryByDays(ResourceResolver resolver) { if (config.maxDays() >= 0) { log.info("Looking for items older than {} days", config.maxDays()); LocalDate date = LocalDate.now().minusDays(config.maxDays()); deleteHistoryByQuery(resolver, String.format(MAX_DAYS_QUERY, date), 0); } }
Example #28
Source File: ResourceResolverConsumer.java From AEM-Rules-for-SonarQube with Apache License 2.0 | 5 votes |
public String findName(final String path) { String name = ""; ResourceResolver resourceResolver = null; try { resourceResolver = resourceResolverProducer.produce(); name = resourceResolver.getResource(path).getName(); } finally { if (null != resourceResolver && resourceResolver.isLive()) { resourceResolver.close(); } } return name; }
Example #29
Source File: AdministrativeAccessUsageCheck.java From AEM-Rules-for-SonarQube with Apache License 2.0 | 5 votes |
public ResourceResolver getResourceResolver(Map<String, Object> credentials) { ResourceResolver resolver = null; try { resolver = resolverFactory.getAdministrativeResourceResolver(credentials); // Noncompliant {{Method 'getAdministrativeResourceResolver' is deprecated. Use 'getServiceResourceResolver' instead.}} } catch (LoginException e) { // } return resolver; }
Example #30
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; }