下面列出了怎么用org.apache.commons.lang.CharEncoding的API类实例代码及写法,或者点击链接到github查看源代码。
@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());
}
}
}
@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());
}
}
@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());
}
}
@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());
}
}
@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());
}
}
@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());
}
}
@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());
}
}
@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());
}
}
@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());
}
}
/**
* 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;
}
}
@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;
}
@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;
}
/**
* 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);
}
}
/**
* 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);
}
}
/**
* 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.");
}
}
/**
* 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);
}
}
/**
* 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);
}
}
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());
}
}
@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;
}
@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);
}
}
/**
* 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);
}
}
/**
* 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);
}
}
/**
* 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);
}
}
/**
* 指定の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);
}
}
/**
* 指定の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);
}
}
/**
* 文字列を暗号化する.
* @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);
}
}
@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);
}
}
/**
* 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;
}
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();
}
/**
* 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.");
}
}