Java Code Examples for org.nutz.lang.Lang#wrapThrow()

The following examples show how to use org.nutz.lang.Lang#wrapThrow() . 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: WechatAPIImpl.java    From mpsdk4j with Apache License 2.0 6 votes vote down vote up
@Override
public Follower getWebOauth2User(String openId, String lang) {
    lang = Strings.sBlank(lang, "zh_CN");
    WebOauth2Result result = _oath2.get(openId);
    if (result == null){
       throw Lang.wrapThrow(new WechatAPIException("用户未授权"));
    } else if (!result.isAvailable()){
        result = refreshWebOauth2Result(result.getRefreshToken());
    }

    String url = mergeAPIUrl(oauth2UserURL, result.getAccessToken(), openId, lang);
    APIResult ar = wechatServerResponse(url,
            HTTP_GET,
            NONE_BODY,
            "以网页授权方式获取公众号[%s]的用户[%s-%s]信息失败.",
            openId,
            lang);
    return Json.fromJson(Follower.class, ar.getJson());
}
 
Example 2
Source File: HttpTool.java    From mpsdk4j with Apache License 2.0 6 votes vote down vote up
public static String get(String url) {
    if (log.isDebugEnabled()) {
        log.debugf("Request url: %s, default timeout: %d", url, CONNECT_TIME_OUT);
    }

    try {
        Response resp = Http.get(url, CONNECT_TIME_OUT);
        if (resp.isOK()) {
            String content = resp.getContent("UTF-8");
            if (log.isInfoEnabled()) {
                log.infof("GET Request success. Response content: %s", content);
            }
            return content;
        }

        throw Lang.wrapThrow(new RuntimeException(String.format("Get request [%s] failed. status: %d",
                                                                url,
                                                                resp.getStatus())));
    }
    catch (Exception e) {
        throw Lang.wrapThrow(e);
    }
}
 
Example 3
Source File: WxApi2Impl.java    From nutzwx with Apache License 2.0 6 votes vote down vote up
/**
 * 微信支付公共POST方法(带证书)
 *
 * @param url
 *            请求路径
 * @param key
 *            商户KEY
 * @param params
 *            参数
 * @param file
 *            证书文件
 * @param password
 *            证书密码
 * @return
 */
@Override
public NutMap postPay(String url, String key, Map<String, Object> params, Object data, String password) {
    params.remove("sign");
    String sign = WxPaySign.createSign(key, params);
    params.put("sign", sign);
    Request req = Request.create(url, METHOD.POST);
    req.setData(Xmls.mapToXml(params));
    Sender sender = Sender.create(req);
    SSLSocketFactory sslSocketFactory;
    try {
        sslSocketFactory = WxPaySSL.buildSSL(data, password);
    }
    catch (Exception e) {
        throw Lang.wrapThrow(e);
    }
    sender.setSSLSocketFactory(sslSocketFactory);
    Response resp = sender.send();
    if (!resp.isOK())
        throw new IllegalStateException("postPay with SSL, resp code=" + resp.getStatus());
    return Xmls.xmlToMap(resp.getContent("UTF-8"));
}
 
Example 4
Source File: HttpTool.java    From mpsdk4j with Apache License 2.0 6 votes vote down vote up
public static String upload(String url, File file) {
    if (log.isDebugEnabled()) {
        log.debugf("Upload url: %s, file name: %s, default timeout: %d",
                   url,
                   file.getName(),
                   CONNECT_TIME_OUT);
    }

    try {
        Request req = Request.create(url, METHOD.POST);
        req.getParams().put("media", file);
        Response resp = new FilePostSender(req).send();
        if (resp.isOK()) {
            String content = resp.getContent();
            return content;
        }

        throw Lang.wrapThrow(new RuntimeException(String.format("Upload file [%s] failed. status: %d",
                                                                url,
                                                                resp.getStatus())));
    }
    catch (Exception e) {
        throw Lang.wrapThrow(e);
    }
}
 
Example 5
Source File: WXBizMsgCryptTest.java    From mpsdk4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecryptMsg() {
    log.info("====== WXBizMsgCrypt#decryptMsg ======");
    try {
        String decryptmsg = pc.decryptMsg(msgSignature,
                                          timeStamp,
                                          nonce,
                                          StreamTool.toStream(fromMsg));
        assertNotNull(decryptmsg);
        log.info(decryptmsg);
        log.info(pc.getFromAppId());
    }
    catch (AesException e) {
        throw Lang.wrapThrow(e);
    }
}
 
Example 6
Source File: JetTemplateView.java    From jetbrick-template-1x with Apache License 2.0 5 votes vote down vote up
@Override
public void render(HttpServletRequest req, HttpServletResponse resp, Object obj) throws Throwable {
    JetContext context = new JetWebContext(req, resp);
    JetTemplate template = JetWebEngineLoader.getJetEngine().getTemplate(evalPath(req, obj));
    try {
        template.render(context, resp.getOutputStream());
    } catch (IOException e) {
        throw Lang.wrapThrow(e);
    }
}
 
Example 7
Source File: WxApi2Impl.java    From nutzwx with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("rawtypes")
public List<WxArticle> get_material_news(String media_id) {
    try {
        NutMap re = Json.fromJson(NutMap.class, get_material(media_id).getReader());
        List<WxArticle> list = new ArrayList<WxArticle>();
        for (Object obj : re.getAs("news_item", List.class)) {
            list.add(Lang.map2Object((Map) obj, WxArticle.class));
        }
        return list;
    }
    catch (Exception e) {
        throw Lang.wrapThrow(e);
    }
}
 
Example 8
Source File: Wxs.java    From nutzwx with Apache License 2.0 5 votes vote down vote up
/**
 * 将一个输入流转为WxInMsg
 */
public static <T> T convert(InputStream in, Class<T> klass) {
    Map<String, Object> map;
    String raw;
    try {
        // fix:
        // DocumentBuilder不支持直接传入Reader,如果直接传InputStream的话又按系统默认编码,所以,用InputSource中转一下
        Reader r = Streams.utf8r(in);
        raw = Lang.readAll(r);
        map = Xmls.asMap(xmls().parse(new InputSource(new StringReader(raw)))
                               .getDocumentElement());
    }
    catch (Exception e) {
        throw Lang.wrapThrow(e);
    }
    Lang.convertMapKey(map, new MapKeyConvertor() {
        @Override
        public String convertKey(String key) {
            return Strings.lowerFirst(key);
        }
    }, true);

    if (DEV_MODE) {
        log.debug("Income >> \n" + Json.toJson(map));
    }
    T t = Lang.map2Object(map, klass);
    if (t instanceof WxInMsg)
        ((WxInMsg) t).raw(raw);
    else if (t instanceof WxOutMsg)
        ((WxOutMsg) t).raw(raw);
    return t;
}
 
Example 9
Source File: MessageHandlerTest.java    From mpsdk4j with Apache License 2.0 5 votes vote down vote up
public void init() {
    log.info("====== MessageHandlerTest ======");
    try {
        xmlParser = factory.newSAXParser();
    }
    catch (Exception e) {
        throw Lang.wrapThrow(e);
    }
}
 
Example 10
Source File: WXBizMsgCryptTest.java    From mpsdk4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testEncryptMsg() {
    log.info("====== WXBizMsgCrypt#encryptMsg ======");
    try {
        String encryptmsg = pc.encryptMsg(replyMsg, timeStamp, nonce);
        assertNotNull(encryptmsg);
        log.info(encryptmsg.replaceAll("\\n", ""));
    }
    catch (AesException e) {
        throw Lang.wrapThrow(e);
    }
}
 
Example 11
Source File: WXBizMsgCryptTest.java    From mpsdk4j with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void init() {
    log.info("====== WXBizMsgCryptTest ======");
    try {
        pc = new WXBizMsgCrypt(token, encodingAesKey, appId);
    }
    catch (AesException e) {
        throw Lang.wrapThrow(e);
    }
}
 
Example 12
Source File: WechatKernel.java    From mpsdk4j with Apache License 2.0 5 votes vote down vote up
/**
 * 微信服务器校验
 * 
 * @return 微信服务器随机字符串
 */
public String check() {
    String sign = get("signature");
    String ts = get("timestamp");
    String nonce = get("nonce");

    if (sign == null
        || sign.length() > 128
        || ts == null
        || ts.length() > 128
        || nonce == null
        || nonce.length() > 128) {
        log.warnf("接入微信服务器认证的加密参数为空或是长度大于128.");
        return "error";
    }

    try {
        String validsign = SHA1.calculate(mpAct.getToken(), ts, nonce);
        if (log.isDebugEnabled()) {
            log.debugf("接入微信服务器认证: %b. 加密字符串: %s",
                       Lang.equals(validsign, sign),
                       validsign);
        }

        if(sign.equals(validsign)){
            return get("echostr");
        }

        return "error";
    }
    catch (AesException e) {
        throw Lang.wrapThrow(new WechatRunTimeException("校验服务器认证出现异常", e));
    }
}
 
Example 13
Source File: WechatKernel.java    From mpsdk4j with Apache License 2.0 5 votes vote down vote up
public WechatKernel() {
    try {
        xmlParser = factory.newSAXParser();
    }
    catch (Exception e) {
        throw Lang.wrapThrow(new WechatRunTimeException("初始化SAXParserFactory出现异常", e));
    }
}
 
Example 14
Source File: HttpTool.java    From mpsdk4j with Apache License 2.0 5 votes vote down vote up
public static String post(String url, String body) {
    if (log.isDebugEnabled()) {
        log.debugf("Request url: %s, post data: %s, default timeout: %d",
                   url,
                   body,
                   CONNECT_TIME_OUT);
    }

    try {
        Request req = Request.create(url, METHOD.POST);
        req.setEnc("UTF-8");
        req.setData(body);
        Response resp = Sender.create(req, CONNECT_TIME_OUT).send();
        if (resp.isOK()) {
            String content = resp.getContent();
            if (log.isInfoEnabled()) {
                log.infof("POST Request success. Response content: %s", content);
            }
            return content;
        }

        throw Lang.wrapThrow(new RuntimeException(String.format("Post request [%s] failed. status: %d",
                                                                url,
                                                                resp.getStatus())));
    }
    catch (Exception e) {
        throw Lang.wrapThrow(e);
    }
}
 
Example 15
Source File: AbstractWxApi2.java    From nutzwx with Apache License 2.0 4 votes vote down vote up
protected WxResp call(String URL, METHOD method, String body) {
    String token = getAccessToken();
    if (log.isInfoEnabled()) {
        log.info("wxapi call: " + URL);
        if (log.isDebugEnabled()) {
            log.debug(body);
        }
    }

    int retry = retryTimes;
    WxResp wxResp = null;
    while (retry >= 0) {
        try {
            String sendUrl = URL.startsWith("http") ? URL : base + URL;
            if (URL.contains("?")) {
                sendUrl += "&access_token=" + token;
            } else {
                sendUrl += "?access_token=" + token;
            }
            Request req = Request.create(sendUrl, method);
            if (body != null)
                req.setData(body);
            Response resp = Sender.create(req).send();
            if (!resp.isOK())
                throw new IllegalArgumentException("resp code=" + resp.getStatus());
            wxResp = Json.fromJson(WxResp.class, resp.getReader("UTF-8"));
            // 处理微信返回  40001 invalid credential
            if (wxResp.errcode() != 40001) {
                break;//正常直接返回
            } else {
                log.warnf("wxapi of access_token request [%s] finished, but the return code is 40001, try to reflush access_token right now, surplus retry times : %s", URL, retry);
                // 强制刷新一次acess_token
                reflushAccessToken();
            }
        } catch (Exception e) {
            if (retry >= 0) {
                log.warn("reflushing access_token... " + retry + " retries left.", e);
            } else {
                log.errorf("%s times attempts to get a wx access_token , but all failed!", retryTimes);
                throw Lang.wrapThrow(e);
            }
        } finally {
            retry--;
        }
    }
    return wxResp;
}
 
Example 16
Source File: HttpTool.java    From mpsdk4j with Apache License 2.0 4 votes vote down vote up
public static Object download(String url) {
    if (log.isDebugEnabled()) {
        log.debugf("Download url: %s, default timeout: %d", url, CONNECT_TIME_OUT);
    }

    try {
        Response resp = Http.get(url);
        if (resp.isOK()) {
            String cd = resp.getHeader().get("Content-disposition");
            if (log.isInfoEnabled()) {
                log.infof("Get download file info: %s", cd);
            }

            if (Lang.isEmpty(cd)) {
                return resp.getContent();
            }

            cd = cd.substring(cd.indexOf(FILE_NAME_FLAG) + FILE_NAME_FLAG.length());
            String tmp = cd.startsWith("\"") ? cd.substring(1) : cd;
            tmp = tmp.endsWith("\"") ? cd.replace("\"", "") : cd;
            String filename = tmp.substring(0, tmp.lastIndexOf("."));
            String fileext = tmp.substring(tmp.lastIndexOf("."));
            if (log.isInfoEnabled()) {
                log.infof("Download file name: %s", filename);
                log.infof("Download file ext: %s", fileext);
            }

            File tmpfile = File.createTempFile(filename, fileext);
            InputStream is = resp.getStream();
            OutputStream os = new FileOutputStream(tmpfile);
            Streams.writeAndClose(os, is);
            return tmpfile;
        }

        throw Lang.wrapThrow(new RuntimeException(String.format("Download file [%s] failed. status: %d, content: %s",
                                                                url,
                                                                resp.getStatus(),
                                                                resp.getContent())));
    }
    catch (Exception e) {
        throw Lang.wrapThrow(e);
    }
}
 
Example 17
Source File: WechatAPIImpl.java    From mpsdk4j with Apache License 2.0 4 votes vote down vote up
/**
 * 微信API响应输出
 * @param url   地址
 * @param methodType    请求方式 1:HTTP_GET, 2:HTTP_POST
 * @param body          POST数据内容
 * @param errorMsg      错误信息
 * @param params        错误信息参数
 * @return              {@link APIResult}
 */
protected APIResult wechatServerResponse(String url, int methodType, Object body, String errorMsg, Object... params) {
    APIResult ar = APIResult.create("{\"errCode\":0,\"errMsg\":\"OK\"}");
    for (int i=0; i < RETRY_COUNT; i++) {
        switch (methodType) {
            case 1:
                ar = APIResult.create(HttpTool.get(url));
                break;
            case 2:
                ar = APIResult.create(HttpTool.post(url, (String)body));
                break;
            case 3:
                ar = APIResult.create(HttpTool.upload(url, (File) body));
                break;
            case 4:
                Object tmp = HttpTool.download(url);
                if(tmp instanceof File) {
                    ar.getContent().put("file", tmp);
                } else {
                    ar = APIResult.create((String) tmp);
                }
                break;
            default:
                break;
        }

        if (ar != null && ar.isSuccess()) {
            return ar;
        }

        log.errorf("第%d尝试与微信服务器建立%s通讯.", (i+1), (methodType == HTTP_GET ? "HTTP GET" : "HTTP POST"));
        if (params == null){
            log.errorf(errorMsg, mpAct.getMpId());
        } else {
            Object[] args = new Object[params.length+1];
            args[0] = mpAct.getMpId();
            System.arraycopy(params, 0, args, 1, params.length);
            log.errorf(errorMsg, args);
            if (ar != null && !Lang.isEmpty(ar.getErrCNMsg())) {
                log.errorf(ar.getErrCNMsg());
            }
        }
    }

    throw Lang.wrapThrow(new WechatAPIException(ar.getJson()));
}