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

The following examples show how to use org.apache.sling.api.SlingHttpServletResponse#setStatus() . 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: ScriptRemoveServlet.java    From APM with Apache License 2.0 6 votes vote down vote up
private void removeSingleFile(ResourceResolver resolver, SlingHttpServletResponse response,
		String fileName) throws IOException {
	if (StringUtils.isEmpty(fileName)) {
		ServletUtils.writeMessage(response, "error", "File name to be removed cannot be empty");
	} else {
		final Script script = scriptFinder.find(fileName, resolver);
		if (script == null) {
			ServletUtils
					.writeMessage(response, "error", String.format("Script not found: '%s'", fileName));
		} else {
			final String scriptPath = script.getPath();

			try {
				scriptStorage.remove(script, resolver);

				ServletUtils.writeMessage(response, "success",
						String.format("Script removed successfully: %s", scriptPath));
			} catch (RepositoryException e) {
				response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
				ServletUtils.writeJson(response,
						String.format("Cannot remove script: '%s'." + " Repository error: %s", scriptPath,
								e.getMessage()));
			}
		}
	}
}
 
Example 2
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 3
Source File: ScriptRemoveServlet.java    From APM with Apache License 2.0 5 votes vote down vote up
@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 4
Source File: ScriptRemoveServlet.java    From APM with Apache License 2.0 5 votes vote down vote up
private void removeAllFiles(ResourceResolver resolver, SlingHttpServletResponse response, String all)
		throws IOException {
	if (!Boolean.parseBoolean(all)) {
		ServletUtils.writeMessage(response, "error", "Remove all scripts is not confirmed");
	} else {
		final List<String> paths = new LinkedList<>();
		final List<Script> scripts = scriptFinder.findAll(resolver);

		try {
			for (Script script : scripts) {
				final String path = script.getPath();

				scriptStorage.remove(script, resolver);
				paths.add(path);
			}

			final Map<String, Object> context = new HashMap<>();
			context.put("paths", paths);

			ServletUtils.writeMessage(response, "success",
					String.format("Scripts removed successfully, total: %d", scripts.size()), context);
		} catch (RepositoryException e) {
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			ServletUtils.writeJson(response,
					"Cannot save remove all scripts. Repository error: " + e.getMessage());
		}
	}
}
 
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: FileUploadServlet.java    From publick-sling-blog with Apache License 2.0 5 votes vote down vote up
/**
 * Handle POST request and send appropriate response after file
 * is uploaded.
 */
@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {
    final String path = request.getParameter(PATH_REQUEST_PARAM);
    String file = fileUploadService.uploadFile(request, path);

    if (file != null) {
        response.setStatus(response.SC_OK);
    } else {
        response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
    }
}
 
Example 9
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 10
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 11
Source File: FormServlet.java    From sling-samples with Apache License 2.0 4 votes vote down vote up
private void fail(final Form form, final int status, final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws ServletException, IOException {
    response.setStatus(status);
    forward(form, request, response, null);
}
 
Example 12
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 13
Source File: ScriptRunServlet.java    From APM with Apache License 2.0 4 votes vote down vote up
@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: 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 15
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 16
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.");
    }
}