Java Code Examples for org.apache.sling.api.SlingHttpServletRequest#getParameter()

The following examples show how to use org.apache.sling.api.SlingHttpServletRequest#getParameter() . 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: GraphqlProductViewHandler.java    From commerce-cif-connector with Apache License 2.0 6 votes vote down vote up
protected String generateHtmlOutput(Collection<Hit> hits, SlingHttpServletRequest request,
    SlingHttpServletResponse response) throws ServletException, IOException {
    // if resource type is not set return String representation of search result
    if (request.getParameter("itemResourceType") == null) {
        return hits.toString();
    }

    StringResponseWrapper hitResponse = new StringResponseWrapper(response);

    RequestDispatcherOptions requestDispatcherOptions = new RequestDispatcherOptions(null);

    // Force a resource type, to render the resource in a specific way
    requestDispatcherOptions.setForceResourceType(request.getParameter("itemResourceType"));

    for (Hit hit : hits) {
        Resource resource = (Resource) hit.get("resource");
        if (resource != null) {
            request.setAttribute(Resource.class.getCanonicalName(), resource);
            RequestDispatcher dispatcher = request.getRequestDispatcher(resource, requestDispatcherOptions);
            dispatcher.include(request, hitResponse);
            request.removeAttribute(Resource.class.getCanonicalName());
        }
    }
    return hitResponse.getString();
}
 
Example 2
Source File: ScriptRunBackgroundServlet.java    From APM with Apache License 2.0 6 votes vote down vote up
@Override
protected void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
    throws IOException {

  final String searchPath = request.getParameter(FILE_REQUEST_PARAMETER);
  final ResourceResolver resolver = request.getResourceResolver();
  final Script script = scriptFinder.find(searchPath, resolver);

  final boolean isValid = script.isValid();
  final boolean isExecutable = script.isLaunchEnabled();

  if (!(isValid && isExecutable)) {
    ServletUtils.writeMessage(response, ERROR_RESPONSE_TYPE, String.format("Script '%s' cannot be processed. " +
            "Script needs to be executable and valid. Actual script status: valid - %s, executable - %s",
        searchPath, isValid, isExecutable));
    return;
  }

  BackgroundJobParameters parameters = getParameters(request, response);
  if (parameters == null) {
    return;
  }

  Job job = scriptRunnerJobManager.scheduleJob(parameters);
  ServletUtils.writeMessage(response, BACKGROUND_RESPONSE_TYPE, BACKGROUND_RESPONSE_TYPE, createMapWithJobIdKey(job));
}
 
Example 3
Source File: ScriptResultServlet.java    From APM with Apache License 2.0 6 votes vote down vote up
@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 4
Source File: SolrProxyServlet.java    From aem-solr-search with Apache License 2.0 6 votes vote down vote up
@Override
public String getTargetURI(SlingHttpServletRequest request) {

    final String searchHandler = (request.getParameter("qt") != null) ? request.getParameter("qt") : "/select";
    final String logicalCoreName = request.getParameter(CORE_NAME_PARAM);

    String core = logicalCoreName;

    // If we are in SolrCloud mode we just need to grab the first shard that matches the logical core name.
    if (solrConfigurationService.isCloudMode()) {
        List<String> shards = solrConfigurationService.fetchCollectionShards();
        for (String shard: shards) {
            if (shard.startsWith(logicalCoreName)) {
                core = shard;
                break;
            }
        }
    }

    // TODO: When in SolrCloud mode dynamically find and active node

    final String targetUri = solrConfigurationService.getSolrEndPoint() + "/" + core + searchHandler;

    LOG.debug("Using '{}' for proxy search", targetUri);
    return targetUri;
}
 
Example 5
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 6
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 7
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 8
Source File: ScriptRunBackgroundServlet.java    From APM with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
    throws IOException {
  final String id = request.getParameter(ID_REQUEST_PARAMETER);
  if (id == null) {
    return;
  }
  JobProgressOutput jobProgressOutput = scriptRunnerJobManager.checkJobStatus(id);
  ServletUtils.writeJson(response, jobProgressOutput);
}
 
Example 9
Source File: HistoryListServlet.java    From APM with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
    throws IOException {

  String filter = request.getParameter("filter");
  List<HistoryEntry> executions = history.findAllHistoryEntries(request.getResourceResolver());
  if (StringUtils.isNotBlank(filter)) {
    CollectionUtils.filter(executions, new ExecutionHistoryFilter(filter));
  }
  ServletUtils.writeJson(response, executions);
}
 
Example 10
Source File: RedirectFilter.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    if(request instanceof SlingHttpServletRequest) {
        final SlingHttpServletRequest sr = (SlingHttpServletRequest)request;
        if(sr.getMethod().equals(ResourceSchemasConstants.POST_METHOD) && sr.getParameter(ResourceSchemasConstants.SRS_FORM_MARKER_PARAMETER) != null) {
            response = new ResponseWrapper((SlingHttpServletResponse)response);
        }
    }
    chain.doFilter(request, response);
}
 
Example 11
Source File: CommentPostServlet.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 title = request.getParameter(CommentsUtil.PROPERTY_TITLE);
    final String text = request.getParameter(CommentsUtil.PROPERTY_TEXT);

    final String userId = request.getRemoteUser();

    logger.debug("New comment from {} : {} - {}", new Object[] {userId, title, text});
    // TODO - check values

    // save comment
    ResourceResolver resolver = null;
    try {
        resolver = factory.getServiceResourceResolver(null);

        final Resource reqResource = resolver.getResource(request.getResource().getPath());

        final Comment c = new Comment();
        c.setTitle(title);
        c.setText(text);
        c.setCreatedBy(userId);

        this.commentsService.addComment(reqResource, c);


        // send redirect at the end
        final String path = request.getResource().getPath();

        response.sendRedirect(resolver.map(request.getContextPath() + path + ".html"));
    } catch ( final LoginException le ) {
        throw new ServletException("Unable to login", le);
    } finally {
        if ( resolver != null ) {
            resolver.close();
        }
    }
}
 
Example 12
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 13
Source File: PageTypeRenderConditionServlet.java    From aem-core-cif-components with Apache License 2.0 5 votes vote down vote up
private boolean checkPageType(SlingHttpServletRequest slingRequest, String pageType) {
    if (StringUtils.isBlank(pageType)) {
        LOGGER.error("{} property is not defined at {}", PAGE_TYPE_PROPERTY, slingRequest.getResource().getPath());
        return false;
    }

    // the caller is a page properties dialog
    if (!StringUtils.contains(slingRequest.getPathInfo(), PAGE_PROPERTIES)) {
        return false;
    }

    PageManager pageManager = slingRequest.getResourceResolver().adaptTo(PageManager.class);
    // the page path is in the "item" request parameter
    String pagePath = slingRequest.getParameter("item");
    Page page = pageManager.getPage(pagePath);
    if (page == null) {
        return false;
    }

    Page parentPage = page.getParent();
    if (parentPage == null) {
        return false;
    }

    // perform the appropriate checks according to the pageType property
    if (PAGE_TYPE_PRODUCT.equals(pageType)) {
        Page productPage = SiteNavigation.getProductPage(page);
        return productPage != null && productPage.getPath().equals(parentPage.getPath());
    } else if (PAGE_TYPE_CATEGORY.equals(pageType)) {
        Page categoryPage = SiteNavigation.getCategoryPage(page);
        return categoryPage != null && categoryPage.getPath().equals(parentPage.getPath());
    }

    return false;
}
 
Example 14
Source File: GraphqlServlet.java    From aem-core-cif-components with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
    String query = request.getParameter(QUERY_PARAMETER);
    String operationName = request.getParameter(OPERATION_NAME_PARAMETER);
    String variables = request.getParameter(VARIABLES_PARAMETER);

    Map<String, Object> vars = null;
    if (StringUtils.isNotBlank(variables)) {
        Type type = TypeToken.getParameterized(Map.class, String.class, Object.class).getType();
        vars = gson.fromJson(variables, type);
    }

    ExecutionResult executionResult = execute(query, operationName, vars);
    writeResponse(executionResult, response);
}
 
Example 15
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 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.");
    }
}
 
Example 17
Source File: GraphqlProductViewHandler.java    From commerce-cif-connector with Apache License 2.0 4 votes vote down vote up
@Override
protected ViewQuery createQuery(SlingHttpServletRequest request,
    Session session, String queryString) throws RepositoryException {

    queryString = preserveWildcards(queryString);

    PredicateGroup gqlPredicateGroup = PredicateConverter.createPredicatesFromGQL(queryString);
    ResourceResolver resolver = request.getResourceResolver();
    tagManager = resolver.adaptTo(TagManager.class);
    Set<String> predicateSet = customizePredicateGroup(gqlPredicateGroup);

    // set default start path
    RequestPathInfo pathInfo = request.getRequestPathInfo();
    CommerceBasePathsService cbps = resolver.adaptTo(CommerceBasePathsService.class);
    String defaultStartPath = cbps.getProductsBasePath();
    String startPath = (pathInfo.getSuffix() != null && pathInfo.getSuffix().startsWith(defaultStartPath)) ? pathInfo.getSuffix()
        : defaultStartPath;
    if (!predicateSet.contains(PathPredicateEvaluator.PATH)) {
        gqlPredicateGroup.add(new Predicate(PathPredicateEvaluator.PATH).set(PathPredicateEvaluator.PATH, startPath));
    }

    String refererHeader = request.getHeader(REFERER_HEADER);
    if (StringUtils.isNotBlank(refererHeader) && refererHeader.contains(PAGE_EDITOR_PATH + "/")) {
        int p = refererHeader.lastIndexOf(PAGE_EDITOR_PATH);
        String pagePath = refererHeader.substring(p + PAGE_EDITOR_PATH.length());
        if (pagePath.endsWith(".html")) {
            pagePath = pagePath.substring(0, pagePath.length() - ".html".length());
        }

        CatalogSearchSupport catalogSearch = new CatalogSearchSupport(resolver);
        String catalogPath = catalogSearch.findCatalogPath(pagePath);
        String rootCategoryId = catalogSearch.findCategoryId(catalogPath);
        if (rootCategoryId != null) {
            gqlPredicateGroup.add(new Predicate(CATEGORY_ID_PARAMETER).set(CATEGORY_ID_PARAMETER, rootCategoryId));
            gqlPredicateGroup.add(new Predicate(CATEGORY_PATH_PARAMETER).set(CATEGORY_PATH_PARAMETER, catalogPath));
        }
    } else {
        LOGGER.warn("The path of the edited page cannot be determined");
    }

    // append node type constraint to match product data index /etc/commerce/oak:index/commerce
    gqlPredicateGroup.add(new Predicate(TypePredicateEvaluator.TYPE).set(TypePredicateEvaluator.TYPE, NT_UNSTRUCTURED));

    // append limit constraint
    if (gqlPredicateGroup.get(Predicate.PARAM_LIMIT) == null) {
        String limit = request.getParameter(LIMIT);
        if ((limit != null) && (!limit.equals(""))) {
            int offset = Integer.parseInt(StringUtils.substringBefore(limit, ".."));
            int total = Integer.parseInt(StringUtils.substringAfter(limit, ".."));
            gqlPredicateGroup.set(Predicate.PARAM_LIMIT, Long.toString(total - offset));
            gqlPredicateGroup.set(Predicate.PARAM_OFFSET, Long.toString(offset));
        } else {
            gqlPredicateGroup.set(Predicate.PARAM_LIMIT, Long.toString(DEFAULT_LIMIT));
        }
    }
    // add product property constraint
    addProductConstraint(gqlPredicateGroup);

    // append order constraint
    if (!predicateSet.contains(Predicate.ORDER_BY)) {
        gqlPredicateGroup.add(new Predicate(Predicate.ORDER_BY)
            .set(Predicate.ORDER_BY, "@" + JCR_LASTMODIFIED)
            .set(Predicate.PARAM_SORT, Predicate.SORT_DESCENDING));
    }

    return new GQLViewQuery(resolver, omniSearchHandler, xssAPI, gqlPredicateGroup);
}
 
Example 18
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 19
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());
}
 
Example 20
Source File: SolrBulkUpdateHandler.java    From aem-solr-search with Apache License 2.0 2 votes vote down vote up
/**
 * Obtains the sling:resourceType from the request.
 *
 * @param request
 * @return the sling:resourceType on success and an empty string otherwise.
 */
protected String getSlingResourceType(SlingHttpServletRequest request) {

    final Map requestMap = request.getParameterMap();
    return requestMap.containsKey(REQ_PARAM_TYPE) ? request.getParameter(REQ_PARAM_TYPE) : "";
}