org.apache.commons.codec.CharEncoding Java Examples

The following examples show how to use org.apache.commons.codec.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: MailServiceImpl.java    From cymbal with Apache License 2.0 6 votes vote down vote up
@Override
public void sendMail(final String title, final String content, final String[] to, final String[] cc,
        final boolean isHtml) {
    retryTemplate.execute(retryContext -> {
        try {
            MimeMessage message = sender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, CharEncoding.UTF_8);
            helper.setFrom(from);
            helper.setTo(to);
            if (cc != null && cc.length > 0) {
                helper.setCc(cc);
            }
            helper.setSubject(title);
            helper.setText(content, isHtml);
            sender.send(message);
            return null;
        } catch (MessagingException e) {
            throw new CymbalException(e);
        }
    }, retryContext -> {
        log.error("Send mail fail", retryContext.getLastThrowable());
        throw (CymbalException) retryContext.getLastThrowable();
    });
}
 
Example #2
Source File: DavRsCmp.java    From io with Apache License 2.0 6 votes vote down vote up
private static Element parseProp(String value) {
    // valをDOMでElement化
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = null;
    Document doc = null;
    try {
        builder = factory.newDocumentBuilder();
        ByteArrayInputStream is = new ByteArrayInputStream(value.getBytes(CharEncoding.UTF_8));
        doc = builder.parse(is);
    } catch (Exception e1) {
        throw DcCoreException.Dav.DAV_INCONSISTENCY_FOUND.reason(e1);
    }
    Element e = doc.getDocumentElement();
    return e;
}
 
Example #3
Source File: ConfigChannelSaltManagerFileSystemTest.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Tests storing a configuration file on the disk and contents of the init.sls.
 *
 * @throws Exception - if anything goes wrong
 */
public void testStoreConfigFile() throws Exception {
    ConfigChannel channel = ConfigChannelSaltManagerTestUtils.createTestChannel(user);
    ConfigChannelSaltManagerTestUtils.addFileToChannel(channel);

    manager.generateConfigChannelFiles(channel);

    File generatedFile = getGeneratedFile(channel,
            channel.getConfigFiles().first().getConfigFileName().getPath());
    assertTrue(generatedFile.exists());
    assertTrue(generatedFile.isFile());
    assertEquals("aoeuäö€üáóéúř", FileUtils.readFileToString(generatedFile, CharEncoding.UTF_8));

    File initSlsFile = getGeneratedFile(channel, "init.sls");
    initSlsAssertions(initSlsFile,
            "file.managed",
            generatedFile.getName());
}
 
Example #4
Source File: DavCmpEsImpl.java    From io with Apache License 2.0 6 votes vote down vote up
private Element parseProp(String value) {
    // valをDOMでElement化
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = null;
    Document doc = null;
    try {
        builder = factory.newDocumentBuilder();
        ByteArrayInputStream is = new ByteArrayInputStream(value.getBytes(CharEncoding.UTF_8));
        doc = builder.parse(is);
    } catch (Exception e1) {
        throw DcCoreException.Dav.DAV_INCONSISTENCY_FOUND.reason(e1);
    }
    Element e = doc.getDocumentElement();
    return e;
}
 
Example #5
Source File: JwtServiceTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private String generateHS256Token(String rawHeader, String rawPayload, String hmacSecret, boolean isValid,
        boolean isSigned) {
    try {
        logger.info("Generating token for " + rawHeader + " + " + rawPayload);

        String base64Header = Base64.encodeBase64URLSafeString(rawHeader.getBytes(CharEncoding.UTF_8));
        String base64Payload = Base64.encodeBase64URLSafeString(rawPayload.getBytes(CharEncoding.UTF_8));
        // TODO: Support valid/invalid manipulation

        final String body = base64Header + TOKEN_DELIMITER + base64Payload;

        String signature = generateHMAC(hmacSecret, body);

        return body + TOKEN_DELIMITER + signature;
    } catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) {
        final String errorMessage = "Could not generate the token";
        logger.error(errorMessage, e);
        fail(errorMessage);
        return null;
    }
}
 
Example #6
Source File: HttpRequestParserTest.java    From pxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testConvertToCaseInsensitiveMapUtf8() throws Exception {
    byte[] bytes = {
            (byte) 0x61, (byte) 0x32, (byte) 0x63, (byte) 0x5c, (byte) 0x22,
            (byte) 0x55, (byte) 0x54, (byte) 0x46, (byte) 0x38, (byte) 0x5f,
            (byte) 0xe8, (byte) 0xa8, (byte) 0x88, (byte) 0xe7, (byte) 0xae,
            (byte) 0x97, (byte) 0xe6, (byte) 0xa9, (byte) 0x9f, (byte) 0xe7,
            (byte) 0x94, (byte) 0xa8, (byte) 0xe8, (byte) 0xaa, (byte) 0x9e,
            (byte) 0x5f, (byte) 0x30, (byte) 0x30, (byte) 0x30, (byte) 0x30,
            (byte) 0x30, (byte) 0x30, (byte) 0x30, (byte) 0x30, (byte) 0x5c,
            (byte) 0x22, (byte) 0x6f, (byte) 0x35
    };
    String value = new String(bytes, CharEncoding.ISO_8859_1);

    MultivaluedMap<String, String> multivaluedMap = new MultivaluedMapImpl();
    multivaluedMap.put("one", Collections.singletonList(value));

    Map<String, String> caseInsensitiveMap = new HttpRequestParser.RequestMap(multivaluedMap);

    assertEquals("Only one key should have exist", caseInsensitiveMap.keySet().size(), 1);

    assertEquals("Value should be converted to UTF-8",
            caseInsensitiveMap.get("one"), "a2c\"UTF8_計算機用語_00000000\"o5");
}
 
Example #7
Source File: DavCmpFsImpl.java    From io with Apache License 2.0 6 votes vote down vote up
private Element parseProp(String value) {
    // valをDOMでElement化
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = null;
    Document doc = null;
    try {
        builder = factory.newDocumentBuilder();
        ByteArrayInputStream is = new ByteArrayInputStream(value.getBytes(CharEncoding.UTF_8));
        doc = builder.parse(is);
    } catch (Exception e1) {
        throw DcCoreException.Dav.DAV_INCONSISTENCY_FOUND.reason(e1);
    }
    Element e = doc.getDocumentElement();
    return e;
}
 
Example #8
Source File: BaseAction.java    From nettice with Apache License 2.0 6 votes vote down vote up
/**
 * 获取请求参数 Map
 */
private Map<String, List<String>> getParamMap(){
	Map<String, List<String>> paramMap = new HashMap<String, List<String>>();
	
	Object msg = DataHolder.getRequest();
	HttpRequest request = (HttpRequest) msg;
	HttpMethod method = request.method();
	if(method.equals(HttpMethod.GET)){
		String uri = request.uri();
		QueryStringDecoder queryDecoder = new QueryStringDecoder(uri, Charset.forName(CharEncoding.UTF_8));
		paramMap = queryDecoder.parameters();
		
	}else if(method.equals(HttpMethod.POST)){
		FullHttpRequest fullRequest = (FullHttpRequest) msg;
		paramMap = getPostParamMap(fullRequest);
	}
	
	return paramMap;
}
 
Example #9
Source File: JsonExportPlugin.java    From xiaoyaoji with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void doExport(String projectId, HttpServletResponse response) throws IOException {
    Project project = ProjectService.instance().getProject(projectId);
    AssertUtils.notNull(project,"项目不存在");
    JSONObject json = (JSONObject) JSON.toJSON(project);
    List<Doc> docs = ProjectService.instance().getProjectDocs(projectId, true);
    json.put(EXPORT_KEY_DOCS, docs);
    json.put(EXPORT_KEY_VER, getPluginInfo().getVersion());
    json.put(GLOBAL,ProjectService.instance().getProjectGlobal(projectId));
    String jsonStr = JsonUtils.toString(json);
    String encoding = Constants.UTF8.displayName();
    response.setCharacterEncoding(encoding);
    response.setContentType("application/json;charset="+encoding);
    PrintWriter writer = response.getWriter();
    response.setContentLength(jsonStr.getBytes().length);
    String fileName = URLEncoder.encode( project.getName(), Charset.forName(CharEncoding.UTF_8).displayName())+".mjson";
    response.setHeader("Content-Disposition","attachment; filename=\""+fileName+"\";");
    writer.write(jsonStr);
    writer.flush();
}
 
Example #10
Source File: MailUtil.java    From cymbal with Apache License 2.0 5 votes vote down vote up
public static String getOpsPlatformUrl(String clusterId) {
    StringBuffer url = new StringBuffer("http://ops.dangdang.com/#redis/page?");
    try {
        url.append("data=")
                .append(URLEncoder.encode(String.format("{\"clusterId\":\"%s\"}", clusterId), CharEncoding.UTF_8));
        url.append("&title=").append(URLEncoder.encode("[\"Redis管理主界面\",\"主机管理\",\"主机详情\"]", CharEncoding.UTF_8));
    } catch (UnsupportedEncodingException e) {
        log.error("fail to encode the url", e);
    }
    return url.toString();
}
 
Example #11
Source File: RestAccessDeniedHandler.java    From jakduk-api with MIT License 5 votes vote down vote up
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {

    response.setContentType(ContentType.APPLICATION_JSON.toString());
    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
    response.setCharacterEncoding(CharEncoding.UTF_8);

    RestErrorResponse restErrorResponse = new RestErrorResponse(ServiceError.UNAUTHORIZED_ACCESS);
    String errorJson = ObjectMapperUtils.getObjectMapper().writeValueAsString(restErrorResponse);

    PrintWriter out = response.getWriter();
    out.print(errorJson);
    out.flush();
    out.close();
}
 
Example #12
Source File: GrafanaDashboardServiceImpl.java    From cymbal with Apache License 2.0 5 votes vote down vote up
private void addDashboard(String dashboard) throws MonitorException {
    // format url
    String url = String.format("%s/%s", grafanaApiUrl, GrafanaDashboardServiceImpl.GRAFANA_ADD_DASHBOARD_URI);
    PostMethod method = new PostMethod(url);

    try {
        // request body
        method.setRequestEntity(new StringRequestEntity(dashboard, "application/json", CharEncoding.UTF_8));
        doHttpAPI(method);
    } catch (UnsupportedEncodingException e) {
        new MonitorException(e);
    }
}
 
Example #13
Source File: HttpHelloWorldServerHandler.java    From netty-learning-example with Apache License 2.0 4 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    User user = new User();
    user.setUserName("sanshengshui");
    user.setDate(new Date());

    if (msg instanceof HttpRequest){
        request = (HttpRequest) msg;
        headers = request.headers();
        String uri = request.uri();
        logger.info("http uri: "+ uri);
        if (uri.equals(FAVICON_ICO)){
            return;
        }
        HttpMethod method = request.method();
        if (method.equals(HttpMethod.GET)){
            QueryStringDecoder queryDecoder = new QueryStringDecoder(uri, Charsets.toCharset(CharEncoding.UTF_8));
            Map<String, List<String>> uriAttributes = queryDecoder.parameters();
            //此处仅打印请求参数(你可以根据业务需求自定义处理)
            for (Map.Entry<String, List<String>> attr : uriAttributes.entrySet()) {
                for (String attrVal : attr.getValue()) {
                    logger.info(attr.getKey() + "=" + attrVal);
                }
            }
            user.setMethod("get");
        }else if (method.equals(HttpMethod.POST)){
            //POST请求,由于你需要从消息体中获取数据,因此有必要把msg转换成FullHttpRequest
            fullRequest = (FullHttpRequest)msg;
            //根据不同的Content_Type处理body数据
            dealWithContentType();
            user.setMethod("post");

        }

        JSONSerializer jsonSerializer = new JSONSerializer();
        byte[] content = jsonSerializer.serialize(user);

        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(content));
        response.headers().set(CONTENT_TYPE, "text/plain");
        response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());

        boolean keepAlive = HttpUtil.isKeepAlive(request);
        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(CONNECTION, KEEP_ALIVE);
            ctx.write(response);
        }
    }
}
 
Example #14
Source File: URLCodec.java    From text_converter with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Default constructor.
 */
public URLCodec() {
    this(CharEncoding.UTF_8);
}
 
Example #15
Source File: AttachmentExportUtil.java    From myexcel with Apache License 2.0 4 votes vote down vote up
private static void setAttachmentConfig(String fileName, HttpServletResponse response) throws UnsupportedEncodingException {
    response.setCharacterEncoding(CharEncoding.UTF_8);
    response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, CharEncoding.UTF_8).replace("+", "%20"));
}
 
Example #16
Source File: URLCodec.java    From pivaa with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Default constructor.
 */
public URLCodec() {
    this(CharEncoding.UTF_8);
}
 
Example #17
Source File: ConfigChannelSaltManager.java    From uyuni with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Checks that the outFile is inside the channel directory and writes the contents to
 * it.
 *
 * @param content string to be written
 * @param channelDir the channel directory
 * @param outFile the output file
 * @throws IllegalArgumentException if there is an attempt to write file outside channel
 * directory
 * @throws IOException if there is an error when writing on the disk
 */
private void writeTextFile(String content, File channelDir, File outFile)
        throws IOException {
    assertStateInOrgDir(channelDir, outFile);
    outFile.getParentFile().mkdirs();
    FileUtils.writeStringToFile(outFile, content, CharEncoding.UTF_8);
 }
 
Example #18
Source File: StringUtils.java    From scim2-compliance-test-suite with Apache License 2.0 2 votes vote down vote up
/**
 * Constructs a new <code>String</code> by decoding the specified array of bytes using the UTF-16 charset.
 * 
 * @param bytes
 *            The bytes to be decoded into characters
 * @return A new <code>String</code> decoded from the specified array of bytes using the UTF-16 charset
 *         or <code>null</code> if the input byte array was <code>null</code>.
 * @throws IllegalStateException
 *             Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen since the
 *             charset is required.
 */
public static String newStringUtf16(byte[] bytes) {
    return StringUtils.newString(bytes, CharEncoding.UTF_16);
}
 
Example #19
Source File: StringUtils.java    From scim2-compliance-test-suite with Apache License 2.0 2 votes vote down vote up
/**
 * Constructs a new <code>String</code> by decoding the specified array of bytes using the UTF-8 charset.
 * 
 * @param bytes
 *            The bytes to be decoded into characters
 * @return A new <code>String</code> decoded from the specified array of bytes using the UTF-8 charset,
 *         or <code>null</code> if the input byte array was <code>null</code>.
 * @throws IllegalStateException
 *             Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen since the
 *             charset is required.
 */
public static String newStringUtf8(byte[] bytes) {
    return StringUtils.newString(bytes, CharEncoding.UTF_8);
}
 
Example #20
Source File: StringUtils.java    From scim2-compliance-test-suite with Apache License 2.0 2 votes vote down vote up
/**
 * Constructs a new <code>String</code> by decoding the specified array of bytes using the UTF-16LE charset.
 * 
 * @param bytes
 *            The bytes to be decoded into characters
 * @return A new <code>String</code> decoded from the specified array of bytes using the UTF-16LE charset,
 *         or <code>null</code> if the input byte array was <code>null</code>.
 * @throws IllegalStateException
 *             Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen since the
 *             charset is required.
 */
public static String newStringUtf16Le(byte[] bytes) {
    return StringUtils.newString(bytes, CharEncoding.UTF_16LE);
}
 
Example #21
Source File: StringUtils.java    From scim2-compliance-test-suite with Apache License 2.0 2 votes vote down vote up
/**
 * Constructs a new <code>String</code> by decoding the specified array of bytes using the UTF-16BE charset.
 * 
 * @param bytes
 *            The bytes to be decoded into characters
 * @return A new <code>String</code> decoded from the specified array of bytes using the UTF-16BE charset,
 *         or <code>null</code> if the input byte array was <code>null</code>.
 * @throws IllegalStateException
 *             Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen since the
 *             charset is required.
 */
public static String newStringUtf16Be(byte[] bytes) {
    return StringUtils.newString(bytes, CharEncoding.UTF_16BE);
}
 
Example #22
Source File: StringUtils.java    From scim2-compliance-test-suite with Apache License 2.0 2 votes vote down vote up
/**
 * Constructs a new <code>String</code> by decoding the specified array of bytes using the US-ASCII charset.
 * 
 * @param bytes
 *            The bytes to be decoded into characters
 * @return A new <code>String</code> decoded from the specified array of bytes using the US-ASCII charset,
 *         or <code>null</code> if the input byte array was <code>null</code>.
 * @throws IllegalStateException
 *             Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen since the
 *             charset is required.
 */
public static String newStringUsAscii(byte[] bytes) {
    return StringUtils.newString(bytes, CharEncoding.US_ASCII);
}
 
Example #23
Source File: StringUtils.java    From scim2-compliance-test-suite with Apache License 2.0 2 votes vote down vote up
/**
 * Constructs a new <code>String</code> by decoding the specified array of bytes using the ISO-8859-1 charset.
 * 
 * @param bytes
 *            The bytes to be decoded into characters, may be <code>null</code>
 * @return A new <code>String</code> decoded from the specified array of bytes using the ISO-8859-1 charset,
 *         or <code>null</code> if the input byte array was <code>null</code>.
 * @throws IllegalStateException
 *             Thrown when a {@link UnsupportedEncodingException} is caught, which should never happen since the
 *             charset is required.
 */
public static String newStringIso8859_1(byte[] bytes) {
    return StringUtils.newString(bytes, CharEncoding.ISO_8859_1);
}
 
Example #24
Source File: StringUtils.java    From scim2-compliance-test-suite with Apache License 2.0 2 votes vote down vote up
/**
 * Encodes the given string into a sequence of bytes using the UTF-8 charset, storing the result into a new byte
 * array.
 * 
 * @param string
 *            the String to encode, may be <code>null</code>
 * @return encoded bytes, or <code>null</code> if the input string was <code>null</code>
 * @throws IllegalStateException
 *             Thrown when the charset is missing, which should be never according the the Java specification.
 * @see <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
 * @see #getBytesUnchecked(String, String)
 */
public static byte[] getBytesUtf8(String string) {
    return StringUtils.getBytesUnchecked(string, CharEncoding.UTF_8);
}
 
Example #25
Source File: StringUtils.java    From scim2-compliance-test-suite with Apache License 2.0 2 votes vote down vote up
/**
 * Encodes the given string into a sequence of bytes using the UTF-16LE charset, storing the result into a new byte
 * array.
 * 
 * @param string
 *            the String to encode, may be <code>null</code>
 * @return encoded bytes, or <code>null</code> if the input string was <code>null</code>
 * @throws IllegalStateException
 *             Thrown when the charset is missing, which should be never according the the Java specification.
 * @see <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
 * @see #getBytesUnchecked(String, String)
 */
public static byte[] getBytesUtf16Le(String string) {
    return StringUtils.getBytesUnchecked(string, CharEncoding.UTF_16LE);
}
 
Example #26
Source File: StringUtils.java    From scim2-compliance-test-suite with Apache License 2.0 2 votes vote down vote up
/**
 * Encodes the given string into a sequence of bytes using the UTF-16BE charset, storing the result into a new byte
 * array.
 * 
 * @param string
 *            the String to encode, may be <code>null</code>
 * @return encoded bytes, or <code>null</code> if the input string was <code>null</code>
 * @throws IllegalStateException
 *             Thrown when the charset is missing, which should be never according the the Java specification.
 * @see <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
 * @see #getBytesUnchecked(String, String)
 */
public static byte[] getBytesUtf16Be(String string) {
    return StringUtils.getBytesUnchecked(string, CharEncoding.UTF_16BE);
}
 
Example #27
Source File: StringUtils.java    From scim2-compliance-test-suite with Apache License 2.0 2 votes vote down vote up
/**
 * Encodes the given string into a sequence of bytes using the UTF-16 charset, storing the result into a new byte
 * array.
 * 
 * @param string
 *            the String to encode, may be <code>null</code>
 * @return encoded bytes, or <code>null</code> if the input string was <code>null</code>
 * @throws IllegalStateException
 *             Thrown when the charset is missing, which should be never according the the Java specification.
 * @see <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
 * @see #getBytesUnchecked(String, String)
 */
public static byte[] getBytesUtf16(String string) {
    return StringUtils.getBytesUnchecked(string, CharEncoding.UTF_16);
}
 
Example #28
Source File: StringUtils.java    From scim2-compliance-test-suite with Apache License 2.0 2 votes vote down vote up
/**
 * Encodes the given string into a sequence of bytes using the US-ASCII charset, storing the result into a new byte
 * array.
 * 
 * @param string
 *            the String to encode, may be <code>null</code>
 * @return encoded bytes, or <code>null</code> if the input string was <code>null</code>
 * @throws IllegalStateException
 *             Thrown when the charset is missing, which should be never according the the Java specification.
 * @see <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
 * @see #getBytesUnchecked(String, String)
 */
public static byte[] getBytesUsAscii(String string) {
    return StringUtils.getBytesUnchecked(string, CharEncoding.US_ASCII);
}
 
Example #29
Source File: StringUtils.java    From scim2-compliance-test-suite with Apache License 2.0 2 votes vote down vote up
/**
 * Encodes the given string into a sequence of bytes using the ISO-8859-1 charset, storing the result into a new
 * byte array.
 * 
 * @param string
 *            the String to encode, may be <code>null</code>
 * @return encoded bytes, or <code>null</code> if the input string was <code>null</code>
 * @throws IllegalStateException
 *             Thrown when the charset is missing, which should be never according the the Java specification.
 * @see <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/nio/charset/Charset.html">Standard charsets</a>
 * @see #getBytesUnchecked(String, String)
 */
public static byte[] getBytesIso8859_1(String string) {
    return StringUtils.getBytesUnchecked(string, CharEncoding.ISO_8859_1);
}