com.alipay.api.internal.util.StringUtils Java Examples

The following examples show how to use com.alipay.api.internal.util.StringUtils. 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: AlipayMobilePublicMultiMediaClient.java    From pay with Apache License 2.0 6 votes vote down vote up
private static String getResponseCharset(String ctype) {
    String charset = DEFAULT_CHARSET;

    if (!StringUtils.isEmpty(ctype)) {
        String[] params = ctype.split(";");
        for (String param : params) {
            param = param.trim();
            if (param.startsWith("charset")) {
                String[] pair = param.split("=", 2);
                if (pair.length == 2) {
                    if (!StringUtils.isEmpty(pair[1])) {
                        charset = pair[1].trim();
                    }
                }
                break;
            }
        }
    }

    return charset;
}
 
Example #2
Source File: BaseAsymmetricEncryptor.java    From alipay-sdk-java-all with Apache License 2.0 6 votes vote down vote up
public boolean verify(String content, String charset, String publicKey, String sign) throws AlipayApiException {
    try {
        if (StringUtils.isEmpty(content)) {
            throw new AlipayApiException("待验签内容不可为空");
        }
        if (StringUtils.isEmpty(publicKey)) {
            throw new AlipayApiException("公钥不可为空");
        }
        if (StringUtils.isEmpty(sign)) {
            throw new AlipayApiException("签名串不可为空");
        }
        if (StringUtils.isEmpty(charset)) {
            charset = DEFAULT_CHARSET;
        }
        return doVerify(content, charset, publicKey, sign);
    } catch (Exception e) {

        String errorMessage = getAsymmetricType() + "验签遭遇异常,请检查公钥格式是否正确。" + e.getMessage() +
                " content=" + content + ",charset=" + charset + ",publicKey=" + publicKey;
        throw new AlipayApiException(errorMessage,e);
    }
}
 
Example #3
Source File: RSAEncryptor.java    From alipay-sdk-java-all with Apache License 2.0 6 votes vote down vote up
protected String doSign(String content, String charset, String privateKey) throws Exception {
    PrivateKey priKey = getPrivateKeyFromPKCS8(AlipayConstants.SIGN_TYPE_RSA,
            new ByteArrayInputStream(privateKey.getBytes()));

    Signature signature = Signature.getInstance(getSignAlgorithm());

    signature.initSign(priKey);

    if (StringUtils.isEmpty(charset)) {
        signature.update(content.getBytes());
    } else {
        signature.update(content.getBytes(charset));
    }

    byte[] signed = signature.sign();

    return new String(Base64.encodeBase64(signed));
}
 
Example #4
Source File: RSAEncryptor.java    From alipay-sdk-java-all with Apache License 2.0 6 votes vote down vote up
protected boolean doVerify(String content, String charset, String publicKey, String sign) throws Exception {
    PublicKey pubKey = getPublicKeyFromX509("RSA",
            new ByteArrayInputStream(publicKey.getBytes()));

    Signature signature = Signature.getInstance(getSignAlgorithm());

    signature.initVerify(pubKey);

    if (StringUtils.isEmpty(charset)) {
        signature.update(content.getBytes());
    } else {
        signature.update(content.getBytes(charset));
    }

    return signature.verify(Base64.decodeBase64(sign.getBytes()));
}
 
Example #5
Source File: AlipayMobilePublicMultiMediaClient.java    From alipay-sdk with Apache License 2.0 6 votes vote down vote up
private static String getResponseCharset(String ctype) {
    String charset = DEFAULT_CHARSET;

    if (!StringUtils.isEmpty(ctype)) {
        String[] params = ctype.split(";");
        for (String param : params) {
            param = param.trim();
            if (param.startsWith("charset")) {
                String[] pair = param.split("=", 2);
                if (pair.length == 2) {
                    if (!StringUtils.isEmpty(pair[1])) {
                        charset = pair[1].trim();
                    }
                }
                break;
            }
        }
    }

    return charset;
}
 
Example #6
Source File: AlipayMobilePublicMultiMediaClient.java    From alipay-sdk with Apache License 2.0 6 votes vote down vote up
private static URL buildGetUrl(String strUrl, String query) throws IOException {
    URL url = new URL(strUrl);
    if (StringUtils.isEmpty(query)) {
        return url;
    }

    if (StringUtils.isEmpty(url.getQuery())) {
        if (strUrl.endsWith("?")) {
            strUrl = strUrl + query;
        } else {
            strUrl = strUrl + "?" + query;
        }
    } else {
        if (strUrl.endsWith("&")) {
            strUrl = strUrl + query;
        } else {
            strUrl = strUrl + "&" + query;
        }
    }

    return new URL(strUrl);
}
 
Example #7
Source File: AlipayMobilePublicMultiMediaClient.java    From alipay-sdk with Apache License 2.0 6 votes vote down vote up
public static String buildQuery(Map<String, String> params, String charset) throws IOException {
    if (params == null || params.isEmpty()) {
        return null;
    }

    StringBuilder query = new StringBuilder();
    Set<Entry<String, String>> entries = params.entrySet();
    boolean hasParam = false;

    for (Entry<String, String> entry : entries) {
        String name = entry.getKey();
        String value = entry.getValue();

        if (StringUtils.areNotEmpty(name, value)) {
            if (hasParam) {
                query.append("&");
            } else {
                hasParam = true;
            }

            query.append(name).append("=").append(URLEncoder.encode(value, charset));
        }
    }

    return query.toString();
}
 
Example #8
Source File: JsonConverter.java    From alipay-sdk with Apache License 2.0 6 votes vote down vote up
/** 
 * @see com.alipay.api.internal.mapping.Converter#getSignItem(com.alipay.api.AlipayRequest, String)
 */
public SignItem getSignItem(AlipayRequest<?> request, String responseBody)
                                                                          throws AlipayApiException {

    // 响应为空则直接返回
    if (StringUtils.isEmpty(responseBody)) {

        return null;
    }

    SignItem signItem = new SignItem();

    // 获取签名
    String sign = getSign(responseBody);
    signItem.setSign(sign);

    // 签名源串
    String signSourceData = getSignSourceData(request, responseBody);
    signItem.setSignSourceDate(signSourceData);

    return signItem;
}
 
Example #9
Source File: XmlConverter.java    From alipay-sdk with Apache License 2.0 6 votes vote down vote up
/** 
 * @see com.alipay.api.internal.mapping.Converter#getSignItem(com.alipay.api.AlipayRequest, String)
 */
public SignItem getSignItem(AlipayRequest<?> request, String responseBody)
                                                                          throws AlipayApiException {

    // 响应为空则直接返回
    if (StringUtils.isEmpty(responseBody)) {

        return null;
    }

    SignItem signItem = new SignItem();

    // 获取签名
    String sign = getSign(responseBody);
    signItem.setSign(sign);

    // 签名源串
    String signSourceData = getSignSourceData(request, responseBody);
    signItem.setSignSourceDate(signSourceData);

    return signItem;
}
 
Example #10
Source File: AbstractAlipayClient.java    From alipay-sdk-java-all with Apache License 2.0 6 votes vote down vote up
public <T extends AlipayResponse> T execute(AlipayRequest<T> request, String accessToken,
                                            String appAuthToken, String targetAppId) throws AlipayApiException {

    //如果根证书序列号非空,抛异常提示开发者使用certificateExecute
    if (!StringUtils.isEmpty(this.alipayRootCertSN)) {
        throw new AlipayApiException("检测到证书相关参数已初始化,证书模式下请改为调用certificateExecute");
    }

    AlipayParser<T> parser = null;
    if (AlipayConstants.FORMAT_XML.equals(this.format)) {
        parser = new ObjectXmlParser<T>(request.getResponseClass());
    } else {
        parser = new ObjectJsonParser<T>(request.getResponseClass());
    }

    return _execute(request, parser, accessToken, appAuthToken, targetAppId);
}
 
Example #11
Source File: AlipayMobilePublicMultiMediaClient.java    From pay with Apache License 2.0 6 votes vote down vote up
private static URL buildGetUrl(String strUrl, String query) throws IOException {
    URL url = new URL(strUrl);
    if (StringUtils.isEmpty(query)) {
        return url;
    }

    if (StringUtils.isEmpty(url.getQuery())) {
        if (strUrl.endsWith("?")) {
            strUrl = strUrl + query;
        } else {
            strUrl = strUrl + "?" + query;
        }
    } else {
        if (strUrl.endsWith("&")) {
            strUrl = strUrl + query;
        } else {
            strUrl = strUrl + "&" + query;
        }
    }

    return new URL(strUrl);
}
 
Example #12
Source File: AlipayMobilePublicMultiMediaClient.java    From pay with Apache License 2.0 6 votes vote down vote up
public static String buildQuery(Map<String, String> params, String charset) throws IOException {
    if (params == null || params.isEmpty()) {
        return null;
    }

    StringBuilder query = new StringBuilder();
    Set<Entry<String, String>> entries = params.entrySet();
    boolean hasParam = false;

    for (Entry<String, String> entry : entries) {
        String name = entry.getKey();
        String value = entry.getValue();

        if (StringUtils.areNotEmpty(name, value)) {
            if (hasParam) {
                query.append("&");
            } else {
                hasParam = true;
            }

            query.append(name).append("=").append(URLEncoder.encode(value, charset));
        }
    }

    return query.toString();
}
 
Example #13
Source File: JsonConverter.java    From pay with Apache License 2.0 6 votes vote down vote up
/** 
 * @see com.alipay.api.internal.mapping.Converter#getSignItem(com.alipay.api.AlipayRequest, String)
 */
public SignItem getSignItem(AlipayRequest<?> request, String responseBody)
                                                                          throws AlipayApiException {

    // 响应为空则直接返回
    if (StringUtils.isEmpty(responseBody)) {

        return null;
    }

    SignItem signItem = new SignItem();

    // 获取签名
    String sign = getSign(responseBody);
    signItem.setSign(sign);

    // 签名源串
    String signSourceData = getSignSourceData(request, responseBody);
    signItem.setSignSourceDate(signSourceData);

    return signItem;
}
 
Example #14
Source File: XmlConverter.java    From pay with Apache License 2.0 6 votes vote down vote up
/** 
 * @see com.alipay.api.internal.mapping.Converter#getSignItem(com.alipay.api.AlipayRequest, String)
 */
public SignItem getSignItem(AlipayRequest<?> request, String responseBody)
                                                                          throws AlipayApiException {

    // 响应为空则直接返回
    if (StringUtils.isEmpty(responseBody)) {

        return null;
    }

    SignItem signItem = new SignItem();

    // 获取签名
    String sign = getSign(responseBody);
    signItem.setSign(sign);

    // 签名源串
    String signSourceData = getSignSourceData(request, responseBody);
    signItem.setSignSourceDate(signSourceData);

    return signItem;
}
 
Example #15
Source File: Dispatcher.java    From jeewx with Apache License 2.0 6 votes vote down vote up
/**
 * 根据事件类型细化查找对应执行器
 * 
 * @param service
 * @param bizContentJson
 * @return
 * @throws MyException
 */
private static ActionExecutor getEventExecutor(String service, JSONObject bizContentJson) throws MyException {
    // 1. 获取事件类型
    String eventType = bizContentJson.getString("EventType");

    if (StringUtils.isEmpty(eventType)) {
        throw new MyException("无法取得事件类型");
    }

    // 2.根据事件类型再次区分服务类型
    // 2.1 激活验证开发者模式
    if (AlipayServiceNameConstants.ALIPAY_CHECK_SERVICE.equals(service)
        && eventType.equals(AlipayServiceEventConstants.VERIFYGW_EVENT)) {

        return new InAlipayVerifyExecutor();

        // 2.2 其他消息通知类 
    } else if (AlipayServiceNameConstants.ALIPAY_PUBLIC_MESSAGE_NOTIFY.equals(service)) {

        return getMsgNotifyExecutor(eventType, bizContentJson);

        // 2.3 对于后续支付宝可能新增的类型,统一默认返回AKC响应
    } else {
        return new InAlipayDefaultExecutor(bizContentJson);
    }
}
 
Example #16
Source File: Dispatcher.java    From jeewx with Apache License 2.0 6 votes vote down vote up
/**
 * 进入事件执行器
 * 
 * @param bizContentJson
 * @return
 */
private static ActionExecutor getEnterEventTypeExecutor(JSONObject bizContentJson) {
    try {

        JSONObject param = JSONObject.fromObject(bizContentJson.get("ActionParam"));
        JSONObject scene = JSONObject.fromObject(param.get("scene"));

        if (!StringUtils.isEmpty(scene.getString("sceneId"))) {

            //自定义场景参数进入服务窗事件
            return new InAlipayDIYQRCodeEnterExecutor(bizContentJson);
        } else {

            //普通进入服务窗事件
            return new InAlipayEnterExecutor(bizContentJson);
        }
    } catch (Exception exception) {
        //无法解析sceneId的情况作为普通进入服务窗事件
        return new InAlipayEnterExecutor(bizContentJson);
    }
}
 
Example #17
Source File: AlipayCoreService.java    From jeewx with Apache License 2.0 6 votes vote down vote up
/**
 * 事件执行
 * @param service
 * @param bizContentJson
 * @return
 * @throws MyException
 */
private String doEventExcute(String service, JSONObject bizContentJson) throws MyException {

	// 1. 获取事件类型
	String eventType = bizContentJson.getString("EventType");

	if (StringUtils.isEmpty(eventType)) {
		throw new MyException("无法取得事件类型");
	}

	// 2.根据事件类型再次区分服务类型
	// 2.1 激活验证开发者模式
	if (AlipayServiceNameConstants.ALIPAY_CHECK_SERVICE.equals(service)&& eventType.equals(AlipayServiceEventConstants.VERIFYGW_EVENT)) {
		return new InAlipayVerifyExecutor().execute();
		// 2.2 其他消息通知类
	} else if (AlipayServiceNameConstants.ALIPAY_PUBLIC_MESSAGE_NOTIFY.equals(service)) {
		return getMsgNotifyExecutor(eventType, bizContentJson);
		// 2.3 对于后续支付宝可能新增的类型,统一默认返回AKC响应
	} else {
		return doSendDefaultMessage(bizContentJson);
	}
}
 
Example #18
Source File: Message.java    From alipay-sdk-java-all with Apache License 2.0 6 votes vote down vote up
public static void addSign(Message message, String appPrivateKey) {
    if (!("message".equals(message.getxType()) && MsgConstants.MSG_CMD_PRODUCE.equals(message.getxCmd()))) {
        return;
    }
    if (StringUtils.isEmpty(message.getxSignType()) || StringUtils.isEmpty(message.getxCharset())
            || StringUtils.isEmpty(appPrivateKey)) {
        throw new IllegalArgumentException("can not add sign, miss x-signType or x-charset.");
    }

    String signContent = genDataPart(message);
    if (StringUtils.isEmpty(signContent)) {
        throw new IllegalArgumentException("can not add sign, miss signContent.");
    }
    try {
        message.setxSign(AlipaySignature.rsaSign(signContent, appPrivateKey, message.getxCharset(),
                message.getxSignType()));
    } catch (Throwable t) {
        throw new IllegalArgumentException("add sign fail. exception:" + t.getMessage());
    }
}
 
Example #19
Source File: SM2Encryptor.java    From alipay-sdk-java-all with Apache License 2.0 6 votes vote down vote up
private static boolean sm2Verify(byte[] signature, byte[] message, PublicKey publicKey, String sm2UserId) {
    try {
        String userId = "1234567812345678";
        if (!StringUtils.isEmpty(sm2UserId)) {
            userId = sm2UserId;
        }
        Signature sm2SignEngine = Signature.getInstance("SM3withSM2");
        sm2SignEngine.setParameter(new SM2ParameterSpec(Strings.toByteArray(userId)));
        sm2SignEngine.initVerify(publicKey);
        sm2SignEngine.update(message);
        return sm2SignEngine.verify(signature);
    } catch (Exception e) {
        AlipayLogger.logBizError(e);
        return false;
    }
}
 
Example #20
Source File: SM2Encryptor.java    From alipay-sdk-java-all with Apache License 2.0 6 votes vote down vote up
private static byte[] sm2Sign(byte[] message, PrivateKey sm2PrivateKey, String sm2UserId) throws AlipayApiException {
    try {
        String userId = "1234567812345678";
        if (!StringUtils.isEmpty(sm2UserId)) {
            userId = sm2UserId;
        }
        Signature sm2SignEngine = Signature.getInstance("SM3withSM2");
        sm2SignEngine.setParameter(new SM2ParameterSpec(
                Strings.toByteArray(userId)));
        sm2SignEngine.initSign(sm2PrivateKey);
        sm2SignEngine.update(message);
        return sm2SignEngine.sign();
    } catch (Exception e) {
        AlipayLogger.logBizError(e);
        throw new AlipayApiException(e);
    }
}
 
Example #21
Source File: XmlConverter.java    From alipay-sdk-java-all with Apache License 2.0 6 votes vote down vote up
/**
 * @see com.alipay.api.internal.mapping.Converter#getCertItem(com.alipay.api.AlipayRequest, String)
 */
public CertItem getCertItem(AlipayRequest<?> request, String responseBody)
        throws AlipayApiException {

    // 响应为空则直接返回
    if (StringUtils.isEmpty(responseBody)) {

        return null;
    }

    CertItem certItem = new CertItem();

    // 获取签名
    String sign = getSign(responseBody);
    certItem.setSign(sign);

    // 获取证书
    String cert = getCert(responseBody);
    certItem.setCert(cert);

    // 签名源串
    String signSourceData = getSignSourceData(request, responseBody);
    certItem.setSignSourceDate(signSourceData);

    return certItem;
}
 
Example #22
Source File: XmlConverter.java    From alipay-sdk-java-all with Apache License 2.0 6 votes vote down vote up
/**
 * @see com.alipay.api.internal.mapping.Converter#getSignItem(com.alipay.api.AlipayRequest, String)
 */
public SignItem getSignItem(AlipayRequest<?> request, String responseBody)
        throws AlipayApiException {

    // 响应为空则直接返回
    if (StringUtils.isEmpty(responseBody)) {

        return null;
    }

    SignItem signItem = new SignItem();

    // 获取签名
    String sign = getSign(responseBody);
    signItem.setSign(sign);

    // 签名源串
    String signSourceData = getSignSourceData(request, responseBody);
    signItem.setSignSourceDate(signSourceData);

    return signItem;
}
 
Example #23
Source File: JsonConverter.java    From alipay-sdk-java-all with Apache License 2.0 6 votes vote down vote up
/**
 * @see com.alipay.api.internal.mapping.Converter#getSignItem(com.alipay.api.AlipayRequest, String)
 */
public SignItem getSignItem(AlipayRequest<?> request, String responseBody)
        throws AlipayApiException {

    // 响应为空则直接返回
    if (StringUtils.isEmpty(responseBody)) {

        return null;
    }

    SignItem signItem = new SignItem();

    // 获取签名
    String sign = getSign(responseBody);
    signItem.setSign(sign);

    // 签名源串
    String signSourceData = getSignSourceData(request, responseBody);
    signItem.setSignSourceDate(signSourceData);

    return signItem;
}
 
Example #24
Source File: Message.java    From alipay-sdk-java-all with Apache License 2.0 6 votes vote down vote up
public static boolean checkSign(Message message, String alipayPublicKey) throws IllegalArgumentException {
    if (!("message".equals(message.getxType()) && MsgConstants.MSG_CMD_CONSUME.equals(message.getxCmd()))) {
        return true;
    }

    if (StringUtils.isEmpty(message.getxSignType()) || StringUtils.isEmpty(message.getxSign())
            || StringUtils.isEmpty(message.getxCharset()) || StringUtils.isEmpty(alipayPublicKey)) {
        throw new IllegalArgumentException("can not check sign, miss x-signType or x-sign or x-charset.");
    }
    String signContent = extractSignContent(message.getBody());
    if (StringUtils.isEmpty(signContent)) {
        throw new IllegalArgumentException("can not check sign, miss signContent.");
    }
    try {
        return AlipaySignature.rsaCheck(signContent, message.getxSign(), alipayPublicKey, message.getxCharset(),
                message.getxSignType());
    } catch (Throwable t) {
        throw new IllegalArgumentException("check sign fail. exception:" + t.getCause().getMessage());
    }
}
 
Example #25
Source File: BaseAsymmetricEncryptor.java    From alipay-sdk-java-all with Apache License 2.0 6 votes vote down vote up
public String decrypt(String cipherTextBase64, String charset, String privateKey) throws AlipayApiException {
    try {
        if (StringUtils.isEmpty(cipherTextBase64)) {
            throw new AlipayApiException("密文不可为空");
        }
        if (StringUtils.isEmpty(privateKey)) {
            throw new AlipayApiException("私钥不可为空");
        }
        if (StringUtils.isEmpty(charset)) {
            charset = DEFAULT_CHARSET;
        }
        return doDecrypt(cipherTextBase64, charset, privateKey);

    } catch (Exception e) {

        String errorMessage = getAsymmetricType() + "非对称解密遭遇异常,请检查私钥格式是否正确。" + e.getMessage() +
                " cipherTextBase64=" + cipherTextBase64 + ",charset=" + charset + ",privateKeySize=" + privateKey.length();
        throw new AlipayApiException(errorMessage,e);
    }

}
 
Example #26
Source File: BaseAsymmetricEncryptor.java    From alipay-sdk-java-all with Apache License 2.0 6 votes vote down vote up
public String encrypt(String plainText, String charset, String publicKey) throws AlipayApiException {
    try {
        if (StringUtils.isEmpty(plainText)) {
            throw new AlipayApiException("密文不可为空");
        }
        if (StringUtils.isEmpty(publicKey)) {
            throw new AlipayApiException("公钥不可为空");
        }
        if (StringUtils.isEmpty(charset)) {
            charset = DEFAULT_CHARSET;
        }
        return doEncrypt(plainText, charset, publicKey);
    } catch (Exception e) {

        String errorMessage = getAsymmetricType() + "非对称解密遭遇异常,请检查公钥格式是否正确。" + e.getMessage() +
                " plainText=" + plainText + ",charset=" + charset + ",publicKey=" + publicKey;
        throw new AlipayApiException(errorMessage,e);
    }

}
 
Example #27
Source File: BaseAsymmetricEncryptor.java    From alipay-sdk-java-all with Apache License 2.0 6 votes vote down vote up
public String sign(String content, String charset, String privateKey) throws AlipayApiException {
    try {
        if (StringUtils.isEmpty(content)) {
            throw new AlipayApiException("待签名内容不可为空");
        }
        if (StringUtils.isEmpty(privateKey)) {
            throw new AlipayApiException("私钥不可为空");
        }
        if (StringUtils.isEmpty(charset)) {
            charset = DEFAULT_CHARSET;
        }
        return doSign(content, charset, privateKey);
    } catch (Exception e) {

        String errorMessage = getAsymmetricType() + "签名遭遇异常,请检查私钥格式是否正确。" + e.getMessage() +
                " content=" + content + ",charset=" + charset + ",privateKeySize=" + privateKey.length();
        throw new AlipayApiException(errorMessage,e);
    }

}
 
Example #28
Source File: Dispatcher.java    From jeewx with Apache License 2.0 5 votes vote down vote up
/**
 * 根据业务参数获取业务执行器
 * 
 * @param params
 * @return
 * @throws MyException
 */
public static ActionExecutor getExecutor(Map<String, String> params) throws MyException {
    //获取服务信息
    String service = params.get("service");
    if (StringUtils.isEmpty(service)) {
        throw new MyException("无法取得服务名");
    }
    //获取内容信息
    String bizContent = params.get("biz_content");
    if (StringUtils.isEmpty(bizContent)) {
        throw new MyException("无法取得业务内容信息");
    }

    //将XML转化成json对象
    JSONObject bizContentJson = (JSONObject) new XMLSerializer().read(bizContent);

    // 1.获取消息类型信息 
    String msgType = bizContentJson.getString("MsgType");
    if (StringUtils.isEmpty(msgType)) {
        throw new MyException("无法取得消息类型");
    }

    // 2.根据消息类型(msgType)进行执行器的分类转发
    //  2.1 纯文本聊天类型
    if ("text".equals(msgType)) {

        return ApplicationContextUtil.getContext().getBean(InAlipayChatTextExecutor.class);

        // 2.2 事件类型
    } else if ("event".equals(msgType)) {

        return getEventExecutor(service, bizContentJson);

    } else {

        // 2.3 后续支付宝还会新增其他类型,因此默认返回ack应答
        return new InAlipayDefaultExecutor(bizContentJson);
    }

}
 
Example #29
Source File: ProtocolData.java    From alipay-sdk-java-all with Apache License 2.0 5 votes vote down vote up
public static ProtocolData fromStr(String str) {
    if (StringUtils.isEmpty(str)) {
        return null;
    }
    int i = str.indexOf(MsgConstants.CRLF2);
    if (i < 0) {
        throw new IllegalArgumentException("not find CRLF2. " + str);
    }

    ProtocolData protocolData = new ProtocolData();

    String protocol = str.substring(0, i);
    String data = str.substring(i + MsgConstants.CRLF2.length());
    try {
        if (!StringUtils.isEmpty(protocol)) {
            String[] kvs = protocol.split(MsgConstants.CRLF);
            for (String kvStr : kvs) {
                String[] kv = kvStr.split(MsgConstants.COLON);
                if (MsgConstants.PROTOCOL_KEY_FROM_SYS.equals(kv[0].trim())) {
                    protocolData.setFromSys(kv[1].trim());
                } else if (MsgConstants.PROTOCOL_KEY_FROM_SYS_IP.equals(kv[0].trim())) {
                    protocolData.setFromSysIp(kv[1].trim());
                } else if (MsgConstants.PROTOCOL_KEY_STREAM_ID.equals(kv[0].trim())) {
                    protocolData.setStreamId(kv[1].trim());
                }
            }
        }
        if (!StringUtils.isEmpty(data)) {
            protocolData.setMessage(Message.fromStr(data));
        }
    } catch (Throwable t) {
        throw new IllegalArgumentException("format illegal. exception:" + t.getMessage() + " str:" + str);
    }

    return protocolData;
}
 
Example #30
Source File: Message.java    From alipay-sdk-java-all with Apache License 2.0 5 votes vote down vote up
private static String genDataPart(Message message) {
    StringBuilder dataSb = new StringBuilder();
    dataSb.append("{\"header\":{");
    if (!StringUtils.isEmpty(message.getAppId())) {
        dataSb.append("\"appId\":\"").append(message.getAppId()).append("\",");
    }
    if (!StringUtils.isEmpty(message.getMsgApi())) {
        dataSb.append("\"msgApi\":\"").append(message.getMsgApi()).append("\",");
    }
    if (',' == dataSb.charAt(dataSb.length() - 1)) {
        dataSb.deleteCharAt(dataSb.length() - 1);
    }
    dataSb.append("}");
    if (!StringUtils.isEmpty(message.getBizContent())) {
        JSONValidator jsonValidator = new JSONValidator(new ExceptionErrorListener());
        if (!jsonValidator.validate(message.getBizContent())) {
            throw new IllegalArgumentException("bizContent json format illegal.");
        }
        dataSb.append(",\"content\":").append(message.getBizContent());
    }
    dataSb.append("}");
    String data = dataSb.toString();
    if ("{\"header\":{}}".equals(data)) {
        data = null;
    }
    return data;
}