org.apache.sling.api.SlingHttpServletRequest Java Examples
The following examples show how to use
org.apache.sling.api.SlingHttpServletRequest.
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: RequestDisposalTest.java From sling-org-apache-sling-models-impl with Apache License 2.0 | 7 votes |
@Test public void testWithInitializedRequest() { // destroy a wrapper of the root request SlingHttpServletRequest destroyedRequest = new SlingHttpServletRequestWrapper(request); factory.requestInitialized(new ServletRequestEvent(servletContext, destroyedRequest)); // but adapt from a wrapper of a wrapper of that wrapper SlingHttpServletRequest adaptableRequest = new SlingHttpServletRequestWrapper(new SlingHttpServletRequestWrapper(destroyedRequest)); TestModel model = factory.getAdapter(adaptableRequest, TestModel.class); assertEquals("teststring", model.testString); assertNoneDisposed(); factory.requestDestroyed(new ServletRequestEvent(servletContext, destroyedRequest)); assertAllDisposed(); }
Example #2
Source File: RelationTypesDataSourceServlet.java From aem-core-cif-components with Apache License 2.0 | 7 votes |
@Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { ResourceBundle resourceBundle = request.getResourceBundle(null); List<Resource> values = new ArrayList<>(); for (RelationType relationType : RelationType.values()) { ValueMap vm = new ValueMapDecorator(new HashMap<String, Object>()); vm.put("value", relationType); vm.put("text", toText(resourceBundle, relationType.getText())); values.add(new ValueMapResource(request.getResourceResolver(), new ResourceMetadata(), JcrConstants.NT_UNSTRUCTURED, vm)); } DataSource ds = new SimpleDataSource(values.iterator()); request.setAttribute(DataSource.class.getName(), ds); }
Example #3
Source File: ExportServlet.java From sling-org-apache-sling-models-impl with Apache License 2.0 | 6 votes |
private void addScriptBindings(SlingScriptHelper scriptHelper, SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException { SimpleBindings bindings = new SimpleBindings(); bindings.put(SLING, scriptHelper); bindings.put(RESOURCE, request.getResource()); bindings.put(SlingModelsScriptEngineFactory.RESOLVER, request.getResource().getResourceResolver()); bindings.put(REQUEST, request); bindings.put(RESPONSE, response); try { bindings.put(READER, request.getReader()); } catch (Exception e) { bindings.put(READER, new BufferedReader(new StringReader(""))); } bindings.put(OUT, response.getWriter()); bindings.put(LOG, logger); scriptEngineFactory.invokeBindingsValuesProviders(bindingsValuesProvidersByContext, bindings); SlingBindings slingBindings = new SlingBindings(); slingBindings.putAll(bindings); request.setAttribute(SlingBindings.class.getName(), slingBindings); }
Example #4
Source File: HexNodeNameGenerator.java From sling-samples with Apache License 2.0 | 6 votes |
/** @inheritDoc */ public String getNodeName( SlingHttpServletRequest request, String parentPath, boolean requirePrefix, NodeNameGenerator defaultNng) { if(SlingbucksConstants.ORDERS_PATH.equals(parentPath)) { final StringBuilder name = new StringBuilder(); for(int i=0; i < 2; i++) { name.append(Long.toHexString(random.nextLong())); } log.debug("Called for {} parent path, node name is {}", parentPath, name.toString()); return name.toString(); } log.debug("Path does not match {}, doing nothing", SlingbucksConstants.ORDERS_PATH); return null; }
Example #5
Source File: SolrQueryHandler.java From aem-solr-search with Apache License 2.0 | 6 votes |
@Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); response.setCharacterEncoding("utf-8"); JSONArray solrDocs = new JSONArray(); SolrClient solr = getQueryingSolrClient(); try { LOG.debug("Query using Solr Client {} and the solr core {}", solr, core); QueryResponse result = solr.query(core, new SolrQuery("*:*")); SolrDocumentList list=result.getResults(); response.getWriter().write(list.toString()); } catch (SolrServerException e) { e.printStackTrace(); } }
Example #6
Source File: ScriptRunBackgroundServlet.java From APM with Apache License 2.0 | 6 votes |
private BackgroundJobParameters getParameters(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws IOException { final String searchPath = request.getParameter(FILE_REQUEST_PARAMETER); final String modeName = request.getParameter(MODE_REQUEST_PARAMETER); final String userName = request.getResourceResolver().getUserID(); if (StringUtils.isEmpty(searchPath)) { ServletUtils.writeMessage(response, ERROR_RESPONSE_TYPE, "Please set the script file name: -d \"file=[name]\""); return null; } if (StringUtils.isEmpty(modeName)) { ServletUtils.writeMessage(response, ERROR_RESPONSE_TYPE, "Running mode not specified."); return null; } return new BackgroundJobParameters(searchPath, modeName, userName); }
Example #7
Source File: CommentServiceImpl.java From publick-sling-blog with Apache License 2.0 | 6 votes |
/** * Delete comment 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 deleteComment(final SlingHttpServletRequest request, final String id) { boolean result = false; try { Session session = request.getResourceResolver().adaptTo(Session.class); Node node = session.getNodeByIdentifier(id); if (node != null) { JcrResourceUtil.setProperty(node, PublickConstants.COMMENT_PROPERTY_DISPLAY, false); session.save(); result = true; } } catch (RepositoryException e) { LOGGER.error("Could not delete comment from JCR", e); } return result; }
Example #8
Source File: ExportServlet.java From sling-org-apache-sling-models-impl with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") private Map<String, String> createOptionMap(SlingHttpServletRequest request) { Map<String, String[]> parameterMap = request.getParameterMap(); String[] selectors = request.getRequestPathInfo().getSelectors(); Map<String, String> result = new HashMap<String, String>(baseOptions.size() + parameterMap.size() + selectors.length - 1); result.putAll(baseOptions); for (String selector : selectors) { if (!selector.equals(registeredSelector)) { result.put(selector, "true"); } } for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) { if (entry.getValue().length == 0) { result.put(entry.getKey(), Boolean.TRUE.toString()); } else { result.put(entry.getKey(), entry.getValue()[0]); } } return result; }
Example #9
Source File: TransformationManagerImpl.java From sling-whiteboard with Apache License 2.0 | 6 votes |
private boolean doStep(Map<String, Object> properties, SlingHttpServletRequest request) { Iterator<String> it = properties.keySet().iterator(); while (it.hasNext()) { String key = it.next(); switch (key) { case TransformationConstants.PATHS: String value = (String) properties.get(key); if (!request.getRequestURI().matches(value)) { return false; } break; case TransformationConstants.EXTENSIONS: String extension = (String) properties.get(key); if (!request.getRequestURI().endsWith(extension)) { return false; } break; default: } } return true; }
Example #10
Source File: AEMDataLayerInterceptorFilter.java From AEM-DataLayer with Apache License 2.0 | 6 votes |
private boolean isApplicable(SlingHttpServletRequest request) { Object appliable = request.getAttribute(REQUEST_PROPERTY_AEM_DATALAYER_APPLICABLE); if (appliable == null) { Resource resource = request.getResource(); PageManager pMgr = resource.getResourceResolver().adaptTo(PageManager.class); Page page = pMgr.getContainingPage(resource); AEMDataLayerConfig config = AEMDataLayerConfig.getDataLayerConfig(page); if (config != null) { DataLayer dataLayer = new DataLayer(config, page); request.setAttribute(DataLayerConstants.REQUEST_PROPERTY_AEM_DATALAYER, dataLayer); request.setAttribute(REQUEST_PROPERTY_AEM_DATALAYER_APPLICABLE, Boolean.TRUE); return true; } else { request.setAttribute(REQUEST_PROPERTY_AEM_DATALAYER_APPLICABLE, Boolean.FALSE); return false; } } else { return Boolean.TRUE.equals(appliable); } }
Example #11
Source File: RequestDisposalTest.java From sling-org-apache-sling-models-impl with Apache License 2.0 | 6 votes |
@Test public void testWithUnitializedRequest() { // destroy a wrapper of the root request SlingHttpServletRequest destroyedRequest = new SlingHttpServletRequestWrapper(request); // but adapt from a wrapper of a wrapper of that wrapper SlingHttpServletRequest adaptableRequest = new SlingHttpServletRequestWrapper(new SlingHttpServletRequestWrapper(destroyedRequest)); TestModel model = factory.getAdapter(adaptableRequest, TestModel.class); assertEquals("teststring", model.testString); assertNoneDisposed(); factory.requestDestroyed(new ServletRequestEvent(servletContext, destroyedRequest)); assertNoneDisposed(); }
Example #12
Source File: IncludeTagFilter.java From sling-org-apache-sling-dynamic-include with Apache License 2.0 | 6 votes |
private String getUrl(Configuration config, SlingHttpServletRequest request) { String url = buildUrl(config, request); if (config.isRewritePath()) { url = removeQuestionMark(url); url = request.getResourceResolver().map(request, url); } else { url = encodeJcrContentPart(url); try { url = new URI(null, null, url, null).toASCIIString(); } catch (URISyntaxException e) { LOG.error("Include url is in the wrong format", e); return null; } } return url; }
Example #13
Source File: ChildResourceViaProvider.java From sling-org-apache-sling-models-impl with Apache License 2.0 | 6 votes |
@Override public Object getAdaptable(Object original, String value) { if (StringUtils.isBlank(value)) { return ORIGINAL; } if (original instanceof Resource) { return ((Resource) original).getChild(value); } else if (original instanceof SlingHttpServletRequest) { final SlingHttpServletRequest request = (SlingHttpServletRequest) original; final Resource resource = request.getResource(); if (resource == null) { return null; } Resource child = resource.getChild(value); if (child == null) { log.debug("Could not obtain child {} of resource {}", value, resource.getPath()); return null; } return new ChildResourceRequestWrapper(request, child); } else { log.warn("Received unexpected adaptable of type {}.", original.getClass().getName()); return null; } }
Example #14
Source File: ScriptResultServlet.java From APM with Apache License 2.0 | 6 votes |
@Override protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws IOException { String fileName = request.getParameter("filename"); String content = request.getParameter("content"); if (fileName == null || fileName.length() == 0) { LOGGER.error("Parameter fileName is required"); return; } response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8")); InputStream input = IOUtils.toInputStream(content); IOUtils.copy(input, response.getOutputStream()); }
Example #15
Source File: LinkOperation.java From sling-samples with Apache License 2.0 | 6 votes |
@Override protected void doRun(SlingHttpServletRequest request, HtmlResponse response, List<Modification> changes) throws RepositoryException { Session session = request.getResourceResolver().adaptTo(Session.class); String resourcePath = request.getResource().getPath(); if (session.itemExists(resourcePath)) { Node source = (Node) session.getItem(resourcePath); // create a symetric link RequestParameter linkParam = request.getRequestParameter("target"); if (linkParam != null) { String linkPath = linkParam.getString(); if (session.itemExists(linkPath)) { Item targetItem = session.getItem(linkPath); if (targetItem.isNode()) { linkHelper.createSymetricLink(source, (Node) targetItem, "link"); } } } } }
Example #16
Source File: BackupServlet.java From publick-sling-blog with Apache License 2.0 | 5 votes |
/** * Return all packages on a GET request in order of newest to oldest. */ @Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { final PrintWriter writer = response.getWriter(); response.setCharacterEncoding(CharEncoding.UTF_8); response.setContentType("application/json"); List<JcrPackage> packages = packageService.getPackageList(request); try { JSONArray jsonArray = new JSONArray(); for (JcrPackage jcrPackage : packages) { final JSONObject json = getJsonFromJcrPackage(jcrPackage); jsonArray.put(json); } response.setStatus(SlingHttpServletResponse.SC_OK); writer.write(jsonArray.toString()); } catch (JSONException | RepositoryException e) { LOGGER.error("Could not write JSON", e); response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
Example #17
Source File: UrlProviderImpl.java From aem-core-cif-components with Apache License 2.0 | 5 votes |
private String toUrl(SlingHttpServletRequest request, Page page, Map<String, String> params, String template, String selectorFilter) { if (page != null && params.containsKey(selectorFilter)) { Resource pageResource = page.adaptTo(Resource.class); boolean deepLink = !WCMMode.DISABLED.equals(WCMMode.fromRequest(request)); if (deepLink) { Resource subPageResource = toSpecificPage(pageResource, params.get(selectorFilter)); if (subPageResource != null) { pageResource = subPageResource; } } params.put(PAGE_PARAM, pageResource.getPath()); } String prefix = "${", suffix = "}"; // variables have the format ${var} if (template.contains("{{")) { prefix = "{{"; suffix = "}}"; // variables have the format {{var}} } StringSubstitutor sub = new StringSubstitutor(params, prefix, suffix); String url = sub.replace(template); url = StringUtils.substringBeforeLast(url, "#" + prefix); // remove anchor if it hasn't been substituted if (url.contains(prefix)) { LOGGER.warn("Missing params for URL substitution. Resulted URL: {}", url); } return url; }
Example #18
Source File: ScriptsDatasourceServlet.java From APM with Apache License 2.0 | 5 votes |
@Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) { String path = request.getRequestPathInfo().getSuffix(); List<Resource> scripts = new ArrayList<>(); Resource resource = request.getResourceResolver().getResource(path); for (Resource child : resource.getChildren()) { if (ScriptsRowModel.isFolder(child) || ScriptModel.isScript(child)) { scripts.add(new ResourceTypeWrapper(child)); } } DataSource dataSource = new SimpleDataSource(scripts.iterator()); request.setAttribute(DataSource.class.getName(), dataSource); }
Example #19
Source File: SystemConfigServlet.java From publick-sling-blog with Apache License 2.0 | 5 votes |
/** * Save system properties on POST. * * @param request The Sling HTTP servlet request. * @param response The Sling HTTP servlet response. */ @Override protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { final PrintWriter writer = response.getWriter(); final boolean allowWrite = userService.isAuthorable(request.getResourceResolver().adaptTo(Session.class)); response.setCharacterEncoding(CharEncoding.UTF_8); response.setContentType("application/json"); if (allowWrite) { final String blogName = request.getParameter(BLOG_NAME_PROPERTY); final boolean extensionlessUrls = Boolean.parseBoolean(request.getParameter(EXTENSIONLESS_URLS_PROPERTY)); final String tempDir = request.getParameter(TEMPORARY_DIRECTORY_PROPERTY); final Map<String, Object> properties = new HashMap<String, Object>(); properties.put(SystemSettingsService.SYSTEM_BLOG_NAME, blogName); properties.put(SystemSettingsService.SYSTEM_EXTENSIONLESS_URLS, extensionlessUrls); properties.put(SystemSettingsService.SYSTEM_TEMPORARY_DIRECTORY, tempDir); boolean result = systemSettingsService.setProperties(properties); if (result) { response.setStatus(SlingHttpServletResponse.SC_OK); sendResponse(writer, "OK", "Settings successfully updated."); } else { response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR); sendResponse(writer, "Error", "Settings failed to update."); } } else { response.setStatus(SlingHttpServletResponse.SC_FORBIDDEN); sendResponse(writer, "Error", "Current user not authorized."); } }
Example #20
Source File: IncludeTagFilter.java From sling-org-apache-sling-dynamic-include with Apache License 2.0 | 5 votes |
private boolean requestHasParameters(Collection<String> ignoreUrlParams, SlingHttpServletRequest request) { final Enumeration<?> paramNames = request.getParameterNames(); while (paramNames.hasMoreElements()) { final String paramName = (String) paramNames.nextElement(); if (!ignoreUrlParams.contains(paramName)) { return true; } } return false; }
Example #21
Source File: ThreeServlet3.java From aem-ide-tooling-4-intellij with Apache License 2.0 | 5 votes |
@Override protected final void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws ServletException, IOException { LOG.info("Servlet GET Method requested"); // Write a standard text/html response response.setContentType("text/html;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); response.getWriter().write("<html><body>Text to write to response</body></html>"); }
Example #22
Source File: ClientLibUseObject.java From aem-clientlib-async with Apache License 2.0 | 5 votes |
/** * Returns the include path for the given library and type, respecting the proxy settings. * @param lib library * @param type type * @param minify {@code true} for minify * @return the path * * @see com.adobe.granite.ui.clientlibs.impl.HtmlLibraryWriter#getIncludePath(SlingHttpServletRequest, ClientLibrary, LibraryType, boolean) */ private String getIncludePath(SlingHttpServletRequest request, ClientLibrary lib, LibraryType type, boolean minify) { String path = lib.getIncludePath(type, minify); if (lib.allowProxy() && (path.startsWith("/libs/") || path.startsWith("/apps/"))) { path = "/etc.clientlibs" + path.substring(5); } else { // check if request session has access (GRANITE-4429) if (request.getResourceResolver().getResource(lib.getPath()) == null) { path = null; } } return path; }
Example #23
Source File: RatingPostServlet.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 rating = request.getParameter(RatingsUtil.PROPERTY_RATING); final String userId = request.getRemoteUser(); logger.debug("New rating from {} : {}", userId, rating); // save rating ResourceResolver resolver = null; try { resolver = factory.getServiceResourceResolver(null); final Resource reqResource = resolver.getResource(request.getResource().getPath()); ratingsService.setRating(reqResource, userId, Double.valueOf(rating)); } catch ( final LoginException le ) { throw new ServletException("Unable to login", le); } finally { if ( resolver != null ) { resolver.close(); } } response.setContentType("application/json"); response.setCharacterEncoding("utf-8"); response.setStatus(200); final PrintWriter pw = response.getWriter(); pw.print("{ "); pw.print(" \"rating\" : "); pw.print(String.valueOf(ratingsService.getRating(request.getResource()))); pw.print("}"); }
Example #24
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 #25
Source File: IncludeTagFilter.java From sling-org-apache-sling-dynamic-include with Apache License 2.0 | 5 votes |
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) request; final String resourceType = slingRequest.getResource().getResourceType(); final Configuration config = configurationWhiteboard.getConfiguration(slingRequest, resourceType); if (config == null) { chain.doFilter(request, response); return; } final IncludeGenerator generator = generatorWhiteboard.getGenerator(config.getIncludeTypeName()); if (generator == null) { LOG.error("Invalid generator: " + config.getIncludeTypeName()); chain.doFilter(request, response); return; } final PrintWriter writer = response.getWriter(); final String url = getUrl(config, slingRequest); if (url == null) { chain.doFilter(request, response); return; } if (config.getAddComment()) { writer.append(String.format(COMMENT, StringEscapeUtils.escapeHtml4(url), resourceType)); } // Only write the includes markup if the required, configurable request // header is present if (shouldWriteIncludes(config, slingRequest)) { String include = generator.getInclude(url); LOG.debug(include); writer.append(include); } else { chain.doFilter(request, response); } }
Example #26
Source File: SelfInjectorTest.java From sling-org-apache-sling-models-impl with Apache License 2.0 | 5 votes |
@Test public void testMatchingClassWithSelfAnnotation() { when(annotatedElement.isAnnotationPresent(Self.class)).thenReturn(true); Object result = injector .getValue(request, "notRelevant", SlingHttpServletRequest.class, annotatedElement, registry); assertSame(request, result); }
Example #27
Source File: CatalogIdentifierDatasource.java From commerce-cif-connector with Apache License 2.0 | 5 votes |
@Override protected void doGet(@Nonnull SlingHttpServletRequest request, @Nonnull SlingHttpServletResponse response) throws ServletException, IOException { DataSource ds; if (catalogIdentifierService == null) { ds = EmptyDataSource.instance(); } else { ds = buildValuesList(request.getResourceResolver()); } request.setAttribute(DataSource.class.getName(), ds); }
Example #28
Source File: ThreeServlet6.java From aem-ide-tooling-4-intellij with Apache License 2.0 | 5 votes |
@Override protected final void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws ServletException, IOException { LOG.info("Servlet GET Method requested"); // Write a standard text/html response response.setContentType("text/html;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); response.getWriter().write("<html><body>Text to write to response</body></html>"); }
Example #29
Source File: ModelAdapterFactory.java From sling-org-apache-sling-models-impl with Apache License 2.0 | 5 votes |
@Override public Object getModelFromRequest(SlingHttpServletRequest request) { Class<?> clazz = this.adapterImplementations.getModelClassForRequest(request); if (clazz == null) { throw new ModelClassException("Could find model registered for request path: " + request.getServletPath()); } return handleBoundModelResult(internalCreateModel(request, clazz)); }
Example #30
Source File: ProductListItemImpl.java From aem-core-cif-components with Apache License 2.0 | 5 votes |
public ProductListItemImpl(String sku, String slug, String name, Price price, String imageURL, Page productPage, String activeVariantSku, SlingHttpServletRequest request, UrlProvider urlProvider) { this.sku = sku; this.slug = slug; this.name = name; this.imageURL = imageURL; this.price = price; this.productPage = productPage; this.activeVariantSku = activeVariantSku; this.request = request; this.urlProvider = urlProvider; }