org.nutz.lang.util.NutMap Java Examples

The following examples show how to use org.nutz.lang.util.NutMap. 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: UserUtils.java    From NutzSite with Apache License 2.0 6 votes vote down vote up
public static List<User_info_list> getUser(String token){
    String data = HttpUtils.sendGet(openIdUrl,"access_token="+token);
    OpenId openId =JSON.parseObject(data,OpenId.class);
    if(Lang.isNotEmpty(openId)){
        List<User_list> userLists =new ArrayList<>();
        openId.getData().getOpenid().forEach(oid->{
            User_list user =new User_list();
            user.setOpenid(oid);
            userLists.add(user);
        });
        String jsonData = JSON.toJSONString(NutMap.NEW().addv("user_list",userLists));
        String re = HttpUtils.sendPostJson(userInfoUrl + "?access_token="+ token ,  jsonData);
        UserData userData =JSON.parseObject(re,UserData.class);
        if(Lang.isNotEmpty(userData) && userData.getUser_info_list().size()>0){
            return userData.getUser_info_list();
        }
    }
    return null;
}
 
Example #2
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 #3
Source File: BeetlViewMakerTest.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void test_view_render() throws Throwable {
    // 存入模板
    loader.put("/hello", "${obj.array.~size},${obj.array[0]},${json(obj.user)}");
    
    // 创建视图
    View view = maker.make(null, "beetl", "/hello");
    
    // 准备好返回值
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("array", new String[]{"http://wendal.net"});
    map.put("user", new NutMap().setv("name", "wendal"));
    
    // 用于接收视图渲染的结果
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    
    // mock出req和resp
    HttpServletRequest req = mockReq(map);
    HttpServletResponse resp = mockResp(out);
    
    // 渲染
    view.render(req, resp, map);
    
    // 对比结果
    assertEquals("1,http://wendal.net,{\"name\":\"wendal\"}", new String(out.toByteArray()));
}
 
Example #4
Source File: AbstractWxApi2.java    From nutzwx with Apache License 2.0 6 votes vote down vote up
@Override
public NutMap genJsSDKConfig(String url, String... jsApiList) {
    String jt = this.getJsapiTicket();
    long timestamp = System.currentTimeMillis();
    String nonceStr = R.UU64();

    String str = String.format("jsapi_ticket=%s&noncestr=%s&timestamp=%d&url=%s", jt, nonceStr, timestamp, url);
    String signature = Lang.sha1(str);

    NutMap map = new NutMap();
    map.put("appId", appid);
    map.put("timestamp", timestamp);
    map.put("nonceStr", nonceStr);
    map.put("signature", signature);
    map.put("jsApiList", jsApiList);
    return map;
}
 
Example #5
Source File: LoachClient.java    From nutzcloud with Apache License 2.0 6 votes vote down vote up
protected boolean _ping() {
    try {
        String pingURL = url + "/ping/" + getServiceName() + "/" + id;
        if (isDebug())
            log.debug("Ping URL=" + pingURL);
        Request req = Request.create(pingURL, METHOD.GET);
        req.getHeader().clear();
        req.getHeader().set("If-None-Match", lastPingETag);
        Response resp = Sender.create(req, conf.getInt("loach.client.ping.timeout", 1000)).setConnTimeout(1000).send();
        String cnt = resp.getContent();
        if (isDebug())
            log.debug("Ping result : " + cnt);
        if (resp.isOK()) {
            lastPingETag = Strings.sBlank(resp.getHeader().get("ETag"), "ABC");
            NutMap re = Json.fromJson(NutMap.class, cnt);
            if (re != null && re.getBoolean("ok", false))
                return true;
        } else if (resp.getStatus() == 304) {
            return true;
        }
    }
    catch (Throwable e) {
        log.debugf("bad url? %s %s", url, e.getMessage());
    }
    return false;
}
 
Example #6
Source File: AbstractWxApi2.java    From nutzwx with Apache License 2.0 6 votes vote down vote up
protected synchronized void reflushAccessToken() {
      String url = String.format("%s/token?grant_type=client_credential&appid=%s&secret=%s", base, appid, appsecret);
      if (log.isDebugEnabled())
          log.debugf("ATS: reflush access_token send: %s", url);

      Response resp = Http.get(url);
      if (!resp.isOK())
          throw new IllegalArgumentException("reflushAccessToken FAIL , openid=" + openid);
      String str = resp.getContent();

      if (log.isDebugEnabled())
          log.debugf("ATS: reflush access_token done: %s", str);

      NutMap re = Json.fromJson(NutMap.class, str);
if(re.getInt("errcode", 0)!=0)
	throw new IllegalArgumentException("reflushAccessToken FAIL : " + str);
      String token = re.getString("access_token");
      int expires = re.getInt("expires_in") - 200;//微信默认超时为7200秒,此处设置稍微短一点
      accessTokenStore.save(token, expires, System.currentTimeMillis());
  }
 
Example #7
Source File: LoachClient.java    From nutzcloud with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void updateServiceList() {
    try {
        String listURL = url + "/list";
        Request req = Request.create(listURL, METHOD.GET);
        req.getHeader().clear();
        req.getHeader().set("If-None-Match", lastListETag);
        Response resp = Sender.create(req).setConnTimeout(1000).setTimeout(3000).send();
        if (resp.isOK()) {
            serviceList = (Map<String, List<NutMap>>) Json.fromJson(NutMap.class, resp.getReader()).get("data");
            for (UpdateListener listener : listeners) {
                listener.onUpdate(serviceList);
            }
            lastChecked = System.currentTimeMillis();
            lastListETag = Strings.sBlank(resp.getHeader().get("ETag", "ABC"));
        } else if (resp.getStatus() == 304) {
            // ok
            lastChecked = System.currentTimeMillis();
        }
    }
    catch (Throwable e) {
        log.debugf("bad url? %s %s", url, e.getMessage());
    }
}
 
Example #8
Source File: AbstractWxApi2.java    From nutzwx with Apache License 2.0 6 votes vote down vote up
protected void reflushCardTicket() {
    String at = this.getAccessToken();
    String url = String.format("%s/ticket/getticket?access_token=%s&type=wx_card", base, at);
    if (log.isDebugEnabled()) {
    	log.debugf("ATS: reflush wx_card ticket send: %s", url);
    }

    Response resp = Http.get(url);
    if (!resp.isOK()) {
        throw new IllegalArgumentException("reflushCardTicket FAIL , openid=" + openid);
    }
    String str = resp.getContent();

    if (log.isDebugEnabled()) {
        log.debugf("ATS: reflush wx_card ticket done: %s", str);
    }

    NutMap re = Json.fromJson(NutMap.class, str);
    String ticket = re.getString("ticket");
    int expires = re.getInt("expires_in") - 200;//微信默认超时为7200秒,此处设置稍微短一点
    cardTicketStore.save(ticket, expires, System.currentTimeMillis());
}
 
Example #9
Source File: WxApi2Impl.java    From nutzwx with Apache License 2.0 5 votes vote down vote up
@Override
public WxResp bindLocation(String uuid, int major, int minor, int poi_id) {
    NutMap params = new NutMap();
    params.put("device_identifier", new NutMap().setv("uuid", uuid).setv("major", major).setv("minor", minor));
    params.put("poi_id", poi_id);
    return postJson(wxBase + "/shakearound/device/bindlocation", params);
}
 
Example #10
Source File: WxLoginImpl.java    From nutzwx with Apache License 2.0 5 votes vote down vote up
@Override
public WxResp userinfo(String openid, String access_token) {
    // https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID
    Request req = Request.create("https://api.weixin.qq.com/sns/userinfo", METHOD.GET);
    NutMap params = new NutMap();
    params.put("access_token", access_token);
    params.put("openid", openid);
    req.setParams(params);
    Response resp = Sender.create(req).send();
    if (!resp.isOK()) {
        return null;
    }
    return Json.fromJson(WxResp.class, resp.getReader("UTF-8"));
}
 
Example #11
Source File: DefaultRpcInjectProxy.java    From nutzcloud with Apache License 2.0 5 votes vote down vote up
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    // 构建RpcReq
    RpcReq req = new RpcReq();
    req.klass = klass;
    req.args = args;
    req.object = proxy;
    req.connectTimeout = rpcInect.connectTimeout() == -1 ? 1000 : rpcInect.connectTimeout();
    req.timeout = rpcInect.timeout() == -1 ? 1000 : rpcInect.timeout();
    req.method = method;
    req.methodSign = LiteRpc.getMethodSign(method);
    // 获取支持该方法的服务器信息
    List<NutMap> servers = liteRpc.getServers(req.klass.getName(), req.methodSign);
    if (servers == null || servers.isEmpty()) {
        throw new RpcException("No server support : " + req.klass.getName() + "." + method.getName() + "(...)");
    }
    // 选一个,执行之
    NutMap server;
    if (servers.size() == 1) {
        server = servers.get(0);
    } else {
        server = servers.get((int) (AL.incrementAndGet() % servers.size()));
    }
    RpcResp resp = endpoint.send(req, server, serializer);
    if (resp.err == null)
        return resp.returnValue;
    throw resp.err;
}
 
Example #12
Source File: WxApi2Impl.java    From nutzwx with Apache License 2.0 5 votes vote down vote up
@Override
public WxResp createQRTicket(long expire, Type type, int id) {
    if (type != Type.EVER || type != Type.TEMP) {// 非整形场景自动适配一下
        return createQRTicket(expire, type, id + "");
    }
    NutMap json = NutMap.NEW();
    json.put("expire_seconds", expire);
    json.put("action_name", type.getValue());
    NutMap action = NutMap.NEW();
    NutMap scene = NutMap.NEW();
    scene.put("scene_id", id);
    action.put("scene", scene);
    json.put("action_info", action);
    return postJson("/qrcode/create", json);
}
 
Example #13
Source File: WxApi2Impl.java    From nutzwx with Apache License 2.0 5 votes vote down vote up
@Override
public WxResp createQRTicket(long expire, Type type, String str) {
    NutMap json = NutMap.NEW();
    json.put("expire_seconds", expire);
    json.put("action_name", type.getValue());
    NutMap action = NutMap.NEW();
    NutMap scene = NutMap.NEW();
    scene.put("scene_str", str);
    action.put("scene", scene);
    json.put("action_info", action);
    return postJson("/qrcode/create", json);
}
 
Example #14
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 #15
Source File: DemoFescarWebLauncher.java    From seata-samples with Apache License 2.0 5 votes vote down vote up
@Ok("json:full")
@At("/api/purchase")
public NutMap purchase(String userId, String commodityCode, int orderCount, boolean dofail) {
    try {
        businessService.purchase(userId, commodityCode, orderCount, dofail);
        return new NutMap("ok", true);
    }
    catch (Throwable e) {
        log.debug("purchase fail", e);
        return new NutMap("ok", false);
    }
}
 
Example #16
Source File: WechatAPIImpl.java    From mpsdk4j with Apache License 2.0 5 votes vote down vote up
@Override
public QRTicket createQR(Object sceneId, int expireSeconds) {
    String url = mergeCgiBinUrl(createQRCodeURL + getAccessToken());
    NutMap data = new NutMap();
    NutMap scene;
    // 临时二维码
    if (expireSeconds > 0) {
        data.put("action_name", "QR_SCENE");
        data.put("expire_seconds", expireSeconds);

        scene = Lang.map("scene_id", Castors.me().castTo(sceneId, Integer.class));
    }
    // 永久二维码
    else if (sceneId instanceof Number) {
        data.put("action_name", "QR_LIMIT_SCENE");
        scene = Lang.map("scene_id", Castors.me().castTo(sceneId, Integer.class));
    }
    // 永久字符串二维码
    else {
        data.put("action_name", "QR_LIMIT_STR_SCENE");
        scene = Lang.map("scene_str", sceneId.toString());
    }
    data.put("action_info", Lang.map("scene", scene));
    APIResult ar = wechatServerResponse(url,
            HTTP_POST,
            Json.toJson(data, JsonFormat.compact()),
            "创建公众号[%s]的[%s]场景二维码失败.");
    return Json.fromJson(QRTicket.class, Json.toJson(ar.getContent()));
}
 
Example #17
Source File: WxApi2Impl.java    From nutzwx with Apache License 2.0 5 votes vote down vote up
@Override
public WxResp bindLocation(int device_id, int poi_id) {
    NutMap params = new NutMap();
    params.put("device_identifier", new NutMap().setv("device_id", device_id));
    params.put("poi_id", poi_id);
    return postJson(wxBase + "/shakearound/device/bindlocation", params);
}
 
Example #18
Source File: WxApi2Impl.java    From nutzwx with Apache License 2.0 5 votes vote down vote up
@Override
public WxResp update(String uuid, int major, int minor, String comment) {
    NutMap params = new NutMap();
    params.put("device_identifier", new NutMap().setv("uuid", uuid).setv("major", major).setv("minor", minor));
    params.put("comment", comment);
    return postJson(wxBase + "/shakearound/device/update", params);
}
 
Example #19
Source File: WxApi2Impl.java    From nutzwx with Apache License 2.0 5 votes vote down vote up
@Override
public NutResource get_material(String media_id) {
    String url = String.format("%s/cgi-bin/material/get_material?access_token=%s", wxBase, getAccessToken());
    Request req = Request.create(url, METHOD.POST);
    NutMap body = new NutMap();
    body.put("media_id", media_id);
    req.setData(Json.toJson(body));
    final Response resp = Sender.create(req).send();
    if (!resp.isOK())
        throw new IllegalStateException("download media file, resp code=" + resp.getStatus());
    String disposition = resp.getHeader().get("Content-disposition");
    return new WxResource(disposition, resp.getStream());
}
 
Example #20
Source File: WxApi2Impl.java    From nutzwx with Apache License 2.0 5 votes vote down vote up
@Override
public WxResp update(int device_id, String comment) {
    NutMap params = new NutMap();
    params.put("device_identifier", new NutMap().setv("device_id", device_id));
    params.put("comment", comment);
    return postJson(wxBase + "/shakearound/device/update", params);
}
 
Example #21
Source File: WxApi2Impl.java    From nutzwx with Apache License 2.0 5 votes vote down vote up
@Override
public WxResp mass_sendall(boolean is_to_all, String group_id, WxOutMsg msg) {
    NutMap filter = new NutMap();
    filter.put("is_to_all", is_to_all);
    if (!is_to_all) {
        filter.put("group_id", group_id);
    }
    return this._mass_send(filter, null, null, msg);
}
 
Example #22
Source File: WxApi2Impl.java    From nutzwx with Apache License 2.0 5 votes vote down vote up
@Override
public WxResp qrcode_create(Object scene_id, int expire_seconds) {
    NutMap params = new NutMap();
    NutMap scene;
    // 临时二维码
    if (expire_seconds > 0) {
        params.put("expire_seconds", expire_seconds);

        // 临时整型二维码
        if (scene_id instanceof Number) {
            params.put("action_name", "QR_SCENE");
            scene = Lang.map("scene_id", Castors.me().castTo(scene_id, Integer.class));
            // 临时字符串二维码
        } else {
            params.put("action_name", "QR_STR_SCENE");
            scene = Lang.map("scene_str", scene_id.toString());
        }
    }
    // 永久二维码
    else if (scene_id instanceof Number) {
        params.put("action_name", "QR_LIMIT_SCENE");
        scene = Lang.map("scene_id", Castors.me().castTo(scene_id, Integer.class));
    }
    // 永久字符串二维码
    else {
        params.put("action_name", "QR_LIMIT_STR_SCENE");
        scene = Lang.map("scene_str", scene_id.toString());
    }
    params.put("action_info", Lang.map("scene", scene));
    return postJson("/qrcode/create", params);
}
 
Example #23
Source File: WxApiImpl.java    From nutzwx with Apache License 2.0 5 votes vote down vote up
public String sendTemplateMsg(String touser,
                              String template_id,
                              String topcolor,
                              Map<String, WxTemplateData> data) {
    if (Strings.isBlank(topcolor))
        topcolor = WxTemplateData.DFT_COLOR;
    NutMap map = new NutMap();
    map.put("touser", touser);
    map.put("template_id", template_id);
    map.put("topcolor", topcolor);
    map.put("data", data);
    return call("/message/template/send", METHOD.POST, Json.toJson(map)).get("msgid")
                                                                        .toString();
}
 
Example #24
Source File: WxApi2Impl.java    From nutzwx with Apache License 2.0 5 votes vote down vote up
/**
 * 微信公众号JS支付
 *
 * @param key
 *            商户KEY
 * @param wxPayUnifiedOrder
 *            交易订单内容
 * @return
 */
@Override
public NutMap pay_jsapi(String key, WxPayUnifiedOrder wxPayUnifiedOrder) {
    NutMap map = this.pay_unifiedorder(key, wxPayUnifiedOrder);
    NutMap params = NutMap.NEW();
    params.put("appId", wxPayUnifiedOrder.getAppid());
    params.put("timeStamp", String.valueOf((int) (System.currentTimeMillis() / 1000)));
    params.put("nonceStr", R.UU32());
    params.put("package", "prepay_id=" + map.getString("prepay_id"));
    params.put("signType", "MD5");
    String sign = WxPaySign.createSign(key, params);
    params.put("paySign", sign);
    return params;
}
 
Example #25
Source File: BeanConfigures.java    From nutzwx with Apache License 2.0 5 votes vote down vote up
public static Map<String, Object> toMap(Properties properties) {
	NutMap map = new NutMap();
	for (Entry<Object, Object> en : properties.entrySet()) {
		map.put(en.getKey().toString(), en.getValue());
	}
	if (map.isEmpty())
		return null;
	return map;
}
 
Example #26
Source File: AbstractWxApi2.java    From nutzwx with Apache License 2.0 5 votes vote down vote up
protected WxResp postJson(String uri, Object... args) {
    NutMap body = new NutMap();
    for (int i = 0; i < args.length; i += 2) {
        body.put(args[i].toString(), args[i + 1]);
    }
    return postJson(uri, body);
}
 
Example #27
Source File: Wxs.java    From nutzwx with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
public static void mapField(StringBuilder sb, Class<?> klass, Field field) {
    sb.append("\r\n");
    String fieldName = field.getName();
    String className = klass.getSimpleName();
    Mirror mirror = Mirror.me(field.getType());
    String getterTmpl = "return (${fieldType})get(\"${fieldName}\")";
    if (mirror.isPrimitiveNumber()) {
        if (mirror.isBoolean()) {
            getterTmpl = "return getBoolean(\"${fieldName}\", false)";
        } else {
            getterTmpl = "return get"
                         + Strings.upperFirst(mirror.getType().getSimpleName())
                         + "(\"${fieldName}\", 0)";
        }
    }

    Tmpl tmpl = Tmpl.parse("    public ${className} set${upperFieldName}(${fieldType} ${fieldName}){\r\n"
                           + "        put(\"${fieldName}\", ${fieldName});\r\n"
                           + "        return this;\r\n"
                           + "    }\r\n"
                           + "\r\n"
                           + "    public ${fieldType} get${upperFieldName}(){\r\n"
                           + "        "
                           + getterTmpl
                           + ";\r\n"
                           + "    }\r\n");
    NutMap ctx = new NutMap().setv("className", className).setv("fieldName", fieldName);
    ctx.setv("upperFieldName", Strings.upperFirst(fieldName));
    ctx.setv("fieldType", field.getType().getSimpleName());
    sb.append(tmpl.render(ctx));
}
 
Example #28
Source File: WxLoginImpl.java    From nutzwx with Apache License 2.0 5 votes vote down vote up
@Override
public WxResp access_token(String code) {
    Request req = Request.create("https://api.weixin.qq.com/sns/oauth2/access_token", METHOD.GET);
    NutMap params = new NutMap();
    params.put("appid", appid);
    params.put("secret", appsecret);
    params.put("code", code);
    params.put("grant_type", "authorization_code");
    req.setParams(params);
    Response resp = Sender.create(req).send();
    if (!resp.isOK()) {
        return null;
    }
    return Json.fromJson(WxResp.class, resp.getReader("UTF-8"));
}
 
Example #29
Source File: SwaggerDemoModule.java    From NutzSite with Apache License 2.0 5 votes vote down vote up
@GET
@ApiOperation(value = "心跳接口", notes = "发我一个ping,回你一个pong", httpMethod="GET")
@At
@Ok("json:full")
public Object ping() {
    return new NutMap("ok", true).setv("data", "pong");
}
 
Example #30
Source File: WxApi2Impl.java    From nutzwx with Apache License 2.0 4 votes vote down vote up
@Override
public WxResp uploadnews(List<WxMassArticle> articles) {
    // 用postJson方法总是抛空指针异常,只好用下面写法了,不知道原因
    return call("/media/uploadnews", METHOD.POST, Json.toJson(new NutMap().setv("articles", articles)));
}