/** * get user profile by access token and client id * * @return * @throws OAuthSdkException */ public UserProfile getUserProfile() throws OAuthSdkException { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(OPEN_CLIENT_ID, String.valueOf(clientId))); params.add(new BasicNameValuePair(ACCESS_TOKEN, accessToken)); JSONObject json = this.request(HttpMethod.GET, USER_PROFILE_PATH, params); if (!this.isSuccessResult(json)) { // error response int errorCode = json.optInt("code", -1); String errorDesc = json.optString("description", StringUtils.EMPTY); log.error("Get user profile error, error info[code={}, desc={}]", errorCode, errorDesc); throw new OAuthSdkException("get user profile error", errorCode, errorDesc); } String data = json.optString("data", StringUtils.EMPTY); if (StringUtils.isBlank(data) || !JSONUtils.mayBeJSON(data)) { log.error("Response json missing 'data' element or not json format, data[{}]", data); } log.debug("Get user profile json response [{}]", data); return new UserProfile(JSONObject.fromObject(data)); }
/** * get open id by access token and client id * * @return * @throws OAuthSdkException */ public String getOpenId() throws OAuthSdkException { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(OPEN_CLIENT_ID, String.valueOf(clientId))); params.add(new BasicNameValuePair(ACCESS_TOKEN, accessToken)); JSONObject json = this.request(HttpMethod.GET, OPEN_ID_PATH, params); if (!this.isSuccessResult(json)) { // error response int errorCode = json.optInt("code", -1); String errorDesc = json.optString("description", StringUtils.EMPTY); log.error("Get user open id error, error info[code={}, desc={}]", errorCode, errorDesc); throw new OAuthSdkException("get user open id error", errorCode, errorDesc); } String data = json.optString("data", StringUtils.EMPTY); if (StringUtils.isBlank(data) || !JSONUtils.mayBeJSON(data)) { log.error("Response json missing 'data' element or not json format, data[{}]", data); } log.debug("Get open id json response [{}]", data); return JSONObject.fromObject(data).optString(OPEN_ID, StringUtils.EMPTY); }
@Override public void registerObjects(ResourceRegister register) { this.config.clearPropertyExclusions(); if (!register.isEmpty()) { Set<Class<? extends Enum<?>>> enums = new HashSet<Class<? extends Enum<?>>>(); Collection<ClassDescriptor> cls = register.getClassDescriptors(); Map<String, Class<?>> classMap = new Hashtable<String, Class<?>>(cls.size()); for (ClassDescriptor cl : cls) { Class<?> clazz = cl.getTargetClass(); if (Enum.class.isAssignableFrom(clazz)) { enums.add((Class<? extends Enum<?>>) clazz); } else { classMap.put(cl.getName(), clazz); Collection<String> fields = cl.getExcludesFields(); for (String fieldName : fields) { this.config.registerPropertyExclusion(clazz, fieldName); } } } MorpherRegistry morpherRegistry = JSONUtils.getMorpherRegistry(); for (Class<? extends Enum> e : enums) { morpherRegistry.registerMorpher(new EnumMorpher(e)); } this.config.setClassMap(classMap); } }
public void testReadObject() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JsonLibModule()); JSONObject ob = mapper.readValue("{\"a\":{\"b\":3}, \"c\":[9, -4], \"d\":null, \"e\":true}", JSONObject.class); assertEquals(4, ob.size()); JSONObject ob2 = ob.getJSONObject("a"); assertEquals(1, ob2.size()); assertEquals(3, ob2.getInt("b")); JSONArray array = ob.getJSONArray("c"); assertEquals(2, array.size()); assertEquals(9, array.getInt(0)); assertEquals(-4, array.getInt(1)); assertTrue(JSONUtils.isNull(ob.get("d"))); assertTrue(ob.getBoolean("e")); }
public void testReadArray() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JsonLibModule()); JSONArray array = mapper.readValue("[null, 13, false, 1.25, \"abc\", {\"a\":13}, [ ] ]", JSONArray.class); assertEquals(7, array.size()); assertTrue(JSONUtils.isNull(array.get(0))); assertEquals(13, array.getInt(1)); assertFalse(array.getBoolean(2)); assertEquals(Double.valueOf(1.25), array.getDouble(3)); assertEquals("abc", array.getString(4)); JSONObject ob = array.getJSONObject(5); assertEquals(1, ob.size()); assertEquals(13, ob.getInt("a")); JSONArray array2 = array.getJSONArray(6); assertEquals(0, array2.size()); }
/** * Parses raw JSON data and returns the found strings. * * @param jsonName Name of attribute which is needed. * @param data Contains raw JSON data. * @return List of strings which were found by jsonName. */ private List<String> parseListFromData(String jsonName, String data) { final List<String> result = new ArrayList<String>(); final JSON json = JSONSerializer.toJSON(data); final Object jsonObject = ((JSONObject)json).get(jsonName); if (JSONUtils.isArray(jsonObject)) { Collection<String> jsonPaths = JSONArray.toCollection((JSONArray)jsonObject, String.class); for (String jsonPath : jsonPaths) { result.add(trimJSONPath(jsonPath)); } } else { result.add(trimJSONPath(String.valueOf(jsonObject))); } return result; }
/** * Returns the value of a key from a given JSON String. * * @param key Key to search after. * @param jsonString Given JSON String, in which the key should be in. * @return The value of the key in the JSON string. */ public static ArrayList<String> getValueFromJSONString(String key, String jsonString) { final ArrayList<String> result = new ArrayList<String>(); LOG.info("JSON STRING: " + jsonString); final JSON json = JSONSerializer.toJSON(jsonString); final Object jsonObject = ((JSONObject)json).get(key); if (JSONUtils.isArray(jsonObject)) { Collection<String> jsonPaths = JSONArray.toCollection((JSONArray)jsonObject, String.class); for (String jsonPath : jsonPaths) { result.add(trimJSONSlashes(jsonPath)); } } else { if (!String.valueOf(jsonObject).equals("null")) { result.add(CCRUtils.trimJSONSlashes(String.valueOf(jsonObject))); } } return result; }
/** * refresh access token by refresh token * * @param refreshToken * @return * @throws OAuthSdkException */ public AccessToken refreshAccessToken(String refreshToken) throws OAuthSdkException { // prepare params List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(CLIENT_ID, String.valueOf(client.getId()))); params.add(new BasicNameValuePair(REDIRECT_URI, client.getRedirectUri())); params.add(new BasicNameValuePair(CLIENT_SECRET, client.getSecret())); params.add(new BasicNameValuePair(GRANT_TYPE, GrantType.REFRESH_TOKEN.getType())); params.add(new BasicNameValuePair(TOKEN_TYPE, AccessToken.TokenType.MAC.getType())); params.add(new BasicNameValuePair(REFRESH_TOKEN, refreshToken)); HttpResponse response = httpClient.get(AuthorizeUrlUtils.getTokenUrl(), params); log.debug("Refresh access token response[{}]", response); String entityContent = HttpResponseUtils.getEntityContent(response); if (StringUtils.isBlank(entityContent) || !JSONUtils.mayBeJSON(entityContent)) { log.error("The refresh token response[{}] is not json format!", entityContent); throw new OAuthSdkException("The refresh token response is not json format"); } JSONObject json = JSONObject.fromObject(entityContent); if (json.has("access_token")) { log.debug("Refresh access token json result[{}]", json); return new AccessToken(json); } // error response int errorCode = json.optInt("error", -1); String errorDesc = json.optString("error_description", StringUtils.EMPTY); log.error("Refresh access token error, error info [code={}, desc={}]!", errorCode, errorDesc); throw new OAuthSdkException("Refresh access token error!", errorCode, errorDesc); }
/** * send request to specify url with params and expected json response * * @param path the path part of api url, /user/profile etc. * @param method GET or POST * @param params query params * @param headers query http headers * @return json response data * @throws OAuthSdkException */ protected JSONObject request( HttpMethod method, String path, List<NameValuePair> params, List<Header> headers) throws OAuthSdkException { // params format List<NameValuePair> paramList = (null == params) ? new ArrayList<NameValuePair>() : params; List<Header> headerList = (null == headers) ? new ArrayList<Header>() : headers; Header[] headerArray = new Header[0]; if (CollectionUtils.isEmpty(headers)) { headerArray = new Header[headerList.size()]; headerArray = headerList.toArray(headerArray); } HttpResponse response; if (HttpMethod.GET.equals(method)) { response = httpClient.get(GlobalConstants.OPEN_API_HOST + path, params, headerArray); } else if (HttpMethod.POST.equals(method)) { response = httpClient.post(GlobalConstants.OPEN_API_HOST + path, params, headerArray); } else { log.error("The http method [{}] is unsupported!", method); throw new OAuthSdkException("unsupported http method"); } String entityContent = HttpResponseUtils.getEntityContent(response); if (StringUtils.isBlank(entityContent) || !JSONUtils.mayBeJSON(entityContent)) { log.error("The response data is not json format, data[{}]", entityContent); throw new OAuthSdkException("response data is not json"); } return JSONObject.fromObject(entityContent); }
/** * get access code by authorization code * * @param code authorization code * @return * @throws OAuthSdkException when encounter error response */ public AccessToken getAccessTokenByCode(String code) throws OAuthSdkException { log.debug("Get access token by code..."); // prepare params List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(CLIENT_ID, String.valueOf(client.getId()))); params.add(new BasicNameValuePair(REDIRECT_URI, client.getRedirectUri())); params.add(new BasicNameValuePair(CLIENT_SECRET, client.getSecret())); params.add(new BasicNameValuePair(GRANT_TYPE, GrantType.AUTHORIZATION_CODE.getType())); params.add(new BasicNameValuePair(CODE, code)); params.add(new BasicNameValuePair(TOKEN_TYPE, AccessToken.TokenType.MAC.getType())); HttpResponse response = httpClient.get(AuthorizeUrlUtils.getTokenUrl(), params); log.debug("Get authorization code access token response[{}]", response); String entityContent = HttpResponseUtils.getEntityContent(response); if (StringUtils.isBlank(entityContent) || !JSONUtils.mayBeJSON(entityContent)) { log.error("The response[{}] is not json format!", entityContent); throw new OAuthSdkException("The response is not json format"); } JSONObject json = JSONObject.fromObject(entityContent); if (json.has("access_token")) { log.debug("Get authorization code access token json result[{}]", json); return new AccessToken(json); } // error response int errorCode = json.optInt("error", -1); String errorDesc = json.optString("error_description", StringUtils.EMPTY); log.error("Get authorization code access token error, error info [code={}, desc={}]!", errorCode, errorDesc); throw new OAuthSdkException("Get authorization code access token error!", errorCode, errorDesc); }
@Override public String getJson() { if (json == null) { final StringBuilder b = new StringBuilder("{\"p\":" + JSONUtils.quote(path) + ",\"l\":" + live + ",\"f\":" + first + ",\"h\":" + allLogsHash + ",\"u\":" + filePointer.getJson()); if (liveNext != null) { b.append(",\"n\":" + JSONUtils.quote(liveNext)); } b.append("}"); json = b.toString(); } return json; }
protected void serializeContents(JSONArray value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { for (int i = 0, len = value.size(); i < len; ++i) { Object ob = value.opt(i); if (ob == null || JSONUtils.isNull(ob)) { jgen.writeNull(); continue; } Class<?> cls = ob.getClass(); if (cls == JSONObject.class) { JSONObjectSerializer.instance.serialize((JSONObject) ob, jgen, provider); } else if (cls == JSONArray.class) { serialize((JSONArray) ob, jgen, provider); } else if (cls == String.class) { jgen.writeString((String) ob); } else if (cls == Integer.class) { jgen.writeNumber(((Integer) ob).intValue()); } else if (cls == Long.class) { jgen.writeNumber(((Long) ob).longValue()); } else if (cls == Boolean.class) { jgen.writeBoolean(((Boolean) ob).booleanValue()); } else if (cls == Double.class) { jgen.writeNumber(((Double) ob).doubleValue()); } else if (JSONObject.class.isAssignableFrom(cls)) { // sub-class JSONObjectSerializer.instance.serialize((JSONObject) ob, jgen, provider); } else if (JSONArray.class.isAssignableFrom(cls)) { // sub-class serialize((JSONArray) ob, jgen, provider); } else if (JSONArray.class.isAssignableFrom(cls)) { // sub-class JSONArraySerializer.instance.serialize((JSONArray) ob, jgen, provider); } else { provider.defaultSerializeValue(ob, jgen); } } }
private static void setDataFormat2JAVA() { // 设定日期转换格式 JSONUtils.getMorpherRegistry().registerMorpher( new DateMorpher(new String[] { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss" })); }
/** * Registers a custom Morpher to handle, based on the input flag, either a DateTime or DateOnly class. */ private static void registerCustomDateMorpher(boolean dateTime) { final Class targetType = dateTime ? DateTime.class : DateOnly.class; Morpher targetMorpher = JSONUtils.getMorpherRegistry().getMorpherFor(targetType); if (targetMorpher == null || targetMorpher == IdentityObjectMorpher.getInstance()) { synchronized (JSONUtils.getMorpherRegistry()) { targetMorpher = JSONUtils.getMorpherRegistry().getMorpherFor(targetType); if (targetMorpher == null || targetMorpher == IdentityObjectMorpher.getInstance()) { // Create a custom Morpher targetMorpher = new ObjectMorpher() { /** * Returns the target Class (DateTime.class or DateOnly.class) for conversion. */ public Class morphsTo() { return targetType; } /** * Returns true if the Morpher supports conversion from this Class. Only the String class is supported currently. */ public boolean supports(Class clazz) { return clazz == String.class; } /** * Morphs the input object into an output object of the supported type. */ public Object morph(Object value) { try { String layout = "yyyy-MM-dd'T'HH:mm:ss"; return targetType == DateTime.class ? Parser.parseDateTime((String) value, layout) : Parser.parseDateOnly((String) value, layout); } catch (Exception e) { if (log.isDebugEnabled()) log.debug("Error in converting '" + value + "' to " + (targetType == DateTime.class ? "DateTime" : "DateOnly"), e); return value; } } }; JSONUtils.getMorpherRegistry().registerMorpher(targetMorpher); } } } }
/** * 获取自动回复规则 * @param accessToken * @return */ public static AutoReplyInfoRule getAutoReplyInfoRule(String accessToken) throws WexinReqException{ AutoReplyRuleGet arr = new AutoReplyRuleGet(); arr.setAccess_token(accessToken); JSONObject result = WeiXinReqService.getInstance().doWeinxinReqJson(arr); Object error = result.get(WeiXinConstant.RETURN_ERROR_INFO_CODE); AutoReplyInfoRule autoReplyInfoRule = (AutoReplyInfoRule) JSONObject.toBean(result,new CustomJsonConfig(AutoReplyInfoRule.class, "keyword_autoreply_info")); JSONObject keywordAutoReplyInfoJsonObj = result.getJSONObject("keyword_autoreply_info"); if(keywordAutoReplyInfoJsonObj!=null && !JSONUtils.isNull(keywordAutoReplyInfoJsonObj)){ /**关键词自动回复的信息 */ JSONArray keywordAutoReplyInfos = keywordAutoReplyInfoJsonObj.getJSONArray("list"); if(keywordAutoReplyInfos!=null){ List<KeyWordAutoReplyInfo> listKeyWordAutoReplyInfo = new ArrayList<KeyWordAutoReplyInfo>(); for(int i=0;i<keywordAutoReplyInfos.size();i++){ KeyWordAutoReplyInfo keyWordAutoReplyInfo = (KeyWordAutoReplyInfo) JSONObject.toBean(keywordAutoReplyInfos.getJSONObject(i),new CustomJsonConfig(KeyWordAutoReplyInfo.class, new String[]{"keyword_list_info","reply_list_info"})); /**处理关键词列表 */ JSONArray keywordListInfos = keywordAutoReplyInfos.getJSONObject(i).getJSONArray("keyword_list_info"); if(keywordListInfos!=null){ List<KeywordListInfo> listKeywordListInfo = new ArrayList<KeywordListInfo>(); for(int j=0;j<keywordListInfos.size();j++){ KeywordListInfo keywordListInfo = (KeywordListInfo) JSONObject.toBean(keywordListInfos.getJSONObject(j),KeywordListInfo.class); listKeywordListInfo.add(keywordListInfo); } keyWordAutoReplyInfo.setKeyword_list_info(listKeywordListInfo); } /**处理关键字回复信息 */ JSONArray replyListInfos = keywordAutoReplyInfos.getJSONObject(i).getJSONArray("reply_list_info"); if(replyListInfos!=null){ List<ReplyListInfo> listReplyListInfo = new ArrayList<ReplyListInfo>(); for(int j=0;j<replyListInfos.size();j++){ ReplyListInfo replyListInfo = (ReplyListInfo) JSONObject.toBean(keywordListInfos.getJSONObject(j),new CustomJsonConfig(ReplyListInfo.class, "news_info")); /**处理关键字回复相关图文消息 */ JSONObject newsInfoJsonObj = replyListInfos.getJSONObject(j).getJSONObject("news_info"); if(newsInfoJsonObj!=null && !JSONUtils.isNull(newsInfoJsonObj)){ JSONArray newsInfos = newsInfoJsonObj.getJSONArray("list"); List<WxArticleConfig> listNewsInfo = new ArrayList<WxArticleConfig>(); for (int k = 0; k < newsInfos.size(); k++) { WxArticleConfig wxArticleConfig = (WxArticleConfig) JSONObject.toBean(newsInfos.getJSONObject(k), WxArticleConfig.class); listNewsInfo.add(wxArticleConfig); } replyListInfo.setNews_info(listNewsInfo); } listReplyListInfo.add(replyListInfo); } keyWordAutoReplyInfo.setReply_list_info(listReplyListInfo); } listKeyWordAutoReplyInfo.add(keyWordAutoReplyInfo); } autoReplyInfoRule.setKeyword_autoreply_info(listKeyWordAutoReplyInfo); } } return autoReplyInfoRule; }
/** * 获取自定义接口配置 * @param accessToken * @return * @throws WexinReqException */ public static CustomWeixinButtonConfig getAllMenuConfigure(String accessToken) throws WexinReqException{ MenuConfigureGet cmcg = new MenuConfigureGet(); cmcg.setAccess_token(accessToken); JSONObject result = WeiXinReqService.getInstance().doWeinxinReqJson(cmcg); Object error = result.get(WeiXinConstant.RETURN_ERROR_INFO_CODE); CustomWeixinButtonConfig customWeixinButtonConfig = (CustomWeixinButtonConfig) JSONObject.toBean(result, new CustomJsonConfig(CustomWeixinButtonConfig.class,"selfmenu_info")); JSONObject selfmenuInfo = result.getJSONObject("selfmenu_info"); if(selfmenuInfo!=null && !JSONUtils.isNull(selfmenuInfo)){ /**处理父类菜单 */ JSONArray buttons = selfmenuInfo.getJSONArray("button"); List<WeixinButtonExtend> listButton = new ArrayList<WeixinButtonExtend>(); for(int i=0;i<buttons.size();i++){ WeixinButtonExtend weixinButtonExtend = (WeixinButtonExtend) JSONObject.toBean(buttons.getJSONObject(i),new CustomJsonConfig(WeixinButtonExtend.class,"sub_button")); /**处理子类菜单 */ JSONObject subButtonJsonObj = buttons.getJSONObject(i).getJSONObject("sub_button"); if(subButtonJsonObj!=null && !JSONUtils.isNull(subButtonJsonObj)){ JSONArray subButtons = subButtonJsonObj.getJSONArray("list"); if (subButtons != null) { List<WeixinButtonExtend> listSubButton = new ArrayList<WeixinButtonExtend>(); for (int j = 0; j < subButtons.size(); j++) { WeixinButtonExtend subBtn = (WeixinButtonExtend) JSONObject.toBean(subButtons.getJSONObject(j), new CustomJsonConfig(WeixinButtonExtend.class,"news_info")); /**处理菜单关联的图文消息 */ JSONObject newsInfoJsonObj = subButtons.getJSONObject(j).getJSONObject("news_info"); if(newsInfoJsonObj!=null && !JSONUtils.isNull(newsInfoJsonObj)){ JSONArray newsInfos = newsInfoJsonObj.getJSONArray("list"); List<WxArticleConfig> listNewsInfo = new ArrayList<WxArticleConfig>(); for (int k = 0; k < newsInfos.size(); k++) { WxArticleConfig wxArticleConfig = (WxArticleConfig) JSONObject.toBean(newsInfos.getJSONObject(k), WxArticleConfig.class); listNewsInfo.add(wxArticleConfig); } subBtn.setNews_info(listNewsInfo); } listSubButton.add(subBtn); } weixinButtonExtend.setSub_button(listSubButton); } } listButton.add(weixinButtonExtend); } customWeixinButtonConfig.setSelfmenu_info(listButton); } return customWeixinButtonConfig; }
protected void serializeContents(JSONObject value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { Iterator<?> it = value.keys(); while (it.hasNext()) { String key = (String) it.next(); Object ob; try { ob = value.get(key); } catch (JSONException e) { throw new JsonGenerationException(e); } if (ob == null || JSONUtils.isNull(ob)) { if (provider.isEnabled(SerializationFeature.WRITE_NULL_MAP_VALUES)) { jgen.writeNullField(key); } continue; } jgen.writeFieldName(key); Class<?> cls = ob.getClass(); if (cls == JSONObject.class) { serialize((JSONObject) ob, jgen, provider); } else if (cls == JSONArray.class) { JSONArraySerializer.instance.serialize((JSONArray) ob, jgen, provider); } else if (cls == String.class) { jgen.writeString((String) ob); } else if (cls == Integer.class) { jgen.writeNumber(((Integer) ob).intValue()); } else if (cls == Long.class) { jgen.writeNumber(((Long) ob).longValue()); } else if (cls == Boolean.class) { jgen.writeBoolean(((Boolean) ob).booleanValue()); } else if (cls == Double.class) { jgen.writeNumber(((Double) ob).doubleValue()); } else if (cls == JSONArray.class) { JSONArraySerializer.instance.serialize((JSONArray) ob, jgen, provider); } else if (JSONObject.class.isAssignableFrom(cls)) { // sub-class serialize((JSONObject) ob, jgen, provider); } else if (JSONArray.class.isAssignableFrom(cls)) { // sub-class JSONArraySerializer.instance.serialize((JSONArray) ob, jgen, provider); } else { provider.defaultSerializeValue(ob, jgen); } } }