org.apache.commons.lang3.CharEncoding Java Examples

The following examples show how to use org.apache.commons.lang3.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: EI2084EnrichNamespaceAdditionTestCase.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #2
Source File: MailService.java    From tutorials 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(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);
    }
}
 
Example #3
Source File: MailService.java    From cubeai 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 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 #4
Source File: MailService.java    From jhipster-microservices-example 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 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 #5
Source File: MailService.java    From scava with Eclipse Public 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 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());
        }
    }
}
 
Example #6
Source File: BaseController.java    From httpkit with Apache License 2.0 6 votes vote down vote up
/**
 * 输出某个字符流的内容,一般是用作页面渲染(支持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);
    }
}
 
Example #7
Source File: MailService.java    From tutorials 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(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);
    }
}
 
Example #8
Source File: HttpReader.java    From httpkit with Apache License 2.0 6 votes vote down vote up
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();
            }
        }
    }
}
 
Example #9
Source File: ClientUtils.java    From livingdoc-core with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @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));

}
 
Example #10
Source File: EI2084EnrichNamespaceAdditionTestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #11
Source File: WeixinJSApiPaymentService.java    From payment with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #12
Source File: ESBJAVA3676EnrichSourcePropNoClone.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
@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"));
}
 
Example #13
Source File: LogParser.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
@Override
public void setup(Context.OperatorContext context)
{
  objMapper = new ObjectMapper();
  encoding = encoding != null ? encoding : CharEncoding.UTF_8;
  setupLog();
}
 
Example #14
Source File: HerdJmsMessageListener.java    From herd with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #15
Source File: ClientUtils.java    From livingdoc-core with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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};
}
 
Example #16
Source File: ESBJAVA3676EnrichSourcePropNoClone.java    From product-ei with Apache License 2.0 5 votes vote down vote up
@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"));
}
 
Example #17
Source File: FileUtils.java    From wenku with MIT License 5 votes vote down vote up
/**
 * 写入内容到文件
 * @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();
    }
}
 
Example #18
Source File: HttpServer.java    From httpkit with Apache License 2.0 5 votes vote down vote up
/**
 * 自适应加载过滤器配置类列表<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;
}
 
Example #19
Source File: ESBJAVA4318Testcase.java    From product-ei with Apache License 2.0 4 votes vote down vote up
@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);
}
 
Example #20
Source File: HttpWriter.java    From httpkit with Apache License 2.0 4 votes vote down vote up
public HttpWriter(OutputStream out)
    throws UnsupportedEncodingException
{
    super(new OutputStreamWriter(out, CharEncoding.UTF_8));
    this.out = out;
}
 
Example #21
Source File: SampleDataJmsMessageListener.java    From herd with Apache License 2.0 4 votes vote down vote up
/**
 * 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);
    }
}
 
Example #22
Source File: RenderUtils.java    From httpkit with Apache License 2.0 4 votes vote down vote up
/**
 * 渲染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();
    }
}
 
Example #23
Source File: LivingDocRestServiceTest.java    From livingdoc-confluence with GNU General Public License v3.0 4 votes vote down vote up
@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();
}
 
Example #24
Source File: XSLTProcessor.java    From spark-xml-utils with Apache License 2.0 4 votes vote down vote up
/**
 * 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());
		
	} 

}
 
Example #25
Source File: XQueryProcessor.java    From spark-xml-utils with Apache License 2.0 4 votes vote down vote up
/**
 * 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());

	}
	
}
 
Example #26
Source File: ESBJAVA4318Testcase.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
@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);
}
 
Example #27
Source File: XPathProcessor.java    From spark-xml-utils with Apache License 2.0 3 votes vote down vote up
/**
 * 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());
		
	}

}
 
Example #28
Source File: XPathProcessor.java    From spark-xml-utils with Apache License 2.0 3 votes vote down vote up
/**
 * 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());
		
	}

}
 
Example #29
Source File: XQueryProcessor.java    From spark-xml-utils with Apache License 2.0 3 votes vote down vote up
/**
 * 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());
		
	}

}
 
Example #30
Source File: HttpRpc.java    From httpkit with Apache License 2.0 3 votes vote down vote up
/**
 * 调用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);
}