org.nutz.json.Json Java Examples

The following examples show how to use org.nutz.json.Json. 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: RestaurantController.java    From flash-waimai with MIT License 7 votes vote down vote up
@RequestMapping(value = "/v4/restaurants", method = RequestMethod.GET)
public Object restaurants(@RequestParam("geohash") String geoHash, @RequestParam("keyword") String keyWord) {
    String[] geoHashArr = geoHash.split(",");
    String longitude = geoHashArr[1];
    String latitude = geoHashArr[0];
    Map<String, Object> params = Maps.newHashMap("name", keyWord);
    System.out.println(Json.toJson(params));
    GeoResults<Map> geoResults = mongoRepository.near(Double.valueOf(longitude), Double.valueOf(latitude),
            "shops", params);
    List<GeoResult<Map>> geoResultList = geoResults.getContent();
    List<Map> list = Lists.newArrayList();
    for (int i = 0; i < geoResultList.size(); i++) {
        Map map = geoResultList.get(i).getContent();
        Distance distance = new Distance(Double.valueOf(longitude), Double.valueOf(latitude),
                Double.valueOf(map.get("longitude").toString()), Double.valueOf(map.get("latitude").toString()));
        map.put("distance", distance.getDistance());
        list.add(map);
    }
    return Rets.success(list);        
}
 
Example #2
Source File: JsonMsgBuilderTest.java    From mpsdk4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testTemplate() {
    log.info("====== JsonMsgBuilder#template ======");
    Template tmp = new Template();
    tmp.setColor("#ff0000");
    tmp.setName("百度一下你就知道");
    tmp.setValue("百度是中国的搜索引擎");

    String tmpJson = JsonMsgBuilder.create()
                                   .template(openId,
                                             tmplId,
                                             "#ff0000",
                                             "http://www.baidu.com",
                                             tmp)
                                   .build();
    assertNotNull(tmpJson);
    assertNotEquals(-1, tmpJson.indexOf("data"));
    assertNotNull(Json.fromJson(tmpJson));
    log.info(tmpJson);
}
 
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: AbstractWxApi2.java    From nutzwx with Apache License 2.0 6 votes vote down vote up
protected void reflushJsapiTicket() {
    String at = this.getAccessToken();
    String url = String.format("%s/ticket/getticket?access_token=%s&type=jsapi", base, at);
    if (log.isDebugEnabled())
        log.debugf("ATS: reflush jsapi ticket send: %s", url);

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

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

    NutMap re = Json.fromJson(NutMap.class, str);
    String ticket = re.getString("ticket");
    int expires = re.getInt("expires_in") - 200;//微信默认超时为7200秒,此处设置稍微短一点
    jsapiTicketStore.save(ticket, expires, System.currentTimeMillis());
}
 
Example #5
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 #6
Source File: SnakerIocLoader.java    From snakerflow with Apache License 2.0 6 votes vote down vote up
public SnakerIocLoader(String...paths) {
  	// 手工构建一个nutz的ioc bean定义
      iobj = new IocObject();
      iobj.setFactory(SnakerIocLoader.class.getName() +"#" + factoryMethodName); // 调用本类的buildSnaker方法
      iobj.setType(SnakerEngine.class); // 反馈类型
      IocValue ds = new IocValue();
      ds.setType(IocValue.TYPE_REFER);
      ds.setValue(dataSourceBeanName); // 引用数据源
      iobj.addArg(ds);
      for (String path : paths) {
      	IocValue p = new IocValue();
      	p.setValue(path);
      	iobj.addArg(p);
}
      if (log.isDebugEnabled())
      	log.debug("snakerflow bean will define as\n" + Json.toJson(iobj));
  }
 
Example #7
Source File: UserModule.java    From nutzcloud with Apache License 2.0 6 votes vote down vote up
/**
 * 这是演示api调用的入口,会顺序调用一堆请求,请关注日志
 */
@Ok("raw")
@At
public String apitest() {
    List<User> users = userService.list();
    log.info("users=" + Json.toJson(users));
    User haoqoo = userService.add("haoqoo", 19);
    User wendal = userService.add("wendal", 28);
    users = userService.list();
    log.info("users=" + Json.toJson(users));
    userService.delete(haoqoo.getId());
    userService.delete(wendal.getId());
    users = userService.list();
    log.info("users=" + Json.toJson(users));
    return "done";
}
 
Example #8
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 #9
Source File: WxApiImpl.java    From nutzwx with Apache License 2.0 6 votes vote down vote up
public void reflushAccessToken() {
    String url = String.format("%s/token?grant_type=client_credential&appid=%s&secret=%s",
                               base,
                               master.getAppid(),
                               master.getAppsecret());
    Response resp = Http.get(url);
    if (!resp.isOK())
        throw new IllegalArgumentException("reflushAccessToken FAIL , openid="
                                           + master.getOpenid());
    String str = resp.getContent();
    Map<String, Object> map = (Map<String, Object>) Json.fromJson(str);
    master.setAccess_token(map.get("token").toString());
    master.setAccess_token_expires(System.currentTimeMillis()
                                   + (((Number) map.get("expires_in")).intValue() - 60)
                                   * 1000);
}
 
Example #10
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 #11
Source File: WxApiImpl.java    From nutzwx with Apache License 2.0 6 votes vote down vote up
protected Map<String, Object> call(String URL, METHOD method, String body) {
    String token = getAccessToken();
    if (URL.contains("?")) {
        URL = base + URL + "&access_token=" + token;
    } else {
        URL = base + URL + "?access_token=" + token;
    }
    Request req = Request.create(URL, method);
    if (body != null)
        req.setData(body);
    Response resp = Sender.create(req).send();
    if (!resp.isOK())
        throw new IllegalArgumentException("resp code=" + resp.getStatus());
    Map<String, Object> map = (Map<String, Object>) Json.fromJson(resp.getReader());
    if (map != null
        && map.containsKey("errcode")
        && ((Number) map.get("errcode")).intValue() != 0) {
        throw new IllegalArgumentException(map.toString());
    }
    return map;
}
 
Example #12
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 #13
Source File: WxApiImpl.java    From nutzwx with Apache License 2.0 6 votes vote down vote up
@Override
public String mediaUpload(String type, File f) {
    if (type == null)
        throw new NullPointerException("media type is NULL");
    if (f == null)
        throw new NullPointerException("meida file is NULL");
    String url = String.format("http://file.api.weixin.qq.com/cgi-bin/media/upload?token=%s&type=%s",
                               getAccessToken(),
                               type);
    Request req = Request.create(url, METHOD.POST);
    req.getParams().put("media", f);
    Response resp = new FilePostSender(req).send();
    if (!resp.isOK())
        throw new IllegalStateException("media upload file, resp code=" + resp.getStatus());
    Map<String, Object> map = (Map<String, Object>) Json.fromJson(resp.getReader());
    if (map != null
        && map.containsKey("errcode")
        && ((Number) map.get("errcode")).intValue() != 0) {
        throw new IllegalArgumentException(map.toString());
    }
    return map.get("media_id").toString();
}
 
Example #14
Source File: AbstractWxHandler.java    From nutzwx with Apache License 2.0 6 votes vote down vote up
public WxOutMsg defaultMsg(WxInMsg msg) {
       if ("帮助".equals(msg.getContent()))
           return Wxs.respText(null, "支持的命令有: 你好 版本 帮助 appid 测试文本 测试新闻 回显");
       if ("你好".equals(msg.getContent()))
           return Wxs.respText(null, "你好!!");
       if ("版本".equals(msg.getContent()))
           return Wxs.respText(null, "Nutz " + Nutz.version());
       if ("appid".equals(msg.getContent()))
           return Wxs.respText(null, msg.getToUserName());
       if ("回显".equals(msg.getContent()))
           return Wxs.respText(null, Json.toJson(msg));
       if ("测试文本".equals(msg.getContent()))
           return Wxs.respText(null, "这真的是一条测试文本");
       if ("测试图片".equals(msg.getContent()))
           return Wxs.respImage(null, "not exist");
       if ("测试新闻".equals(msg.getContent())) {
           WxArticle nutzam = new WxArticle("官网", "nutz官网", "https://nutz.cn/rs/logo/logo.png", "http://nutzam.com");
           WxArticle nutzcn = new WxArticle("Nutz社区", "nutz官方社区", "https://nutz.cn/rs/logo/logo.png", "https://nutz.cn");
           return Wxs.respNews(null, nutzam, nutzcn);
       }
       if (WxMsgType.shortvideo.name().equals(msg.getMsgType())) {
           return Wxs.respText(null, "小视频?讨厌...");
       }
	return Wxs.respText("这是缺省回复哦.你发送的类型是:"+msg.getMsgType()+". http://nutz.cn");
}
 
Example #15
Source File: PositionService.java    From flash-waimai with MIT License 6 votes vote down vote up
@Cacheable(value = Cache.APPLICATION ,key = "#root.targetClass.simpleName+':'+#cityName+'-'+#keyword")
public List searchPlace(String cityName, String keyword) {
    logger.info("获取地址信息:{},{}",cityName,keyword);
    Map<String, String> params = Maps.newHashMap();
    params.put("key", appConfiguration.getTencentKey());
    params.put("keyword", URLEncoder.encode(keyword));
    params.put("boundary", "region(" + URLEncoder.encode(cityName) + ",0)");
    params.put("page_size", "10");
    try {
        String str = HttpClients.get(appConfiguration.getQqApiUrl() + "place/v1/search", params);
        Map result = (Map) Json.fromJson(str);
        if (Integer.valueOf(result.get("status").toString()).intValue() == 0) {
            return (List) result.get("data");
        }
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage());
    }
    return null;

}
 
Example #16
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 #17
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 #18
Source File: WxApi2Impl.java    From nutzwx with Apache License 2.0 5 votes vote down vote up
@Override
public WxResp media_upload(String type, File f) {
    if (type == null)
        throw new NullPointerException("media type is NULL");
    if (f == null)
        throw new NullPointerException("meida file is NULL");
    String url = String.format("%s/cgi-bin/media/upload?access_token=%s&type=%s", wxBase, getAccessToken(), type);
    Request req = Request.create(url, METHOD.POST);
    req.getParams().put("media", f);
    Response resp = new FilePostSender(req).send();
    if (!resp.isOK())
        throw new IllegalStateException("media upload file, resp code=" + resp.getStatus());
    return Json.fromJson(WxResp.class, resp.getReader("UTF-8"));
}
 
Example #19
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 #20
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 #21
Source File: WxApi2Impl.java    From nutzwx with Apache License 2.0 5 votes vote down vote up
@Override
public WxResp uploadimg(File f) {
    if (f == null)
        throw new NullPointerException("meida file is NULL");
    String url = String.format("%s/cgi-bin/media/uploadimg?access_token=%s", wxBase, getAccessToken());
    Request req = Request.create(url, METHOD.POST);
    req.getParams().put("media", f);
    Response resp = new FilePostSender(req).send();
    if (!resp.isOK())
        throw new IllegalStateException("uploadimg, resp code=" + resp.getStatus());
    return Json.fromJson(WxResp.class, resp.getReader("UTF-8"));
}
 
Example #22
Source File: WxApi2Impl.java    From nutzwx with Apache License 2.0 5 votes vote down vote up
@Override
public WxResp add_material(String type, File f) {
    if (f == null)
        throw new NullPointerException("meida file is NULL");
    String url = String.format("%s/cgi-bin/material/add_material?access_token=%s&type=%s",
                               wxBase,
                               getAccessToken(),
                               type);
    Request req = Request.create(url, METHOD.POST);
    req.getParams().put("media", f);
    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 #23
Source File: UserAPITest.java    From mpsdk4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetFollower() {
    log.info("====== UserAPI#getFollower ====== ");
    MockUpHttpGet(Json.toJson(follower));
    Follower f = wechatAPI.getFollower(openId, null);
    assertNotNull(f);
    assertEquals(f.getSubscribe(), 1);
}
 
Example #24
Source File: JsonMsgBuilderTest.java    From mpsdk4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testMusic() {
    log.info("====== JsonMsgBuilder#music ======");
    String musicJson = JsonMsgBuilder.create().music(musicMsg).build();
    assertNotNull(musicJson);
    assertNotEquals(-1, musicJson.indexOf("music"));
    assertNotNull(Json.fromJson(musicJson));
    log.info(musicJson);
}
 
Example #25
Source File: JsonMsgBuilderTest.java    From mpsdk4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testVideo() {
    log.info("====== JsonMsgBuilder#video ======");
    VideoMsg vim = new VideoMsg();
    vim.setToUserName(openId);
    vim.setMediaId(mediaId);
    vim.setThumbMediaId(mediaId);
    vim.setTitle("Video message");
    vim.setDescription("Video message.");
    String videoJson = JsonMsgBuilder.create().video(vim).build();
    assertNotNull(videoJson);
    assertNotEquals(-1, videoJson.indexOf("video"));
    assertNotNull(Json.fromJson(videoJson));
    log.info(videoJson);
}
 
Example #26
Source File: JsonMsgBuilderTest.java    From mpsdk4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testVoice() {
    log.info("====== JsonMsgBuilder#voice ======");
    VoiceMsg vom = new VoiceMsg();
    vom.setToUserName(openId);
    vom.setMediaId(mediaId);
    String voiceJson = JsonMsgBuilder.create().voice(vom).build();
    assertNotNull(voiceJson);
    assertNotEquals(-1, voiceJson.indexOf("voice"));
    assertNotNull(Json.fromJson(voiceJson));
    log.info(voiceJson);
}
 
Example #27
Source File: JsonMsgBuilderTest.java    From mpsdk4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testImage() {
    log.info("====== JsonMsgBuilder#image ======");
    ImageMsg im = new ImageMsg();
    im.setToUserName(openId);
    im.setMediaId(mediaId);
    String imgJson = JsonMsgBuilder.create().image(im).build();
    assertNotNull(imgJson);
    assertNotEquals(-1, imgJson.indexOf("image"));
    assertNotNull(Json.fromJson(imgJson));
    log.info(imgJson);
}
 
Example #28
Source File: JsonMsgBuilderTest.java    From mpsdk4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testText() {
    log.info("====== JsonMsgBuilder#text ======");
    TextMsg tm = new TextMsg();
    tm.setToUserName(openId);
    tm.setContent("Hello world! 世界,你好!");
    String textJson = JsonMsgBuilder.create().text(tm).build();
    assertNotNull(textJson);
    assertNotEquals(-1, textJson.indexOf("text"));
    assertNotNull(Json.fromJson(textJson));
    log.info(textJson);
}
 
Example #29
Source File: AllAPIRetryTest.java    From mpsdk4j with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void init() {
    log.info("====== AllAPIRetryTest ======");
    Object[] test2 = new Object[]{ 1, "2", 3};
    Object[] test3 = new Object[4];
    test3[0] = "0";
    System.arraycopy(test2, 0, test3, 1, test2.length);
    System.out.println(Json.toJson(test2));
    System.out.println(Json.toJson(test3));

}
 
Example #30
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);
}