org.nutz.json.JsonFormat Java Examples

The following examples show how to use org.nutz.json.JsonFormat. 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: AccessTokenAopInterceptor.java    From NutzSite with Apache License 2.0 6 votes vote down vote up
/**
 * 过滤器 验证登录
 * @param chain
 * @throws Throwable
 */
@Override
public void filter(InterceptorChain chain) throws Throwable {
    try {
        String token = Strings.sNull(Mvcs.getReq().getHeader("authorization"));
        if (JWTUtil.verifyToken(token)) {
            chain.doChain();
        }else {
            Mvcs.SKIP_COMMITTED =true;
            Mvcs.write(Mvcs.getResp(), Result.token(), JsonFormat.full());
        }
    } catch (Throwable e) {
        log.debug("aop.error", e);
        throw e;
    }
}
 
Example #2
Source File: WxApi2Impl.java    From nutzwx with Apache License 2.0 6 votes vote down vote up
@Override
public WxResp add_video(File f, String title, String introduction) {
    if (f == null)
        throw new NullPointerException("meida file is NULL");
    String url = String.format("%s/cgi-bin/material/add_material?type=video&access_token=%s",
                               wxBase,
                               getAccessToken());
    Request req = Request.create(url, METHOD.POST);
    req.getParams().put("media", f);
    req.getParams()
       .put("description",
            Json.toJson(new NutMap().setv("title", title).setv("introduction", introduction),
                        JsonFormat.compact().setQuoteName(true)));
    Response resp = new FilePostSender(req).send();
    if (!resp.isOK())
        throw new IllegalStateException("add_material, resp code=" + resp.getStatus());
    return Json.fromJson(WxResp.class, resp.getReader("UTF-8"));
}
 
Example #3
Source File: NutJsonFunction.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public Object call(Object[] paras, Context ctx) {
    switch (paras.length) {
    case 1:
        return Json.toJson(paras[0], JsonFormat.compact());
    case 2:
        Object t = paras[1];
        if (t != null && t instanceof String) {
            if ("full".equals(t)) {
                return Json.toJson(paras[0], JsonFormat.full());
            }
            if ("nice".equals(t)) {
                return Json.toJson(paras[0], JsonFormat.nice());
            }
            if ("compact".equals(t)) {
                return Json.toJson(paras[0], JsonFormat.compact());
            }
            if ("forLook".equals(t)) {
                return Json.toJson(paras[0], JsonFormat.forLook());
            }
            if ("tidy".equals(t)) {
                return Json.toJson(paras[0], JsonFormat.tidy());
            }
        }
    }
    throw new BeetlException(BeetlException.FUNCTION_INVALID);
}
 
Example #4
Source File: WechatAPIImpl.java    From mpsdk4j with Apache License 2.0 5 votes vote down vote up
@Override
public boolean createMenu(Menu... menu) {
    String url = mergeCgiBinUrl(createMenuURL + getAccessToken());
    Map<String, Object> body = new HashMap<String, Object>();
    body.put("button", menu);
    String data = Json.toJson(body, JsonFormat.compact());
    APIResult ar = wechatServerResponse(url,
            HTTP_POST,
            data,
            "生成公众号[%s]的自定义菜单失败.");
    return ar.isSuccess();
}
 
Example #5
Source File: WechatAPIImpl.java    From mpsdk4j with Apache License 2.0 5 votes vote down vote up
@Override
public boolean batchMove2Group(Collection<String> openIds, int groupId) {
    String url = mergeCgiBinUrl(updateMembersGroupURL + getAccessToken());
    Map<String, Object> data = new HashMap<String, Object>();
    data.put("openid_list", Json.toJson(openIds));
    data.put("to_groupid", groupId);
    APIResult ar = wechatServerResponse(url,
            HTTP_GET,
            Json.toJson(data, JsonFormat.compact()),
            "批量移动公众号[%s]的%d个用户到新分组[%d]失败.",
            openIds.size(),
            groupId);
    return ar.isSuccess();
}
 
Example #6
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 #7
Source File: WechatAPIImpl.java    From mpsdk4j with Apache License 2.0 5 votes vote down vote up
@Override
public List<Follower> getFollowers(Collection<Follower2> users) {
    String url = mergeCgiBinUrl(batchUserInfoURL + getAccessToken());
    String data = Json.toJson(Lang.map("user_list", users), JsonFormat.compact());
    APIResult ar = wechatServerResponse(url,
            HTTP_POST,
            data,
            "批量获取公众号[%s]的%d个用户信息失败.",
            users.size());
    return Json.fromJsonAsList(Follower.class, Json.toJson(ar.get("user_info_list")));
}
 
Example #8
Source File: MenuAPITest.java    From mpsdk4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetMenu() {
    log.info("====== MenuAPI#getMenu ======");

    String mockup_menus = "{\"menu\":{\"button\":"+Json.toJson(customerMenus,JsonFormat.compact())+"}}";
    MockUpHttpGet(mockup_menus);

    List<Menu> menus = wechatAPI.getMenu();
    assertNotNull(menus);
    assertEquals(menus.size(), 3);
}
 
Example #9
Source File: MemoryAccessTokenStore.java    From nutzwx with Apache License 2.0 5 votes vote down vote up
@Override
public void save(String token, int time, long lastCacheTimeMillis) {
    at = new WxAccessToken();
    at.setToken(token);
    at.setExpires(time);
    at.setLastCacheTimeMillis(lastCacheTimeMillis);
    log.debugf("new wx access token generated : \n %s", Json.toJson(at, JsonFormat.nice()));
}
 
Example #10
Source File: RedisAccessTokenStore.java    From nutzwx with Apache License 2.0 5 votes vote down vote up
@Override
public WxAccessToken get() {
    Jedis jedis = null;
    try {
        jedis = jedisPool.getResource();
        if (tokenKey == null) {
            throw new RuntimeException("Redis token key should not be null!");
        }
        Map<String, String> hash = jedis.hgetAll(tokenKey);
        if (Lang.isEmpty(hash)) {
            log.warnf("could not find a valid token in redis with key [%s]", tokenKey);
            return null;
        }
        WxAccessToken at = new WxAccessToken();// 从redis中拿出3个值组装成WxAccessToken返回
        at.setToken(hash.get("token"));
        at.setLastCacheTimeMillis(Long.valueOf(hash.get("lastCacheMillis")));
        at.setExpires(Integer.valueOf(hash.get("expires")));
        log.debugf("wx access_token fetched from redis with the key [%s] : \n %s",
                tokenKey,
                Json.toJson(at, JsonFormat.nice()));
        return at;
    } catch (Exception e) {
        log.error(e);
    } finally {
        // jedisPool.returnResource(jedis); //这是老版本归还连接的方法 已经deprecated
        jedis.close();// 2.9.0的方法直接close
    }
    return null;
}
 
Example #11
Source File: LoachClient.java    From nutzcloud with Apache License 2.0 4 votes vote down vote up
/**
 * 主逻辑
 */
public long exec() throws Exception {
    // 启动延时
    if (startUpDelay > 0) {
        log.debug("start up delay " + startUpDelay + "ms");
        int delay = startUpDelay;
        startUpDelay = 0;
        return delay;
    } else if (startUpDelay == -1) {
        if (!nbApp.isStarted())
            return 100;
    }
    // 心跳
    if (regOk) {
        // 尝试心跳,成功就是返回
        if (_ping()) {
            if (pingRetryCount > 0 && isDebug())
                log.debug("loach client ping OK");
            pingRetryCount = 0;
            return getPingInterval();
        } else {
            if (pingRetryCount < 5) {
                pingRetryCount++;
                log.info("loach client ping FAIL count=" + pingRetryCount);
                return getInterval();
            } else {
                regOk = false;
                log.info("loach client ping FAIL too many time, redo reg!");
            }
        }
    }
    NutMap regInfo = new NutMap();
    regInfo.put("id", id);
    regInfo.put("name", getServiceName());
    regInfo.put("vip", conf.get("server.vip", "127.0.0.1"));
    regInfo.put("port", appContext.getServerPort(null));
    regInfo.put("eth.mac", Networks.mac(NetworkType.LAN));
    regInfo.put("eth.ipv4", Networks.ipv4(NetworkType.LAN));
    regInfo.putAll(EXT_REG_DATA);
    String regData = Json.toJson(regInfo, JsonFormat.compact());
    _reg(regData);
    return getInterval();
}