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

The following examples show how to use org.apache.sling.api.SlingHttpServletResponse#setContentType() . 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: SystemConfigServlet.java    From publick-sling-blog with Apache License 2.0 5 votes vote down vote up
/**
 * 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 2
Source File: ErrorHandler.java    From publick-sling-blog with Apache License 2.0 5 votes vote down vote up
@Override
public void activate() {
    SlingHttpServletRequest request = getRequest();
    SlingHttpServletResponse response = getResponse();
    ResourceResolver resolver = getResourceResolver();

    isAnonymous = "anonymous".equals(resolver.adaptTo(Session.class).getUserID());

    message = (String) request.getAttribute(SlingConstants.ERROR_MESSAGE);
    Integer scObject = (Integer) request.getAttribute(SlingConstants.ERROR_STATUS);

    code = (scObject != null) ? scObject.intValue() : response.SC_INTERNAL_SERVER_ERROR;

    if (message == null) {
        message = statusToString(code);
    }

    // Print stack trace only if the user is not anonymous
    if (!isAnonymous) {
        if (request.getAttribute(SlingConstants.ERROR_EXCEPTION) instanceof Throwable) {
            Throwable throwable = (Throwable) request.getAttribute(SlingConstants.ERROR_EXCEPTION);
            printStackTrace(throwable);
        }
    }

    response.setStatus(code);
    response.setContentType("text/html"); 
    response.setCharacterEncoding("utf-8");
}
 
Example 3
Source File: ThreeServlet4.java    From aem-ide-tooling-4-intellij with Apache License 2.0 5 votes vote down vote up
@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 4
Source File: ThreeServlet2.java    From aem-ide-tooling-4-intellij with Apache License 2.0 5 votes vote down vote up
@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 5
Source File: ThreeServlet9.java    From aem-ide-tooling-4-intellij with Apache License 2.0 5 votes vote down vote up
@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 6
Source File: ThreeServlet15.java    From aem-ide-tooling-4-intellij with Apache License 2.0 5 votes vote down vote up
@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 7
Source File: OneServlet.java    From aem-ide-tooling-4-intellij with Apache License 2.0 5 votes vote down vote up
@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 8
Source File: SolrUpdateHandler.java    From aem-solr-search with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("application/json");
    response.setCharacterEncoding("utf-8");

    Resource page = request.getResource();
    GeometrixxMediaContentType contentType = page.adaptTo(GeometrixxMediaPage.class);

    response.getWriter().write(contentType.getJson().toJSONString());
}
 
Example 9
Source File: ThreeServlet3.java    From aem-ide-tooling-4-intellij with Apache License 2.0 5 votes vote down vote up
@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 10
Source File: BackupServlet.java    From publick-sling-blog with Apache License 2.0 5 votes vote down vote up
/**
 * 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 11
Source File: ThreeServlet.java    From aem-ide-tooling-4-intellij with Apache License 2.0 5 votes vote down vote up
@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 12
Source File: MimeTypeServlet.java    From sling-samples with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) 
        throws ServletException, IOException {
    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");
    final String mimeType = detector.getMimeType(request.getResource());
    response.getWriter().write(PREFIX); 
    response.getWriter().write(String.valueOf(mimeType));
}
 
Example 13
Source File: ThreeServlet5.java    From aem-ide-tooling-4-intellij with Apache License 2.0 5 votes vote down vote up
@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 14
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 15
Source File: ThreeServlet10.java    From aem-ide-tooling-4-intellij with Apache License 2.0 5 votes vote down vote up
@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 16
Source File: SampleFelixServlet.java    From aem-osgi-annotation-demo with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(final SlingHttpServletRequest req,
        final SlingHttpServletResponse resp) throws ServletException, IOException {

    PrintWriter out = resp.getWriter();

    resp.setContentType("text/plain");
    out.write("Annotation Demo Servlet - Felix - enabled: " + enabled + "\n");
    out.write(sampleFelixService.getSettings());
}
 
Example 17
Source File: HealthCheckExecutorServlet.java    From aem-healthcheck with Apache License 2.0 4 votes vote down vote up
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
                                                    throws ServletException, IOException {
    response.setContentType("application/json");
    response.setHeader("Cache-Control", "must-revalidate,no-cache,no-store");

    // parse query parameters
    String tagsStr = StringUtils.defaultString(request.getParameter(PARAM_TAGS));
    String[] tags = tagsStr.split("[, ;]+");
    String combineTagsOr = StringUtils.defaultString(request.getParameter(PARAM_COMBINE_TAGS_OR), "true");

    // execute health checks
    HealthCheckExecutionOptions options = new HealthCheckExecutionOptions();
    options.setCombineTagsWithOr(Boolean.valueOf(combineTagsOr));
    options.setForceInstantExecution(true);
    List<HealthCheckExecutionResult> results = healthCheckExecutor.execute(options, tags);

    // check results
    boolean allOk = true;
    for(HealthCheckExecutionResult result : results) {
        if(!result.getHealthCheckResult().isOk()) {
            allOk = false;
            break;
        }
    }

    // set appropriate status code
    if(!allOk) {
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    } else {
        response.setStatus(HttpServletResponse.SC_OK);
    }

    // write out JSON response
    JSONObject resultJson = new JSONObject();
    try {
        generateResponse(results, resultJson);
    } catch(JSONException ex) {
        logger.error("Could not serialize result into JSON", ex);
    }
    response.getWriter().write(resultJson.toString());
}
 
Example 18
Source File: ServletUtils.java    From APM with Apache License 2.0 4 votes vote down vote up
public static void writeJson(SlingHttpServletResponse response, String json) throws IOException {
	response.setCharacterEncoding("UTF-8");
	response.setContentType("application/json");
	response.getWriter().print(json);
	response.getWriter().flush();
}
 
Example 19
Source File: SolrBulkUpdateHandler.java    From aem-solr-search with Apache License 2.0 4 votes vote down vote up
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("application/json");
    response.setCharacterEncoding("utf-8");

    JSONArray solrDocs = new JSONArray();

    final String slingResourceType = getSlingResourceType(request);

    if (StringUtils.isEmpty(slingResourceType)) {
        response.getWriter().write(solrDocs.toJSONString());
        return;
    }

    Map<String, String> params = new HashMap<String, String>();
    params.put("path", "/content/geometrixx-media");
    params.put("type", "cq:PageContent");
    params.put("property", "sling:resourceType");
    params.put("property.value", slingResourceType);
    params.put("p.offset", "0");
    params.put("p.limit", "50");

    Session session = null;

    try {
        session = repository.loginAdministrative(null);
        Query query = queryBuilder.createQuery(PredicateGroup.create(params), session);
        SearchResult results = query.getResult();

        LOG.info("Found '{}' matches for query", results.getTotalMatches());

        for (Hit hit: results.getHits()) {

            // The query returns the jcr:content node, so we need its parent.
            Resource page = hit.getResource().getParent();
            GeometrixxMediaContentType contentType = page.adaptTo(GeometrixxMediaPage.class);

            if (contentType != null) {
                solrDocs.add(contentType.getJson());
            }
        }

    } catch (RepositoryException e) {
        LOG.error("Error getting repository", e);
    } finally {
        if (session != null && session.isLive())  {
            session.logout();
        }
    }

    response.getWriter().write(solrDocs.toJSONString());
}
 
Example 20
Source File: RecaptchaConfigServlet.java    From publick-sling-blog with Apache License 2.0 4 votes vote down vote up
/**
 * Save reCAPTCHA 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 siteKey = request.getParameter(SITE_KEY_PROPERTY);
        final String secretKey = request.getParameter(SECRET_KEY_PROPERTY);
        final boolean enabled = Boolean.parseBoolean(request.getParameter(ENABLED_PROPERTY));

        final Map<String, Object> properties = new HashMap<String, Object>();

        properties.put(RecaptchaService.RECAPTCHA_SITE_KEY, siteKey);
        properties.put(RecaptchaService.RECAPTCHA_ENABLED, enabled);

        /* Don't save the password if it's all stars. Don't save the password
         * if the user just added text to the end of the stars. This shouldn't
         * happen as the JavaScript should remove the value on focus. Save the
         * password if it's null or blank in order to clear it out. */
        if (StringUtils.isBlank(secretKey) || !secretKey.contains(PublickConstants.PASSWORD_REPLACEMENT)) {
            properties.put(RecaptchaService.RECAPTCHA_SECRET_KEY, secretKey);
        }

        final boolean result = recaptchaService.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.");
    }
}