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

The following examples show how to use org.apache.sling.api.SlingHttpServletResponse#getWriter() . 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: 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 2
Source File: SampleOsgiServlet.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 - OSGi - enabled: " + enabled + "\n");
    out.write(sampleOsgiService.getSettings());
}
 
Example 3
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 4
Source File: RatingPostServlet.java    From sling-samples with Apache License 2.0 5 votes vote down vote up
@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 5
Source File: CommentServlet.java    From publick-sling-blog with Apache License 2.0 5 votes vote down vote up
/**
 * Return all comments 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<Resource> comments = commentService.getComments(request);

    try {
        JSONArray jsonArray = new JSONArray();

        for (Resource comment : comments) {
            final JSONObject json = new JSONObject();
            final ValueMap properties = comment.getValueMap();
            final Resource post = commentService.getParentPost(comment);

            json.put(PublickConstants.COMMENT_PROPERTY_COMMENT,
                    properties.get(PublickConstants.COMMENT_PROPERTY_COMMENT, String.class));
            json.put(JSON_ID, properties.get(JcrConstants.JCR_UUID, String.class));
            json.put(JSON_EDITED, properties.get(PublickConstants.COMMENT_PROPERTY_EDITED, false));
            json.put(JSON_REPLIES, commentService.numberOfReplies(comment));
            json.put(JSON_SPAM, properties.get(PublickConstants.COMMENT_PROPERTY_SPAM, false));
            json.put(JSON_POST, new JSONObject()
                    .put(JSON_POST_TEXT, post.getValueMap().get(PublickConstants.COMMENT_PROPERTY_TITLE, String.class))
                    .put(JSON_POST_LINK, linkRewriter.rewriteLink(post.getPath(), request.getServerName())));

            jsonArray.put(json);
        }

        response.setStatus(SlingHttpServletResponse.SC_OK);
        writer.write(jsonArray.toString());
    } catch (JSONException e) {
        LOGGER.error("Could not write JSON", e);
        response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}
 
Example 6
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 7
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 8
Source File: EmailServlet.java    From publick-sling-blog with Apache License 2.0 5 votes vote down vote up
/**
 * Send email on post to servlet. The submission is verified through the reCAPTCHA
 * service before submitting. Upon completion, a JSON response is returned.
 *
 * @param request The Sling HTTP servlet request
 * @param response The Sling HTTP servlet response
 * @see <a href="http://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-using-smtp-java.html">Sending an Email Through the Amazon SES SMTP Interface with Java</a>
 */
@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("application/json");

    PrintWriter writer = response.getWriter();
    boolean notRobot = recaptchaService.validate(request);

    if (notRobot) {
        final String submitterName = request.getParameter("name");
        final String submitterEmail = request.getParameter("email");
        final String submitterMessage = request.getParameter("message");

        if (StringUtils.isNotEmpty(submitterName)
                && StringUtils.isNotEmpty(submitterName)
                && StringUtils.isNotEmpty(submitterName)) {

            final String body = String.format(BODY, submitterName, submitterEmail, submitterMessage);
            final boolean result = emailService.sendMail(SUBJECT, body);

            if (result) {
                response.setStatus(SlingHttpServletResponse.SC_OK);
                sendResponse(writer, SlingHttpServletResponse.SC_OK, "Email was sent successfully.");
            } else {
                response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                sendResponse(writer, SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error.");
            }
        } else {
            response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            sendResponse(writer, SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Submission was missing the message, name or email.");
        }
    } else {
        response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        sendResponse(writer, SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "The reCAPTCHA service determined that you were a robot.");
    }
}
 
Example 9
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.");
    }
}
 
Example 10
Source File: EmailConfigServlet.java    From publick-sling-blog with Apache License 2.0 4 votes vote down vote up
/**
 * Save email configuration 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 smtpUsername = request.getParameter(SMTP_USERNAME_PROPERTY);
        final String smtpPassword = request.getParameter(SMTP_PASSWORD_PROPERTY);
        final String sender = request.getParameter(SENDER_PROPERTY);
        final String recipient = request.getParameter(RECIPIENT_PROPERTY);
        final String host = request.getParameter(HOST_PROPERTY);
        final Long port = getPortNumber(request.getParameter(PORT_PROPERTY));

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

        properties.put(EmailService.EMAIL_SMTP_USERNAME, smtpUsername);
        properties.put(EmailService.EMAIL_SENDER, sender);
        properties.put(EmailService.EMAIL_RECIPIENT, recipient);
        properties.put(EmailService.EMAIL_SMTP_HOST, host);
        properties.put(EmailService.EMAIL_SMTP_PORT, port);

        /* 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 (smtpPassword == null || !smtpPassword.contains(PublickConstants.PASSWORD_REPLACEMENT)) {
            properties.put(EmailService.EMAIL_SMTP_PASSWORD, smtpPassword);
        }

        final boolean result = emailService.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 11
Source File: AkismetConfigServlet.java    From publick-sling-blog with Apache License 2.0 4 votes vote down vote up
/**
 * Save Akismet 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 apiKey = request.getParameter(API_KEY_PROPERTY);
        final String domainName = request.getParameter(DOMAIN_NAME_PROPERTY);
        final boolean enabled = Boolean.parseBoolean(request.getParameter(ENABLED_PROPERTY));

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

        properties.put(AkismetService.AKISMET_DOMAIN_NAME, domainName);
        properties.put(AkismetService.AKISMET_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(apiKey) || !apiKey.contains(PublickConstants.PASSWORD_REPLACEMENT)) {
            properties.put(AkismetService.AKISMET_API_KEY, apiKey);
        }

        final boolean result = akismetService.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 12
Source File: SimpleJSONServlet.java    From aem-solr-search with Apache License 2.0 3 votes vote down vote up
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {

    PrintWriter out = response.getWriter();

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

    solrCore = request.getParameter(REQUEST_PARAM_CORE_NAME);

    getJSONWriter(response.getWriter());
}