org.apache.commons.lang.CharEncoding Java Examples

The following examples show how to use org.apache.commons.lang.CharEncoding. 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: MailService.java    From flair-engine with Apache License 2.0 7 votes vote down vote up
@Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
    log.debug("Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
        isMultipart, isHtml, to, subject, content);

    // Prepare message using a Spring helper
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, CharEncoding.UTF_8);
        message.setTo(to);
        message.setFrom(jHipsterProperties.getMail().getFrom());
        message.setSubject(subject);
        message.setText(content, isHtml);
        javaMailSender.send(mimeMessage);
        log.debug("Sent email to User '{}'", to);
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.warn("Email could not be sent to user '{}'", to, e);
        } else {
            log.warn("Email could not be sent to user '{}': {}", to, e.getMessage());
        }
    }
}
 
Example #2
Source File: MailService.java    From klask-io with GNU General Public License v3.0 6 votes vote down vote up
@Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
    log.debug("Send e-mail[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
        isMultipart, isHtml, to, subject, content);

    // Prepare message using a Spring helper
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, CharEncoding.UTF_8);
        message.setTo(to);
        message.setFrom(jHipsterProperties.getMail().getFrom());
        message.setSubject(subject);
        message.setText(content, isHtml);
        javaMailSender.send(mimeMessage);
        log.debug("Sent e-mail to User '{}'", to);
    } catch (Exception e) {
        log.warn("E-mail could not be sent to user '{}', exception is: {}", to, e.getMessage());
    }
}
 
Example #3
Source File: MailService.java    From expper with GNU General Public License v3.0 6 votes vote down vote up
@Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
    log.debug("Send e-mail[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
        isMultipart, isHtml, to, subject, content);

    // Prepare message using a Spring helper
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, CharEncoding.UTF_8);
        message.setTo(to);
        message.setFrom(jHipsterProperties.getMailgun().getFrom());
        message.setSubject(subject);
        message.setText(content, isHtml);
        javaMailSender.send(mimeMessage);
        log.debug("Sent e-mail to User '{}'", to);
    } catch (Exception e) {
        log.warn("E-mail could not be sent to user '{}', exception is: {}", to, e.getMessage());
    }
}
 
Example #4
Source File: DcCoreUtils.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * Authorizationヘッダの内容をBasic認証のものとしてパースする.
 * @param authzHeaderValue Authorizationヘッダの内容
 * @return id, pwの2要素の文字列配列、またはパース失敗時はnull
 */
public static String[] parseBasicAuthzHeader(String authzHeaderValue) {
    if (authzHeaderValue == null || !authzHeaderValue.startsWith(AUTHZ_BASIC)) {
        return null;
    }
    try {
        // 認証スキーマ以外の部分を取得
        byte[] bytes = DcCoreUtils.decodeBase64Url(authzHeaderValue.substring(AUTHZ_BASIC.length()));
        String rawStr = new String(bytes, CharEncoding.UTF_8);
        int pos = rawStr.indexOf(":");
        // 認証トークンの値に「:」を含んでいない場合は認証エラーとする
        if (pos == -1) {
            return null;
        }
        String username = rawStr.substring(0, pos);
        String password = rawStr.substring(pos + 1);
        return new String[] {decodeUrlComp(username), decodeUrlComp(password) };
    } catch (UnsupportedEncodingException e) {
        return null;
    }
}
 
Example #5
Source File: MailService.java    From ServiceCutter with Apache License 2.0 6 votes vote down vote up
@Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
    log.debug("Send e-mail[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
            isMultipart, isHtml, to, subject, content);

    // Prepare message using a Spring helper
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, CharEncoding.UTF_8);
        message.setTo(to);
        message.setFrom(from);
        message.setSubject(subject);
        message.setText(content, isHtml);
        javaMailSender.send(mimeMessage);
        log.debug("Sent e-mail to User '{}'", to);
    } catch (Exception e) {
        log.warn("E-mail could not be sent to user '{}', exception is: {}", to, e.getMessage());
    }
}
 
Example #6
Source File: MailService.java    From angularjs-springboot-bookstore with MIT License 6 votes vote down vote up
@Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
    log.debug("Send e-mail[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
            isMultipart, isHtml, to, subject, content);

    // Prepare message using a Spring helper
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, CharEncoding.UTF_8);
        message.setTo(to);
        message.setFrom(from);
        message.setSubject(subject);
        message.setText(content, isHtml);
        javaMailSender.send(mimeMessage);
        log.debug("Sent e-mail to User '{}'", to);
    } catch (Exception e) {
        log.warn("E-mail could not be sent to user '{}', exception is: {}", to, e.getMessage());
    }
}
 
Example #7
Source File: MailService.java    From OpenIoE with Apache License 2.0 6 votes vote down vote up
@Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
    log.debug("Send e-mail[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
        isMultipart, isHtml, to, subject, content);

    // Prepare message using a Spring helper
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, CharEncoding.UTF_8);
        message.setTo(to);
        message.setFrom(jHipsterProperties.getMail().getFrom());
        message.setSubject(subject);
        message.setText(content, isHtml);
        javaMailSender.send(mimeMessage);
        log.debug("Sent e-mail to User '{}'", to);
    } catch (Exception e) {
        log.warn("E-mail could not be sent to user '{}', exception is: {}", to, e.getMessage());
    }
}
 
Example #8
Source File: MailService.java    From gpmr with Apache License 2.0 6 votes vote down vote up
@Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
    log.debug("Send e-mail[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
        isMultipart, isHtml, to, subject, content);

    // Prepare message using a Spring helper
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, CharEncoding.UTF_8);
        message.setTo(to);
        message.setFrom(jHipsterProperties.getMail().getFrom());
        message.setSubject(subject);
        message.setText(content, isHtml);
        javaMailSender.send(mimeMessage);
        log.debug("Sent e-mail to User '{}'", to);
    } catch (Exception e) {
        log.warn("E-mail could not be sent to user '{}', exception is: {}", to, e.getMessage());
    }
}
 
Example #9
Source File: _MailService.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 6 votes vote down vote up
@Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
    log.debug("Send e-mail[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
        isMultipart, isHtml, to, subject, content);

    // Prepare message using a Spring helper
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, CharEncoding.UTF_8);
        message.setTo(to);
        message.setFrom(jHipsterProperties.getMail().getFrom());
        message.setSubject(subject);
        message.setText(content, isHtml);
        javaMailSender.send(mimeMessage);
        log.debug("Sent e-mail to User '{}'", to);
    } catch (Exception e) {
        log.warn("E-mail could not be sent to user '{}', exception is: {}", to, e.getMessage());
    }
}
 
Example #10
Source File: MailService.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 6 votes vote down vote up
@Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
    log.debug("Send e-mail[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
        isMultipart, isHtml, to, subject, content);

    // Prepare message using a Spring helper
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, CharEncoding.UTF_8);
        message.setTo(to);
        message.setFrom(jHipsterProperties.getMail().getFrom());
        message.setSubject(subject);
        message.setText(content, isHtml);
        javaMailSender.send(mimeMessage);
        log.debug("Sent e-mail to User '{}'", to);
    } catch (Exception e) {
        log.warn("E-mail could not be sent to user '{}', exception is: {}", to, e.getMessage());
    }
}
 
Example #11
Source File: ErrorHtmlResource.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * returns HTML string for error code.
 * @param code message code
 * @return HTML string
 */
private String htmlForCode(String code) {
    String title = DcCoreMessageUtils.getMessage("PS-ER-0001");
    String msg = null;
    try {
        msg = DcCoreMessageUtils.getMessage(code);
    } catch (Exception e) {
        log.info(e.getMessage());
        msg = DcCoreMessageUtils.getMessage("PS-ER-0002");
    }

    String html = DcCoreUtils.readStringResource("html/error.html", CharEncoding.UTF_8);
    html = MessageFormat.format(html, title, msg);
    return html;
}
 
Example #12
Source File: TransCellAccessToken.java    From io with Apache License 2.0 5 votes vote down vote up
@Override
public String toTokenString() {
    String samlStr = this.toSamlString();
    try {
        // Base64urlする
        String token = DcCoreUtils.encodeBase64Url(samlStr.getBytes(CharEncoding.UTF_8));
        return token;
    } catch (UnsupportedEncodingException e) {
        // UTF8が処理できないはずがない。
        throw new RuntimeException(e);
    }
}
 
Example #13
Source File: LocalToken.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * 文字列を暗号化する.
 * @param in 入力文字列
 * @param ivBytes イニシャルベクトル
 * @return 暗号化された文字列
 */
public static String encode(final String in, final byte[] ivBytes) {
    // IVに、発行CELLのURL逆順を入れることで、より短いトークンに。
    Cipher cipher;
    try {
        cipher = Cipher.getInstance(AES_CBC_PKCS5_PADDING);
        cipher.init(Cipher.ENCRYPT_MODE, aesKey, new IvParameterSpec(ivBytes));
        byte[] cipherBytes = cipher.doFinal(in.getBytes(CharEncoding.UTF_8));
        return DcCoreUtils.encodeBase64Url(cipherBytes);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}
 
Example #14
Source File: LocalToken.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * 指定のIssuer向けのIV(Initial Vector)を生成して返します.
 * IVとしてissuerの最後の最後の16文字を逆転させた文字列を用います。 これにより、違うIssuerを想定してパースすると、パースに失敗する。
 * @param issuer Issuer URL
 * @return Initial Vectorの Byte配列
 */
protected static byte[] getIvBytes(final String issuer) {
    try {
        return StringUtils.reverse("123456789abcdefg" + issuer)
                .substring(0, IV_BYTE_LENGTH).getBytes(CharEncoding.UTF_8);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}
 
Example #15
Source File: UnitLocalUnitUserToken.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * 指定のIssuer向けのIV(Initial Vector)を生成して返します.
 * IVとしてissuerの最初の16文字を用います。 これにより、違うIssuerを想定してパースすると、パースに失敗する。
 * @param issuer Issuer URL
 * @return Initial Vectorの Byte配列
 */
public static byte[] getIvBytes(final String issuer) {
    try {
        return (issuer + "123456789abcdefg")
                .substring(0, IV_BYTE_LENGTH).getBytes(CharEncoding.UTF_8);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}
 
Example #16
Source File: DcCoreUtils.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * basic認証ヘッダを生成して返します.
 * @param id id
 * @param pw pw
 * @return basic認証のヘッダ
 */
public static String createBasicAuthzHeader(final String id, final String pw) {
    String line = encodeUrlComp(id) + ":" + encodeUrlComp(pw);
    try {
        return encodeBase64Url(line.getBytes(CharEncoding.UTF_8));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}
 
Example #17
Source File: DcCoreUtils.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * URLエンコードのデコードを行う.
 * @param in Urlエンコードされた文字列
 * @return 元の文字列
 */
public static String decodeUrlComp(final String in) {
    try {
        return URLDecoder.decode(in, CharEncoding.UTF_8);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}
 
Example #18
Source File: DcCoreUtils.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * URLエンコードのエンコードを行う.
 * @param in Urlエンコードしたい文字列
 * @return Urlエンコードされた文字列
 */
public static String encodeUrlComp(final String in) {
    try {
        return URLEncoder.encode(in, CharEncoding.UTF_8);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}
 
Example #19
Source File: LocalStorageManager.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public String readFile(String subPath, boolean isProtectedResource) throws ApsSystemException {
	subPath = (null == subPath) ? "" : subPath;
	String fullPath = this.createFullPath(subPath, isProtectedResource);
	File file = new File(fullPath);
	try {
		return FileUtils.readFileToString(file, CharEncoding.UTF_8);
	} catch (Throwable t) {
		logger.error("Error reading File with path {}", subPath, t);
		throw new ApsSystemException("Error reading file", t);
	}
}
 
Example #20
Source File: ThymeleafConfiguration.java    From expper with GNU General Public License v3.0 5 votes vote down vote up
@Bean
@Description("Spring mail message resolver")
public MessageSource emailMessageSource() {
    log.info("loading non-reloadable mail messages resources");
    ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
    messageSource.setBasename("classpath:/mails/messages/messages");
    messageSource.setDefaultEncoding(CharEncoding.UTF_8);
    return messageSource;
}
 
Example #21
Source File: ICalendarSyncPoint.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void encodeAndTransmitResponse(HttpServletResponse httpServletResponse, Calendar calendar) throws Exception {
    httpServletResponse.setHeader("Content-Type", "text/calendar; charset=" + CharEncoding.UTF_8);

    final OutputStream outputStream = httpServletResponse.getOutputStream();
    outputStream.write(calendar.toString().getBytes(CharEncoding.UTF_8));
    outputStream.close();
}
 
Example #22
Source File: RestClientImpl.java    From verigreen with Apache License 2.0 5 votes vote down vote up
private void checkResponse(javax.ws.rs.core.Response response) throws RestClientException {
    
    if (response.getStatusInfo().getFamily() != Family.SUCCESSFUL) {
        String responseStr = "";
        try (Scanner scanner =
                new Scanner((InputStream) response.getEntity(), CharEncoding.UTF_8)) {
            responseStr = scanner.useDelimiter("\\A").next();
        }
        throw new RestClientException(String.format(
                "Failed : HTTP error code : %d response message: %s",
                response.getStatusInfo().getStatusCode(),
                responseStr), response.getStatusInfo().getStatusCode());
    }
}
 
Example #23
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 #24
Source File: LinkRewriterFilter.java    From publick-sling-blog with Apache License 2.0 5 votes vote down vote up
/**
 * Filter all GET requests for HTML pages.
 *
 * Wrap the request and convert the response to a String where we can pass
 * it to the Link Rewriter service.
 *
 * @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 String path = slingRequest.getPathInfo().toLowerCase();
    final String host = slingRequest.getServerName();
    final String method = slingRequest.getMethod();

    response.setCharacterEncoding(CharEncoding.UTF_8);

    if (linkRewriter != null && "GET".equals(method) && path.endsWith(".html")) {
        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);
        }

        String servletResponse = new String(responseWrapper.toString());

        out.write(linkRewriter.rewriteAllLinks(servletResponse, host));
    } else {
      chain.doFilter(request, response);
    }
}
 
Example #25
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 #26
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 #27
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 #28
Source File: ThymeleafConfiguration.java    From ServiceCutter with Apache License 2.0 5 votes vote down vote up
@Bean
@Description("Spring mail message resolver")
public MessageSource emailMessageSource() {
    log.info("loading non-reloadable mail messages resources");
    ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
    messageSource.setBasename("classpath:/mails/messages/messages");
    messageSource.setDefaultEncoding(CharEncoding.UTF_8);
    return messageSource;
}
 
Example #29
Source File: ThymeleafConfiguration.java    From angularjs-springboot-bookstore with MIT License 5 votes vote down vote up
@Bean
@Description("Spring mail message resolver")
public MessageSource emailMessageSource() {
    log.info("loading non-reloadable mail messages resources");
    ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
    messageSource.setBasename("classpath:/mails/messages/messages");
    messageSource.setDefaultEncoding(CharEncoding.UTF_8);
    return messageSource;
}
 
Example #30
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);
    }
}