类org.apache.commons.lang3.CharEncoding源码实例Demo

下面列出了怎么用org.apache.commons.lang3.CharEncoding的API类实例代码及写法,或者点击链接到github查看源代码。

@Test(groups = "wso2.esb", description = "Enrich / Payload Factory mediators,soap namespace is added when soap is not in use")
public void testEnrichNamespaceAdditionTestCase() throws Exception {

    String endpoint = getApiInvocationURL(API_NAME) + "/test_with_pf";
    String requestXml = "<MetaData><DateTimeSent/></MetaData>";
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(endpoint);
    httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/xml;charset=UTF-8");
    HttpEntity stringEntity = new StringEntity(requestXml, CharEncoding.UTF_8);
    httpPost.setEntity(stringEntity);
    HttpResponse response = httpclient.execute(httpPost);
    HttpEntity resEntity = response.getEntity();

    BufferedReader rd = new BufferedReader(new InputStreamReader(resEntity.getContent()));
    String result = "";
    String line;
    while ((line = rd.readLine()) != null) {
        result += line;
    }
    Assert.assertTrue(!result.contains("http://schemas.xmlsoap.org/soap/envelope/"),
            "unnessary namespaces present in message");
}
 
源代码2 项目: cubeai   文件: MailService.java
@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 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());
        }
    }
}
 
源代码4 项目: scava   文件: MailService.java
@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(from);
        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());
        }
    }
}
 
源代码5 项目: httpkit   文件: BaseController.java
/**
 * 输出某个字符流的内容,一般是用作页面渲染(支持jar包内置内容输出)<br>
 * @author nan.li
 * @param inputStream
 */
public void okCharStream(InputStream inputStream)
{
    try
    {
        String content = IOUtils.toString(inputStream, CharEncoding.UTF_8);
        okHtml(content);
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    finally
    {
        StreamUtils.close(inputStream);
    }
}
 
源代码6 项目: httpkit   文件: HttpReader.java
public HttpReader(InputStream in)
    throws UnsupportedEncodingException
{
    this.in = in;
    this.reader = new BufferedReader(new InputStreamReader(in, CharEncoding.UTF_8));
    //依次从头读到尾
    //1.读消息签名
    if (readSignatureFully())
    {
        //2.读消息头
        if (readHeadersFully())
        {
            //3.读消息体
            if (readBodyFully())
            {
                //解析其他的额外信息 
                resolveExtraInfo();
            }
        }
    }
}
 
@Test(groups = "wso2.esb", description = "Enrich / Payload Factory mediators,soap namespace is added when soap is not in use")
public void testEnrichNamespaceAdditionTestCase() throws Exception {

    String endpoint = getApiInvocationURL(API_NAME) + "/test_with_pf";
    String requestXml = "<MetaData><DateTimeSent/></MetaData>";
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(endpoint);
    httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/xml;charset=UTF-8");
    HttpEntity stringEntity = new StringEntity(requestXml, CharEncoding.UTF_8);
    httpPost.setEntity(stringEntity);
    HttpResponse response = httpclient.execute(httpPost);
    HttpEntity resEntity = response.getEntity();

    BufferedReader rd = new BufferedReader(new InputStreamReader(resEntity.getContent()));
    String result = "";
    String line;
    while ((line = rd.readLine()) != null) {
        result += line;
    }
    Assert.assertTrue(!result.contains("http://schemas.xmlsoap.org/soap/envelope/") , "unnessary namespaces present in message");
}
 
源代码8 项目: payment   文件: WeixinJSApiPaymentService.java
private Map<String, String> generatePaymentForm(BillingData bill) {
    Assert.isNotNull(bill);
    logger.debug("[billing data : \n {} ]", bill);
    WechatPrepayResponseDto prepayResponse = prepay(bill);
    Assert.isNotNull(prepayResponse);

    String nonceStr = ValidateCode.randomCode(10);
    String timeStamp = String.valueOf(new Date().getTime() / 1000);

    //@TODO extract sign logic
    Map<String, String> parmameters = new TreeMap<>();
    parmameters.put("appId", prepayResponse.getAppId());
    parmameters.put("timeStamp", timeStamp);
    parmameters.put("nonceStr", nonceStr);
    parmameters.put("package", "prepay_id=" + prepayResponse.getPrepay_id());
    parmameters.put("signType", "MD5");

    String param_str = ParamUtils.buildParams(parmameters) + "&key=" + prepayResponse.getSecurityKey();
    String paySign = MD5Util.MD5Encode(param_str, CharEncoding.UTF_8).toUpperCase();
    parmameters.put("paySign", paySign);
    return parmameters;
}
 
源代码9 项目: livingdoc-core   文件: ClientUtils.java
/**
 * @param separator
 * @param args
 * @return
 * @throws UnsupportedEncodingException
 */
public static String encodeToBase64(final String separator, final String... args) throws UnsupportedEncodingException {

    // TODO Since Java 8 it can be used: java.util.Base64.getEncoder().encodeToString(string);

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < args.length; ++i) {
        sb.append(args[i]);
        if (i != (args.length - 1) && separator != null) {
            sb.append(separator);
        }
    }

    return DatatypeConverter.printBase64Binary((sb.toString()).getBytes(CharEncoding.UTF_8));

}
 
源代码10 项目: tutorials   文件: MailService.java
@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 '{}'", to, e);
    }
}
 
源代码11 项目: tutorials   文件: MailService.java
@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 '{}'", to, e);
    }
}
 
@Test(groups = "wso2.esb", description = "Tests Enrich Source OM Property without clone")
public void testEnrichSourceTypePropertyAndCloneFalse() throws Exception {

    String endpoint = getProxyServiceURLHttp(PROXY_NAME);

    String requestXml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
            + "   <soapenv:Header/>\n" + "   <soapenv:Body>\n" + "      <payload>\n" + "         <content>\n"
            + "            <abc>\n" + "               <def>123</def>\n" + "            </abc>\n"
            + "         </content>\n" + "      </payload>\n" + "   </soapenv:Body>\n" + "</soapenv:Envelope>";

    DefaultHttpClient httpclient = new DefaultHttpClient();

    HttpPost httpPost = new HttpPost(endpoint);
    httpPost.addHeader("SOAPAction", "\"urn:mediate\"");
    httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "text/xml;charset=UTF-8");
    HttpEntity stringEntity = new StringEntity(requestXml, CharEncoding.UTF_8);
    httpPost.setEntity(stringEntity);
    HttpResponse response = httpclient.execute(httpPost);
    HttpEntity resEntity = response.getEntity();

    BufferedReader rd = new BufferedReader(new InputStreamReader(resEntity.getContent()));
    String result = "";
    String line;
    while ((line = rd.readLine()) != null) {
        result += line;
    }
    Assert.assertTrue(!result.contains("payload"));
}
 
源代码13 项目: httpkit   文件: HttpServer.java
/**
 * 自适应加载过滤器配置类列表<br>
 * 首先尝试从配置文件:filters.cfg中加载,若无配置文件,则使用系统内置的默认的过滤器列表
 * @return
 */
public CtrlFilterChain initFilterConfigs()
{
    try
    {
        List<String> classNameList = null;
        if (getClass().getClassLoader().getResource(Constants.FILTERS_CFG_PATH) != null)
        {
            Logs.i("开始加载Http Filter配置文件:" + Constants.FILTERS_CFG_PATH);
            classNameList = IOUtils.readLines(getClass().getClassLoader().getResourceAsStream(Constants.FILTERS_CFG_PATH), CharEncoding.UTF_8);
        }
        else
        {
            Logs.i("未发现Http Filter配置文件,将采用默认的过滤器配置!");
            classNameList = new ArrayList<>();
            //以下是内置的默认过滤器列表
            
            //跨域过滤器
            classNameList.add("com.lnwazg.httpkit.filter.common.CORSFilter");
        }
        return initFilterConfigs(classNameList);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    return null;
}
 
源代码14 项目: wenku   文件: FileUtils.java
/**
 * 写入内容到文件
 * @param fileName 完整文件路径,包括文件名
 * @param fileContent 写入的内容
 */
public static void writeFile(String fileName, String fileContent) {
    try {
        File f = new File(fileName);
        if (!f.exists()) {
            f.createNewFile();
        }
        IOUtils.write(fileContent, new FileOutputStream(f), CharEncoding.UTF_8);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
@Test(groups = "wso2.esb", description = "Tests Enrich Source OM Property without clone")
public void testEnrichSourceTypePropertyAndCloneFalse() throws Exception {

    String endpoint = getProxyServiceURLHttp(PROXY_NAME);

    String requestXml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
            "   <soapenv:Header/>\n" +
            "   <soapenv:Body>\n" +
            "      <payload>\n" +
            "         <content>\n" +
            "            <abc>\n" +
            "               <def>123</def>\n" +
            "            </abc>\n" +
            "         </content>\n" +
            "      </payload>\n" +
            "   </soapenv:Body>\n" +
            "</soapenv:Envelope>";

    DefaultHttpClient httpclient = new DefaultHttpClient();

    HttpPost httpPost = new HttpPost(endpoint);
    httpPost.addHeader("SOAPAction", "\"urn:mediate\"");
    httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "text/xml;charset=UTF-8");
    HttpEntity stringEntity = new StringEntity(requestXml, CharEncoding.UTF_8);
    httpPost.setEntity(stringEntity);
    HttpResponse response = httpclient.execute(httpPost);
    HttpEntity resEntity = response.getEntity();

    BufferedReader rd = new BufferedReader(new InputStreamReader(resEntity.getContent()));
    String result = "";
    String line;
    while ((line = rd.readLine()) != null) {
        result += line;
    }
    Assert.assertTrue(!result.contains("payload"));
}
 
源代码16 项目: livingdoc-core   文件: ClientUtils.java
/**
 * Returns an array with decoded elements from a string in base64.
 *
 * @param base64String
 * @param separator
 * @return
 * @throws UnsupportedEncodingException
 */
public static String[] decodeFromBase64(final String base64String, final String separator) throws UnsupportedEncodingException {

    // TODO Since Java 8 it can be used: java.util.Base64.getDecoder().decode(base64String);

    byte[] bytes = DatatypeConverter.parseBase64Binary(base64String);
    String decodedAuthorization = new String(bytes, CharEncoding.UTF_8);
    return separator != null ? decodedAuthorization.split(separator) : new String[]{decodedAuthorization};
}
 
源代码17 项目: herd   文件: HerdJmsMessageListener.java
/**
 * Process the message as S3 notification.
 *
 * @param payload the JMS message payload.
 *
 * @return boolean whether message was processed.
 */
private boolean processS3Notification(String payload)
{
    boolean messageProcessed = false;

    try
    {
        // Process messages coming from S3 bucket.
        S3EventNotification s3EventNotification = S3EventNotification.parseJson(payload);
        String objectKey = URLDecoder.decode(s3EventNotification.getRecords().get(0).getS3().getObject().getKey(), CharEncoding.UTF_8);

        // Perform the complete upload single file.
        CompleteUploadSingleMessageResult completeUploadSingleMessageResult = uploadDownloadService.performCompleteUploadSingleMessage(objectKey);

        if (LOGGER.isDebugEnabled())
        {
            LOGGER.debug("completeUploadSingleMessageResult={}", jsonHelper.objectToJson(completeUploadSingleMessageResult));
        }

        messageProcessed = true;
    }
    catch (RuntimeException | UnsupportedEncodingException e)
    {
        // The logging is set to DEBUG level, since the method is expected to fail when message is not of the expected type.
        LOGGER.debug("Failed to process message from the JMS queue for an S3 notification. jmsQueueName=\"{}\" jmsMessagePayload={}",
            HerdJmsDestinationResolver.SQS_DESTINATION_HERD_INCOMING, payload, e);
    }

    return messageProcessed;
}
 
源代码18 项目: attic-apex-malhar   文件: LogParser.java
@Override
public void setup(Context.OperatorContext context)
{
  objMapper = new ObjectMapper();
  encoding = encoding != null ? encoding : CharEncoding.UTF_8;
  setupLog();
}
 
源代码19 项目: micro-integrator   文件: ESBJAVA4318Testcase.java
@Test(groups = "wso2.esb", description = "cache meditor with payloads including Processing Insturctions")
public void testCacheMediatorWithPIs() throws Exception {

    String requestXml =
            "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://services.samples\" xmlns:xsd=\"http://services.samples/xsd\">\n"
                    + "   <soapenv:Header>\n"
                    + "      <m:Trans xmlns:m=\"http://www.w3schools.com/transaction/\">234</m:Trans>\n"
                    + "   </soapenv:Header>\n" + "   <soapenv:Body>\n" + "      <ser:getFullQuote>\n"
                    + "         <ser:request>\n" + "            <xsd:symbol>IBM</xsd:symbol>\n"
                    + "         </ser:request>\n" + "      </ser:getFullQuote>\n" + "   </soapenv:Body>\n"
                    + "</soapenv:Envelope>";

    final String expectedValue = "<?xml version='1.0' encoding='UTF-8'?><soapenv:Envelope "
            + "xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"><soapenv:Body><b xmlns=\"http://ws"
            + ".apache.org/ns/synapse\"><?xml-multiple  array?><xyz><a xmlns=\"\">after "
            + "cache</a></xyz></b></soapenv:Body></soapenv:Envelope>";

    DefaultHttpClient httpclient = new DefaultHttpClient();

    // this is to populate the cache mediator
    HttpPost httpPost = new HttpPost(getProxyServiceURLHttp("PF"));
    httpPost.addHeader("SOAPAction", "urn:getFullQuote");
    httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "text/xml;charset=UTF-8");
    HttpEntity stringEntity = new StringEntity(requestXml, CharEncoding.UTF_8);
    httpPost.setEntity(stringEntity);
    HttpResponse response = httpclient.execute(httpPost);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    response.getEntity().writeTo(baos);
    String actualValue = baos.toString();

    // this is to get the actual cache response
    HttpPost httpPost2 = new HttpPost(getProxyServiceURLHttp("PF"));
    httpPost2.addHeader("SOAPAction", "urn:getFullQuote");
    httpPost2.setHeader(HttpHeaders.CONTENT_TYPE, "text/xml;charset=UTF-8");
    HttpEntity stringEntity2 = new StringEntity(requestXml, CharEncoding.UTF_8);
    httpPost2.setEntity(stringEntity2);
    HttpResponse response2 = httpclient.execute(httpPost);

    ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
    response2.getEntity().writeTo(baos2);
    String actualValue2 = baos2.toString();
    Assert.assertEquals(actualValue2, expectedValue);
}
 
源代码20 项目: httpkit   文件: RenderUtils.java
/**
 * 渲染ftl文件
 * @author nan.li
 * @param ioInfo
 * @param code
 * @param basePath      /root/web/
 * @param resourcePath  static/
 * @param subPath       page/index.ftl
 * @param extraParamMap 额外的参数表
 */
public static void renderFtl(IOInfo ioInfo, HttpResponseCode code, String basePath, String resourcePath, String subPath, Map<String, Object> extraParamMap)
{
    //获取Freemarker配置对象
    String key = basePath;
    if (!configureMap.containsKey(key))
    {
        configureMap.put(key, FreeMkKit.getConfigurationByClassLoader(RenderUtils.class.getClassLoader(), "/" + resourcePath));
    }
    Configuration configuration = configureMap.get(key);
    //根据名称去获取相应的模板对象(这个自身就有了缓存了,因此无需更改)
    Template template;
    try
    {
        template = configuration.getTemplate(subPath, CharEncoding.UTF_8);
        //公共参数
        //这个参数不能从缓存中获取,因为ioInfo.getSocket().getLocalAddress().getHostName()是动态变化的!
        //            Map<String, Object> map = Maps.asMap("base",
        //                String.format("http://%s:%d%s", ioInfo.getSocket().getLocalAddress().getHostName(), ioInfo.getHttpServer().getPort(), basePath));
        //            Map<String, Object> map = Maps.asMap("base",
        //                String.format("http://%s:%d%s", ioInfo.getSocket().getInetAddress().getHostAddress(), ioInfo.getHttpServer().getPort(), basePath));
        
        //从请求头Host参数中获取浏览器访问的真实地址
        Map<String, Object> map = Maps.asMap("base",
            String.format("http://%s%s", ioInfo.getReader().getHeader("Host"), basePath));
            
        //如果额外参数表非空,则加上额外参数
        if (Maps.isNotEmpty(extraParamMap))
        {
            map.putAll(extraParamMap);
        }
        
        //进行参数转换
        String msg = FreeMkKit.format(template, map);
        if (StringUtils.isNotEmpty(template.toString()))
        {
            //如果模板为空
            if (StringUtils.isEmpty(msg))
            {
                //转换异常,则通知内部服务器异常
                CommonResponse.internalServerError().accept(ioInfo);
            }
            else
            {
                //转换正常
                renderHtml(ioInfo, code, msg);
            }
        }
        else
        {
            //如果模板为空
            renderHtml(ioInfo, code, "");
        }
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}
 
源代码21 项目: httpkit   文件: HttpWriter.java
public HttpWriter(OutputStream out)
    throws UnsupportedEncodingException
{
    super(new OutputStreamWriter(out, CharEncoding.UTF_8));
    this.out = out;
}
 
源代码22 项目: product-ei   文件: ESBJAVA4318Testcase.java
@Test(groups = "wso2.esb", description = "cache meditor with payloads including Processing Insturctions")
public void testCacheMediatorWithPIs() throws Exception {

    String requestXml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://services.samples\" xmlns:xsd=\"http://services.samples/xsd\">\n"
            + "   <soapenv:Header>\n"
            + "      <m:Trans xmlns:m=\"http://www.w3schools.com/transaction/\">234</m:Trans>\n"
            + "   </soapenv:Header>\n" + "   <soapenv:Body>\n" + "      <ser:getFullQuote>\n"
            + "         <ser:request>\n" + "            <xsd:symbol>IBM</xsd:symbol>\n"
            + "         </ser:request>\n" + "      </ser:getFullQuote>\n" + "   </soapenv:Body>\n"
            + "</soapenv:Envelope>";

    final String expectedValue = "<?xml version='1.0' encoding='UTF-8'?><soapenv:Envelope " +
            "xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"><soapenv:Body><b xmlns=\"http://ws" +
            ".apache.org/ns/synapse\"><?xml-multiple  array?><xyz><a xmlns=\"\">after " +
            "cache</a></xyz></b></soapenv:Body></soapenv:Envelope>";

    DefaultHttpClient httpclient = new DefaultHttpClient();

    // this is to populate the cache mediator
    HttpPost httpPost = new HttpPost(getProxyServiceURLHttp("PF"));
    httpPost.addHeader("SOAPAction", "urn:getFullQuote");
    httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "text/xml;charset=UTF-8");
    HttpEntity stringEntity = new StringEntity(requestXml, CharEncoding.UTF_8);
    httpPost.setEntity(stringEntity);
    HttpResponse response = httpclient.execute(httpPost);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    response.getEntity().writeTo(baos);
    String actualValue = baos.toString();

    // this is to get the actual cache response
    HttpPost httpPost2 = new HttpPost(getProxyServiceURLHttp("PF"));
    httpPost2.addHeader("SOAPAction", "urn:getFullQuote");
    httpPost2.setHeader(HttpHeaders.CONTENT_TYPE, "text/xml;charset=UTF-8");
    HttpEntity stringEntity2 = new StringEntity(requestXml, CharEncoding.UTF_8);
    httpPost2.setEntity(stringEntity2);
    HttpResponse response2 = httpclient.execute(httpPost);

    ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
    response2.getEntity().writeTo(baos2);
    String actualValue2 = baos2.toString();
    Assert.assertEquals(actualValue2, expectedValue);
}
 
源代码23 项目: herd   文件: SampleDataJmsMessageListener.java
/**
 * Processes a JMS message.
 *
 * @param payload the message payload
 * @param allHeaders the JMS headers
 */
@JmsListener(id = HerdJmsDestinationResolver.SQS_DESTINATION_SAMPLE_DATA_QUEUE,
    containerFactory = "jmsListenerContainerFactory",
    destination = HerdJmsDestinationResolver.SQS_DESTINATION_SAMPLE_DATA_QUEUE)
public void processMessage(String payload, @Headers Map<Object, Object> allHeaders)
{
    LOGGER.info("Message received from the JMS queue. jmsQueueName=\"{}\" jmsMessageHeaders=\"{}\" jmsMessagePayload={}",
        HerdJmsDestinationResolver.SQS_DESTINATION_SAMPLE_DATA_QUEUE, allHeaders, payload);

    try
    {
        // Process messages coming from S3 bucket.
        S3EventNotification s3EventNotification = S3EventNotification.parseJson(payload);
        String objectKey = URLDecoder.decode(s3EventNotification.getRecords().get(0).getS3().getObject().getKey(), CharEncoding.UTF_8);
        long fileSize = s3EventNotification.getRecords().get(0).getS3().getObject().getSizeAsLong();
        // parse the objectKey, it should be in the format of namespace/businessObjectDefinitionName/fileName
        String[] objectKeyArrays = objectKey.split("/");
        Assert.isTrue(objectKeyArrays.length == 3, String.format("S3 notification message %s is not in expected format", objectKey));

        String namespace = objectKeyArrays[0];
        String businessObjectDefinitionName = objectKeyArrays[1];
        String fileName = objectKeyArrays[2];
        String path = namespace + "/" + businessObjectDefinitionName + "/";
        BusinessObjectDefinitionSampleFileUpdateDto businessObjectDefinitionSampleFileUpdateDto =
                new BusinessObjectDefinitionSampleFileUpdateDto(path, fileName, fileSize);

        String convertedNamespaece = convertS3KeyFormat(namespace);
        String convertedBusinessObjectDefinitionName = convertS3KeyFormat(businessObjectDefinitionName);

        BusinessObjectDefinitionKey businessObjectDefinitionKey =
                new BusinessObjectDefinitionKey(convertedNamespaece, convertedBusinessObjectDefinitionName);
        try
        {
            businessObjectDefinitionService.updateBusinessObjectDefinitionEntitySampleFile(businessObjectDefinitionKey,
                    businessObjectDefinitionSampleFileUpdateDto);
        }
        catch (ObjectNotFoundException ex)
        {
            LOGGER.info("Failed to find the business object definition, next try the original namespace and business oject defination name " + ex);
            // if Business object definition is not found, use the original name space and bdef name
            businessObjectDefinitionKey = new BusinessObjectDefinitionKey(namespace, businessObjectDefinitionName);
            businessObjectDefinitionService.updateBusinessObjectDefinitionEntitySampleFile(businessObjectDefinitionKey,
                    businessObjectDefinitionSampleFileUpdateDto);
        }
    }
    catch (RuntimeException | IOException e)
    {
        LOGGER.error("Failed to process message from the JMS queue. jmsQueueName=\"{}\" jmsMessagePayload={}",
                HerdJmsDestinationResolver.SQS_DESTINATION_SAMPLE_DATA_QUEUE, payload, e);
    }
}
 
@BeforeClass
static public void setUp() throws Exception {

    credentials = "Basic " + Base64.getEncoder().encodeToString("username:password".getBytes(CharEncoding.UTF_8));

    objectMapper = new ObjectMapper();
    objectMapper.disable(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS);

    Runner runner = Runner.newInstance("DocumentRunner");
    runners = new ArrayList<>();
    runners.add(runner);
    runnerAsString = "{\"runner\":" + objectMapper.writeValueAsString(runner) + "}";

    Repository repository = Repository.newInstance("1");
    repository.setType(RepositoryType.newInstance("CONFLUENCE"));
    repository.setMaxUsers(1);
    repositories = new ArrayList<>();
    repositories.add(repository);
    repositoryAsString = "{\"repository\":" + objectMapper.writeValueAsString(repository) + "}";
    repositoriesExpected = "{\"specificationRepositoriesOfAssociatedProject\":" + objectMapper.writeValueAsString(repositories) + "}";

    Project project = Project.newInstance("LDProject");
    projects = new ArrayList<>();
    projects.add(project);

    SystemUnderTest systemUnderTest = SystemUnderTest.newInstance("sut");
    systemUnderTests = new ArrayList<>();
    systemUnderTests.add(systemUnderTest);
    systemUnderTestAsString = "{\"systemUnderTest\":" + objectMapper.writeValueAsString(systemUnderTest) + "}";

    specification = Specification.newInstance("DocumentSpecification");
    specification.setRepository(repository);
    specificationAsString = "{\"specification\":" + objectMapper.writeValueAsString(specification) + "}";

    Reference reference = new Reference();
    references = new ArrayList<>();
    references.add(reference);
    referenceAsString = "{\"reference\":" + objectMapper.writeValueAsString(references.get(0)) + "}";

    requirement = new Requirement();
    requirement.setRepository(repository);
    requirementAsString = "{\"requirement\":" + objectMapper.writeValueAsString(requirement) + "}";

    execution = new Execution();
}
 
源代码25 项目: spark-xml-utils   文件: XSLTProcessor.java
/**
 * Transform the content.
 * 
 * @param content the xml to be transformed
 * @param stylesheetParams HashMap of stylesheet params
 * @return transformed content
 * @throws XSLTException
 */
public String transform(String content, HashMap<String,String> stylesheetParams) throws XSLTException {

	try {

		// Create streamsource for the content
		StreamSource contentSource = new StreamSource(IOUtils.toInputStream(content, CharEncoding.UTF_8));

		// Apply transformation
		return transform(contentSource, stylesheetParams);

	} catch (IOException e) {
		
		log.error("Problems transforming the content. "  + e.getMessage(),e);
		throw new XSLTException(e.getMessage());
		
	} 

}
 
源代码26 项目: spark-xml-utils   文件: XQueryProcessor.java
/**
 * Initialization to improve performance for repetitive invocations of evaluate expressions
 * 
 * @throws XQueryException
 */
private void init() throws XQueryException {
	
	try {
		
		// Get the processor
		proc = new Processor(false);

		// Set any specified configuration properties for the processor
		if (featureMappings != null) {
			for (Entry<String, Object> entry : featureMappings.entrySet()) {
				proc.setConfigurationProperty(entry.getKey(), entry.getValue());
			}
		}
		
		// Get the XQuery compiler
		XQueryCompiler xqueryCompiler = proc.newXQueryCompiler();
		xqueryCompiler.setEncoding(CharEncoding.UTF_8);

		// Set the namespace to prefix mappings
		this.setPrefixNamespaceMappings(xqueryCompiler, namespaceMappings);

		// Compile the XQuery expression and get an XQuery evaluator
		exp = xqueryCompiler.compile(xQueryExpression);
		eval = exp.load();
		
		// Create and initialize the serializer 
		baos = new ByteArrayOutputStream();
		serializer = proc.newSerializer(baos);
		// Appears ok to always set output property to xml (even if we are just returning a text string)
		serializer.setOutputProperty(Serializer.Property.METHOD, "xml");
		serializer.setOutputProperty(Serializer.Property.OMIT_XML_DECLARATION,"yes");
		serializer.setProcessor(proc);
		
	} catch (SaxonApiException e) {
		
		log.error("Problems creating an XQueryProcessor.  " + e.getMessage(),e);
		throw new XQueryException(e.getMessage());

	}
	
}
 
源代码27 项目: httpkit   文件: HttpRpc.java
/**
 * 调用Http服务
 * @author nan.li
 * @param requestUri
 * @param uniqueMethodName
 * @param requestParam
 * @return
 * @throws UnsupportedEncodingException 
 */
private String callHttp(String requestUri, String uniqueMethodName, String requestParam)
    throws UnsupportedEncodingException
{
    Logs.i("begin to call http RPC, post url=" + requestUri);
    return HttpUtils.doPost(requestUri, "application/json", requestParam.getBytes(CharEncoding.UTF_8), Maps.asStrMap("uniqueMethodName", uniqueMethodName), 3000, 3000);
}
 
源代码28 项目: spark-xml-utils   文件: XPathProcessor.java
/**
 * Filter the content with the XPath expression specified when creating the XPathProcessor.
 * 
 * @param content String to which the XPath expression will be applied
 * @return TRUE if the XPath expression evaluates to true, FALSE otherwise
 * @throws XPathException
 */
public boolean filterString(String content) throws XPathException {

	try {

		return filterStream(IOUtils.toInputStream(content,CharEncoding.UTF_8));

	} catch (IOException e) {
		
		log.error("Problems processing the content.  " + e.getMessage(),e);
		throw new XPathException(e.getMessage());
		
	}

}
 
源代码29 项目: spark-xml-utils   文件: XPathProcessor.java
/**
 * Evaluate the content with the XPath expression specified when creating the XPathProcessor
 * and return a serialized response.
 * 
 * @param content String to which the XPath Expression will be evaluated
 * @return Serialized response from the evaluation.  
 * @throws XPathException
 */
public String evaluateString(String content) throws XPathException{

	try {
		
		return evaluateStream(IOUtils.toInputStream(content,CharEncoding.UTF_8));

	} catch (IOException e) {
		
		log.error("Problems processing the content.  " + e.getMessage(),e);
		throw new XPathException(e.getMessage());
		
	}

}
 
源代码30 项目: spark-xml-utils   文件: XQueryProcessor.java
/**
 * Evaluate the content with the XQuery expression specified when creating the XQueryProcessor
 * and return a serialized response.
 * 
 * @param content String to which the XQuery Expression will be evaluated
 * @return Serialized response from the evaluation. 
 * @throws XQueryException
 */
public String evaluateString(String content) throws XQueryException {

	try {

		return evaluateStream(IOUtils.toInputStream(content,CharEncoding.UTF_8));

	} catch (IOException e) {
		
		log.error("Problems processing the content.  " + e.getMessage(),e);
		throw new XQueryException(e.getMessage());
		
	}

}
 
 类所在包
 类方法
 同包方法