Java Code Examples for org.apache.sling.api.SlingHttpServletRequest#getResourceResolver()
The following examples show how to use
org.apache.sling.api.SlingHttpServletRequest#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: GraphqlClientDataSourceServlet.java From aem-core-cif-components with Apache License 2.0 | 6 votes |
List<Resource> getGraphqlClients(@Nonnull SlingHttpServletRequest request) { ResourceResolver resolver = request.getResourceResolver(); List<Resource> graphqlClients = new ArrayList<>(); final Config cfg = new Config(request.getResource().getChild(Config.DATASOURCE)); boolean showEmptyOption = false; if (cfg != null) { ExpressionHelper expressionHelper = new ExpressionHelper(expressionResolver, request); showEmptyOption = expressionHelper.getBoolean(cfg.get("showEmptyOption")); } // Add empty option if (showEmptyOption) { graphqlClients.add(new GraphqlClientResource(i18n.get("Inherit", "Inherit property"), StringUtils.EMPTY, resolver)); } // Add other configurations for (String identifier : identifiers) { graphqlClients.add(new GraphqlClientResource(identifier, identifier, resolver)); } return graphqlClients; }
Example 2
Source File: ScriptRunBackgroundServlet.java From APM with Apache License 2.0 | 6 votes |
@Override protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws IOException { final String searchPath = request.getParameter(FILE_REQUEST_PARAMETER); final ResourceResolver resolver = request.getResourceResolver(); final Script script = scriptFinder.find(searchPath, resolver); final boolean isValid = script.isValid(); final boolean isExecutable = script.isLaunchEnabled(); if (!(isValid && isExecutable)) { ServletUtils.writeMessage(response, ERROR_RESPONSE_TYPE, String.format("Script '%s' cannot be processed. " + "Script needs to be executable and valid. Actual script status: valid - %s, executable - %s", searchPath, isValid, isExecutable)); return; } BackgroundJobParameters parameters = getParameters(request, response); if (parameters == null) { return; } Job job = scriptRunnerJobManager.scheduleJob(parameters); ServletUtils.writeMessage(response, BACKGROUND_RESPONSE_TYPE, BACKGROUND_RESPONSE_TYPE, createMapWithJobIdKey(job)); }
Example 3
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 4
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 5
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 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: 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 8
Source File: ScriptRemoveServlet.java From APM with Apache License 2.0 | 5 votes |
@Override protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { final String all = request.getParameter("confirmation"); final String fileName = request.getParameter("file"); ResourceResolver resolver = request.getResourceResolver(); if (fileName != null) { removeSingleFile(resolver, response, fileName); } else if (all != null) { removeAllFiles(resolver, response, all); } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); ServletUtils.writeMessage(response, "error", "Invalid arguments specified"); } }
Example 9
Source File: AbstractDatasourceServlet.java From APM with Apache License 2.0 | 5 votes |
@Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) { SimpleDataSourceBuilder builder = new SimpleDataSourceBuilder(request.getResourceResolver()); if (emptyOption != null) { builder.addOption(emptyOption); } options.forEach(item -> builder.addOption(getName(item.toString()), item.toString())); request.setAttribute(DataSource.class.getName(), builder.build()); }
Example 10
Source File: SampleServlet.java From AEM-Rules-for-SonarQube with Apache License 2.0 | 5 votes |
@Override protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws ServletException, IOException { ResourceResolver resourceResolver = null; resourceResolver = request.getResourceResolver(); // do sth }
Example 11
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 12
Source File: SlingObjectInjector.java From sling-org-apache-sling-models-impl with Apache License 2.0 | 4 votes |
@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 13
Source File: ScriptRunServlet.java From APM with Apache License 2.0 | 4 votes |
@Override protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws ServletException, IOException { ResourceResolver resolver = request.getResourceResolver(); final String searchPath = request.getParameter("file"); final String modeName = request.getParameter("mode"); if (StringUtils.isEmpty(searchPath)) { ServletUtils.writeMessage(response, "error", "Please set the script file name: -d \"file=[name]\""); return; } if (StringUtils.isEmpty(modeName)) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); ServletUtils.writeMessage(response, "error", "Running mode not specified."); return; } final Script script = scriptFinder.find(searchPath, resolver); if (script == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); ServletUtils.writeMessage(response, "error", String.format("Script not found: %s", searchPath)); return; } try { final ExecutionMode mode = ExecutionMode.fromString(modeName, ExecutionMode.DRY_RUN); final ExecutionResult result = scriptManager.process(script, mode, resolver); if (result.isSuccess()) { ServletUtils.writeJson(response, ProgressHelper.toJson(result.getEntries())); } else { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); ServletUtils.writeJson(response, ProgressHelper.toJson(result.getLastError())); } } catch (RepositoryException e) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); ServletUtils.writeMessage(response, "error", String.format("Script cannot be executed because of" + " repository error: %s", e.getMessage())); } }
Example 14
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 15
Source File: Author.java From sling-samples with Apache License 2.0 | 2 votes |
/** * Instantiates a new author model. * * @param request the request */ public Author(SlingHttpServletRequest request) { ResourceResolver resourceResolver = request.getResourceResolver(); userId = resourceResolver.getUserID(); }
Example 16
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"); }