Java Code Examples for org.apache.sling.api.SlingHttpServletResponse#sendError()

The following examples show how to use org.apache.sling.api.SlingHttpServletResponse#sendError() . 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: DefaultHtmlServlet.java    From sling-whiteboard with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {

    final Resource r = request.getResource();
    final String resourceType = r.getResourceType();
    final ResourceSchema m = registry.getSchema(resourceType);
    if(m == null) {
        response.sendError(
            HttpServletResponse.SC_BAD_REQUEST,
            "ResourceSchema not found for resource type " + resourceType + " at " + request.getResource().getPath());
        return;
    }
    
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html");

    renderingLogic.render(r, m, new HtmlResourceRenderer(registry, request, response.getWriter()));
    response.getWriter().flush();
}
 
Example 2
Source File: SearchDataSourceServlet.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
    final String PARAMETER_OFFSET = "_commerce_offset";
    final String PARAMETER_LIMIT = "_commerce_limit";
    final String PARAMETER_COMMERCE_TYPE = "_commerce_commerce_type";
    final Config cfg = new Config(request.getResource().getChild(Config.DATASOURCE));
    final SlingScriptHelper sling = ((SlingBindings) request.getAttribute(SlingBindings.class.getName())).getSling();
    final ExpressionHelper ex = new ExpressionHelper(sling.getService(ExpressionResolver.class), request);
    final String itemRT = cfg.get("itemResourceType", String.class);
    final long offset = ex.get(cfg.get("offset", "0"), long.class);
    final long limit = ex.get(cfg.get("limit", "20"), long.class);
    final String commerceType = ex.get(cfg.get("commerceType", "product"), String.class);

    Map<String, Object> queryParameters = new HashMap<>(request.getParameterMap());
    queryParameters.put(PARAMETER_OFFSET, String.valueOf(offset));
    queryParameters.put(PARAMETER_LIMIT, String.valueOf(limit));
    queryParameters.put(PARAMETER_COMMERCE_TYPE, commerceType);

    final String rootPath = request.getParameter("root");

    String rootCategoryId = new CatalogSearchSupport(request.getResourceResolver()).findCategoryId(rootPath);
    if (rootCategoryId != null) {
        queryParameters.put(CATEGORY_ID_PARAMETER, rootCategoryId);
        queryParameters.put(CATEGORY_PATH_PARAMETER, rootPath);
    }
    String queryString = new ObjectMapper().writeValueAsString(queryParameters);
    try {
        Iterator<Resource> virtualResults = request.getResourceResolver().findResources(queryString, VIRTUAL_PRODUCT_QUERY_LANGUAGE);

        final DataSource ds = new SimpleDataSource(new TransformIterator<>(virtualResults, r -> new ResourceWrapper(r) {
            public String getResourceType() {
                return itemRT;
            }
        }));

        request.setAttribute(DataSource.class.getName(), ds);
    } catch (Exception x) {
        response.sendError(500, x.getMessage());
        LOGGER.error("Error finding resources", x);
    }
}
 
Example 3
Source File: DataLayerTestServlet.java    From AEM-DataLayer with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
		throws IOException, ServletException {
	log.trace("doGet");
	String suffix = request.getRequestPathInfo().getSuffix();

	if (StringUtils.isNotEmpty(suffix)) {
		log.debug("Retrieving data layer for {}", suffix);
		Resource resource = request.getResourceResolver().getResource(suffix);
		if (resource != null) {

			HttpServletRequest req = requestResponseFactory.createRequest("GET", suffix + ".html");
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			HttpServletResponse resp = requestResponseFactory.createResponse(baos);
			requestProcessor.processRequest(req, resp, request.getResourceResolver());

			DataLayer dataLayer = DataLayerUtil.getDataLayer(req);
			if (dataLayer != null) {
				response.setContentType("application/json");
				response.getWriter().write(DataLayerUtil.toJSON(dataLayer));
			} else {
				log.warn("No Data Layer found for {}", suffix);
				response.sendError(404, "No Data Layer found for " + suffix);
			}

		} else {
			log.warn("No Resource found at {}", suffix);
			response.sendError(404, "No Resource found at " + suffix);
		}
	} else {
		response.sendError(400, "Missing Suffix");
	}

}
 
Example 4
Source File: StatsTestServlet.java    From sling-samples with Apache License 2.0 5 votes vote down vote up
@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) 
        throws ServletException, IOException {
    final RequestParameter param = request.getRequestParameter(IMPORT_FILE_ATTRIB_NAME);
    if(param == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing required parameter " + IMPORT_FILE_ATTRIB_NAME);
        return;
    }
    
    InputStream is = null;
    final PrintWriter pw = response.getWriter();
    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");
    
    try {
        is = param.getInputStream();
        pw.println("Creating stats from supplied mbox file...");
        int counter=0;
        final Iterator<Message> it = parser.parse(is);
        while(it.hasNext()) {
            final Message m = it.next();
            final String [] to = MailStatsProcessorImpl.toArray(m.getTo());
            final String [] cc = MailStatsProcessorImpl.toArray(m.getCc());
            for(String from : MailStatsProcessorImpl.toArray(m.getFrom())) {
                processor.computeStats(m.getDate(), from.toString(), to, cc);
            }
            counter++;
        }
        pw.println(counter + " messages parsed");
    } finally {
        processor.flush();
        pw.flush();
        if(is != null) {
            is.close();
        }
    }
}
 
Example 5
Source File: SystemFilter.java    From publick-sling-blog with Apache License 2.0 5 votes vote down vote up
/**
 * Prevent unauthorables from accessing Sling's user admin.
 *
 * @param request The Sling HTTP Servlet Request.
 * @param response The Sling HTTP Servlet Response.
 * @param chain The Filter Chain to continue processin the response.
 */
@Override
public void doFilter(final ServletRequest request, final ServletResponse response,
        final FilterChain chain) throws IOException, ServletException {

    // Since this is a Sling Filter, the request and response objects are guaranteed
    // to be of types SlingHttpServletRequest and SlingHttpServletResponse.
    final SlingHttpServletRequest slingRequest = (SlingHttpServletRequest)request;
    final SlingHttpServletResponse slingResponse = (SlingHttpServletResponse)response;
    final String path = slingRequest.getPathInfo().toLowerCase();
    final String method = slingRequest.getMethod();

    response.setCharacterEncoding(CharEncoding.UTF_8);

    if ("POST".equals(method) && path.startsWith("/system")) {
        if (userService != null) {
            final boolean allow = userService.isAuthorable(slingRequest.getResourceResolver().adaptTo(Session.class));

            if (allow) {
                chain.doFilter(request, response);
            } else {
                slingResponse.sendError(SlingHttpServletResponse.SC_FORBIDDEN);
            }
        } else {
            slingResponse.sendError(SlingHttpServletResponse.SC_FORBIDDEN);
        }
    } else {
        chain.doFilter(request, response);
    }
}
 
Example 6
Source File: PreviewFilter.java    From publick-sling-blog with Apache License 2.0 4 votes vote down vote up
/**
 * Handle blog posts that are not published. If the user is authenticated,
 * display a preview bar. If the user is anonymous, seve a 404.
 *
 * @param request The Sling HTTP Servlet Request.
 * @param response The Sling HTTP Servlet Response.
 * @param chain The Filter Chain to continue processin the response.
 */
@Override
public void doFilter(final ServletRequest request, final ServletResponse response,
        final FilterChain chain) throws IOException, ServletException {

    // Since this is a Sling Filter, the request and response objects are guaranteed
    // to be of types SlingHttpServletRequest and SlingHttpServletResponse.
    final SlingHttpServletRequest slingRequest = (SlingHttpServletRequest)request;
    final SlingHttpServletResponse slingResponse = (SlingHttpServletResponse)response;

    final Resource resource = slingRequest.getResource();
    final String method = slingRequest.getMethod();
    final String resourceType = resource.getResourceType();

    response.setCharacterEncoding(CharEncoding.UTF_8);

    if ("GET".equals(method) && PublickConstants.PAGE_TYPE_BLOG.equals(resourceType)) {

        if (!resource.getValueMap().get("visible", false)) {
            final boolean authorable = userService.isAuthorable(slingRequest.getResourceResolver().adaptTo(Session.class));

            /* If user is logged in and page isn't published, inject a preview bar. */
            if (authorable) {
                PrintWriter out = response.getWriter();
                CharResponseWrapper responseWrapper = new CharResponseWrapper((HttpServletResponse)response);

                try {
                  chain.doFilter(request, responseWrapper);
                } catch (Exception e) {
                  LOGGER.error("Could not continue chain", e);
                  chain.doFilter(request, response);
                }

                final String servletResponse = new String(responseWrapper.toString());
                final String previewHeader = getPreviewHeader(slingRequest, PREVIEW_HEADER_PATH);

                /* Insert component before body close tag. Append to end if body close tag doesn't exist. */
                if (servletResponse != null && servletResponse.contains(INSERTION_TAG)) {
                    String[] html = servletResponse.split(INSERTION_TAG);

                    out.write(html[0] + INSERTION_TAG + previewHeader + html[1]);
                } else {
                    out.write(servletResponse + previewHeader);
                }
            } else {
                /* If user is not logged in and page isn't published, forward to 404. */
                slingResponse.sendError(SlingHttpServletResponse.SC_NOT_FOUND);
            }
        } else {
            chain.doFilter(request, slingResponse);
        }
    } else {
        chain.doFilter(request, slingResponse);
    }
}