Java Code Examples for org.apache.sling.api.resource.ResourceResolver#adaptTo()
The following examples show how to use
org.apache.sling.api.resource.ResourceResolver#adaptTo() .
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: 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 2
Source File: ScriptReplicatorImpl.java From APM with Apache License 2.0 | 6 votes |
@Override public void replicate(Script script, ResourceResolver resolver) throws ExecutionException, ReplicationException { eventManager.trigger(Event.BEFORE_REPLICATE, script); final List<Script> includes = new LinkedList<>(); includes.add(script); includes.addAll(new ReferenceFinder(scriptFinder, resolver).findReferences(script)); final Session session = resolver.adaptTo(Session.class); for (final Script include : includes) { replicator.replicate(session, ReplicationActionType.ACTIVATE, include.getPath()); } eventManager.trigger(Event.AFTER_REPLICATE, script); }
Example 3
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 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: 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 6
Source File: CommentServiceImpl.java From publick-sling-blog with Apache License 2.0 | 6 votes |
/** * Mark comment as ham, submit it to Akismet and mark it valid it by setting * it's display property to true. * * @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 markAsHam(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.submitHam(resource); } } catch (RepositoryException e) { LOGGER.error("Could not submit ham.", e); } return result; }
Example 7
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 8
Source File: IsProductDetailPageServlet.java From commerce-cif-connector with Apache License 2.0 | 5 votes |
/** * Finds the {@code cq:catalogPath} property at the given path and exposes its value in the property * {@link #CATALOG_PATH_PROPERTY} to Granite UI expressions. * * @param path a Sling resource path * @param request the current request */ static void prepareCatalogPathProperty(String path, SlingHttpServletRequest request) { ResourceResolver resourceResolver = request.getResourceResolver(); CatalogSearchSupport catalogSearchSupport = new CatalogSearchSupport(resourceResolver); String catalogPath = catalogSearchSupport.findCatalogPath(path); if (StringUtils.isBlank(catalogPath)) { CommerceBasePathsService pathsService = resourceResolver.adaptTo(CommerceBasePathsService.class); catalogPath = pathsService.getProductsBasePath(); } ExpressionCustomizer customizer = ExpressionCustomizer.from(request); customizer.setVariable(CATALOG_PATH_PROPERTY, catalogPath); }
Example 9
Source File: EncryptPostProcessor.java From sling-whiteboard with Apache License 2.0 | 5 votes |
@Override public void process(SlingHttpServletRequest slingRequest, List<Modification> modifications) throws Exception { Set<Modification> mods = modifications.stream() .filter(modification -> modification.getSource().endsWith(config.suffix())).collect(Collectors.toSet()); if (mods.isEmpty()) { return; } ResourceResolver resolver = slingRequest.getResourceResolver(); Session session = resolver.adaptTo(Session.class); for (Modification mod : mods) { String encryptPropertyPath = mod.getSource(); String propertyPath = encryptPropertyPath.substring(0, encryptPropertyPath.lastIndexOf(config.suffix())); String resourcePath = propertyPath.substring(0, propertyPath.lastIndexOf('/')); if (config.inline()) { session.move(encryptPropertyPath, propertyPath); } EncryptableValueMap map = resolver.resolve(resourcePath).adaptTo(EncryptableValueMap.class); map.encrypt(propertyPath.substring(resourcePath.length() + 1, propertyPath.length())); session.removeItem(encryptPropertyPath); } modifications.removeAll(mods); mods.forEach(mod -> { logger.debug("removed {} for source {}", mod.getType() , mod.getSource()); }); }
Example 10
Source File: ScriptStorageImpl.java From APM with Apache License 2.0 | 5 votes |
@Override public void remove(final Script script, ResourceResolver resolver) throws RepositoryException { scriptManager.getEventManager().trigger(Event.BEFORE_REMOVE, script); final Session session = resolver.adaptTo(Session.class); final String path = script.getPath(); if (path != null) { session.removeItem(path); session.save(); } }
Example 11
Source File: ScriptStorageImpl.java From APM with Apache License 2.0 | 5 votes |
private Script saveScript(FileDescriptor descriptor, LaunchMetadata launchMetadata, boolean overwrite, ResourceResolver resolver) { Script result = null; try { final Session session = resolver.adaptTo(Session.class); final ValueFactory valueFactory = session.getValueFactory(); final Binary binary = valueFactory.createBinary(descriptor.getInputStream()); final Node saveNode = session.getNode(descriptor.getPath()); final Node fileNode, contentNode; if (overwrite && saveNode.hasNode(descriptor.getName())) { fileNode = saveNode.getNode(descriptor.getName()); contentNode = fileNode.getNode(JcrConstants.JCR_CONTENT); } else { fileNode = saveNode.addNode(generateFileName(descriptor.getName(), saveNode), JcrConstants.NT_FILE); contentNode = fileNode.addNode(JcrConstants.JCR_CONTENT, JcrConstants.NT_RESOURCE); } contentNode.setProperty(JcrConstants.JCR_DATA, binary); contentNode.setProperty(JcrConstants.JCR_ENCODING, SCRIPT_ENCODING.name()); fileNode.addMixin(ScriptNode.APM_SCRIPT); fileNode.setProperty(ScriptNode.APM_LAUNCH_ENABLED, launchMetadata.isExecutionEnabled()); setOrRemoveProperty(fileNode, ScriptNode.APM_LAUNCH_MODE, launchMetadata.getLaunchMode()); setOrRemoveProperty(fileNode, ScriptNode.APM_LAUNCH_ENVIRONMENT, launchMetadata.getLaunchEnvironment()); setOrRemoveProperty(fileNode, ScriptNode.APM_LAUNCH_HOOK, launchMetadata.getExecutionHook()); setOrRemoveProperty(fileNode, ScriptNode.APM_LAUNCH_SCHEDULE, launchMetadata.getExecutionSchedule()); removeProperty(fileNode, ScriptNode.APM_LAST_EXECUTED); JcrUtils.setLastModified(fileNode, Calendar.getInstance()); session.save(); result = scriptFinder.find(fileNode.getPath(), resolver); } catch (RepositoryException e) { LOG.error(e.getMessage(), e); } return result; }
Example 12
Source File: GraphqlProductViewHandler.java From commerce-cif-connector with Apache License 2.0 | 4 votes |
@Override protected ViewQuery createQuery(SlingHttpServletRequest request, Session session, String queryString) throws RepositoryException { queryString = preserveWildcards(queryString); PredicateGroup gqlPredicateGroup = PredicateConverter.createPredicatesFromGQL(queryString); ResourceResolver resolver = request.getResourceResolver(); tagManager = resolver.adaptTo(TagManager.class); Set<String> predicateSet = customizePredicateGroup(gqlPredicateGroup); // set default start path RequestPathInfo pathInfo = request.getRequestPathInfo(); CommerceBasePathsService cbps = resolver.adaptTo(CommerceBasePathsService.class); String defaultStartPath = cbps.getProductsBasePath(); String startPath = (pathInfo.getSuffix() != null && pathInfo.getSuffix().startsWith(defaultStartPath)) ? pathInfo.getSuffix() : defaultStartPath; if (!predicateSet.contains(PathPredicateEvaluator.PATH)) { gqlPredicateGroup.add(new Predicate(PathPredicateEvaluator.PATH).set(PathPredicateEvaluator.PATH, startPath)); } String refererHeader = request.getHeader(REFERER_HEADER); if (StringUtils.isNotBlank(refererHeader) && refererHeader.contains(PAGE_EDITOR_PATH + "/")) { int p = refererHeader.lastIndexOf(PAGE_EDITOR_PATH); String pagePath = refererHeader.substring(p + PAGE_EDITOR_PATH.length()); if (pagePath.endsWith(".html")) { pagePath = pagePath.substring(0, pagePath.length() - ".html".length()); } CatalogSearchSupport catalogSearch = new CatalogSearchSupport(resolver); String catalogPath = catalogSearch.findCatalogPath(pagePath); String rootCategoryId = catalogSearch.findCategoryId(catalogPath); if (rootCategoryId != null) { gqlPredicateGroup.add(new Predicate(CATEGORY_ID_PARAMETER).set(CATEGORY_ID_PARAMETER, rootCategoryId)); gqlPredicateGroup.add(new Predicate(CATEGORY_PATH_PARAMETER).set(CATEGORY_PATH_PARAMETER, catalogPath)); } } else { LOGGER.warn("The path of the edited page cannot be determined"); } // append node type constraint to match product data index /etc/commerce/oak:index/commerce gqlPredicateGroup.add(new Predicate(TypePredicateEvaluator.TYPE).set(TypePredicateEvaluator.TYPE, NT_UNSTRUCTURED)); // append limit constraint if (gqlPredicateGroup.get(Predicate.PARAM_LIMIT) == null) { String limit = request.getParameter(LIMIT); if ((limit != null) && (!limit.equals(""))) { int offset = Integer.parseInt(StringUtils.substringBefore(limit, "..")); int total = Integer.parseInt(StringUtils.substringAfter(limit, "..")); gqlPredicateGroup.set(Predicate.PARAM_LIMIT, Long.toString(total - offset)); gqlPredicateGroup.set(Predicate.PARAM_OFFSET, Long.toString(offset)); } else { gqlPredicateGroup.set(Predicate.PARAM_LIMIT, Long.toString(DEFAULT_LIMIT)); } } // add product property constraint addProductConstraint(gqlPredicateGroup); // append order constraint if (!predicateSet.contains(Predicate.ORDER_BY)) { gqlPredicateGroup.add(new Predicate(Predicate.ORDER_BY) .set(Predicate.ORDER_BY, "@" + JCR_LASTMODIFIED) .set(Predicate.PARAM_SORT, Predicate.SORT_DESCENDING)); } return new GQLViewQuery(resolver, omniSearchHandler, xssAPI, gqlPredicateGroup); }
Example 13
Source File: ScriptDownloadServlet.java From APM with Apache License 2.0 | 4 votes |
@Override protected void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws ServletException, IOException { String fileName = request.getParameter("filename"); String filePath = request.getParameter("filepath"); String mode = request.getParameter("mode"); try { final ResourceResolver resourceResolver = request.getResourceResolver(); final Session session = resourceResolver.adaptTo(Session.class); if (!("view").equals(mode)) { response.setContentType("application/octet-stream"); // Your content type response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8")); } String path = StringUtils.replace(filePath, "_jcr_content", "jcr:content"); Node jcrContent = session.getNode(path + "/jcr:content"); InputStream input = jcrContent.getProperty("jcr:data").getBinary().getStream(); session.save(); int read; byte[] bytes = new byte[BYTES_DOWNLOAD]; OutputStream os = response.getOutputStream(); while ((read = input.read(bytes)) != -1) { os.write(bytes, 0, read); } input.close(); os.flush(); os.close(); } catch (RepositoryException e) { LOGGER.error(e.getMessage(), e); response.sendRedirect("/etc/cqsm.html"); // response.sendError(500); } }
Example 14
Source File: ScriptManagerImpl.java From APM with Apache License 2.0 | 4 votes |
private ActionExecutor createExecutor(ExecutionMode mode, ResourceResolver resolver) throws RepositoryException { final Context context = new ContextImpl((JackrabbitSession) resolver.adaptTo(Session.class)); return ActionExecutorFactory.create(mode, context, actionFactory); }
Example 15
Source File: PageManagerImpl.java From jackalope with Apache License 2.0 | 4 votes |
public PageManagerImpl(ResourceResolver resolver) { this.resolver = resolver; Session session = resolver.adaptTo(Session.class); if (session == null) throw new IllegalArgumentException("Resolver must be adaptable to Session."); this.session = session; }