@Override public void updateConnectorData(UpdateInfo updateInfo) throws Exception { int retrievedItems = ITEMS_PER_PAGE; long lastUploadTime = getLastUploadTime(updateInfo); for (int page = 0; retrievedItems == ITEMS_PER_PAGE; page++) { JSONObject feed = retrievePhotoHistory(updateInfo, lastUploadTime, System.currentTimeMillis(), page); if (!(feed.getString("stat").equalsIgnoreCase("ok"))) { String message = "n/a"; if (feed.containsKey("message")) message = feed.getString("message"); throw new Exception("There was an error calling the Flickr API: " + message); } JSONObject photosWrapper = feed.getJSONObject("photos"); if (photosWrapper != null) { if (photosWrapper.containsKey("photo")) { JSONArray photos = photosWrapper.getJSONArray("photo"); retrievedItems = photos.size(); apiDataService.cacheApiDataJSON(updateInfo, feed, -1, -1); } else break; } else break; } }
@Override @SuppressWarnings({"rawtypes", "unchecked"}) @Post public Representation post(Representation entity) { Form form = new Form(entity); String operation = null; int start = 0; int limit = 50; try { operation = URLDecoder.decode(form.getQueryString(), "utf-8"); operation = new String(operation.getBytes("iso-8859-1"), "utf-8"); JSONObject json = JSONObject.fromObject(operation); start = json.containsKey("start") == false ? start : Integer.parseInt(json.getString("start")); limit = json.containsKey("limit") == false ? limit : Integer.parseInt(json.getString("limit")); } catch (Exception e) { // e.printStackTrace(); } List<Role> list = service.getAllRole(start, limit); Page page = new Page(list); page.setStart(start); page.setPageSize(limit); int totalCount = service.getCountRole(); page.setTotalCount(totalCount); return new JsonRepresentation(JSONObject.fromObject(page)); }
@Override public boolean configure(final StaplerRequest req, final JSONObject json) throws FormException { JSONObject selectedJson = json.getJSONObject("searchBackend"); if (selectedJson.containsKey(SOLR_URL)) { String solrUrl = selectedJson.getString(SOLR_URL); ensureNotError(doCheckSolrUrl(solrUrl), SOLR_URL); try { setSolrUrl(makeSolrUrl(solrUrl)); } catch (IOException e) { // Really shouldn't be possible, but this is the correct action, should it ever happen throw new FormException("Incorrect freetext config", SOLR_URL); } } if (selectedJson.containsKey(SOLR_COLLECTION)) { String solrCollection = selectedJson.getString(SOLR_COLLECTION); ensureNotError(doCheckSolrCollection(solrCollection, getSolrUrl()), SOLR_COLLECTION); setSolrCollection(solrCollection); } if (selectedJson.containsKey(LUCENE_PATH)) { String lucenePath = selectedJson.getString(LUCENE_PATH); ensureNotError(doCheckLucenePath(lucenePath), LUCENE_PATH); setLucenePath(new File(lucenePath)); } if (json.containsKey(USE_SECURITY)) { setUseSecurity(json.getBoolean(USE_SECURITY)); } setSearchBackend(SearchBackendEngine.valueOf(json.get("").toString())); reconfigure(); return super.configure(req, json); }
public void reloadFiltreBase(String filtreString) { if (filtreString != null) { filtreJson = JSONObject.fromObject(filtreString); if (filtreJson.containsKey("Nom")) { setFiltreNomBase(filtreJson.getString("Nom")); } if (filtreJson.containsKey("Environnement")) { for (Environnement env : listEnvironnement) { if (env.getEnvironnement().equalsIgnoreCase(filtreJson.getString("Environnement"))) { setFiltreEnvironnementBase(env.getId()); } } } if (filtreJson.containsKey("Date de début")) { setFiltreDateDebutBase(filtreJson.getString("Date de début")); } if (filtreJson.containsKey("Criticité")) { for (Checklist_Criticite crit : listCriticite) { if (crit.getLibelle().equalsIgnoreCase(filtreJson.getString("Criticité"))) { setFiltreCriticiteBase(crit.getId()); } } } if (validForm == 0) { setFiltreNom(filtreNomBase); setFiltreEnvironnement(filtreEnvironnementBase); setFiltreDateDebut(filtreDateDebutBase); setFiltreCriticite(filtreCriticiteBase); } } }
@Override public void fromJson(JSONObject json) { if (json.containsKey(PROVIDER)) { provider = new Provider(json.getJSONObject(PROVIDER)); } if (json.containsKey(EVENTCREATED_ON)) { eventCreatedOn = getDate(json, EVENTCREATED_ON); } }
private JSONObject extractTika(String contents) { JSONObject jObj = (JSONObject) JSONSerializer.toJSON(contents); if (jObj.containsKey("_source")) { JSONObject jObjSource = jObj.getJSONObject("_source"); if (jObjSource.containsKey("raw_content")) { String rawHtml = jObjSource.getString("raw_content"); ByteArrayInputStream bIs = new ByteArrayInputStream(rawHtml.getBytes()); Metadata metadata = new Metadata(); AutoDetectParser adp = new AutoDetectParser(); ContentHandler handler = new BodyContentHandler(10 * 1024 * 1024); try { adp.parse(bIs, handler, metadata); String[] metadataNames = metadata.names(); JSONObject jObjMetadata = new JSONObject(); for (String metadataName : metadataNames) { String[] values = metadata.getValues(metadataName); JSONArray jArray = new JSONArray(); for (String mValue : values) { jArray.add(mValue); } jObjMetadata.accumulate(metadataName, jArray); } // remove empty lines from the text String rawTextAdjusted = handler.toString().replaceAll("(?m)^[ \t]*\r?\n", ""); // detect language LanguageIdentifier li = new LanguageIdentifier(rawTextAdjusted); jObjSource.accumulate("tikametadata", jObjMetadata); jObjSource.accumulate("raw_text", rawTextAdjusted); jObjSource.accumulate("rawtextdetectedlanguage", li.getLanguage()); } catch (Exception e) { LOG.error("Error:", e); ; } } } return jObj; }
/** * Takes a JSON object and fills its internal data-structure. * * @param json the JSON Object. */ public void fromJson(JSONObject json) { super.fromJson(json); if (json.containsKey(CHANGE)) { change = new Change(json.getJSONObject(CHANGE)); } if (json.containsKey(PATCH_SET)) { patchSet = new PatchSet(json.getJSONObject(PATCH_SET)); } else if (json.containsKey(PATCHSET)) { patchSet = new PatchSet(json.getJSONObject(PATCHSET)); } }
@Test public void testServiceExists() throws Exception { JSON json = getAsJSON("/pdf/info.json"); assertTrue(json instanceof JSONObject); JSONObject obj = (JSONObject) json; assertTrue(obj.containsKey("scales")); assertTrue(obj.containsKey("dpis")); assertTrue(obj.containsKey("layouts")); assertTrue(obj.containsKey("printURL")); assertTrue(obj.containsKey("createURL")); }
/** * The same as {@code toPinYinWithMap} except if invoke {@code toPinYinWithMapMixModul} it does * not filter hanzi Eg: * * <pre> * String c = "hello world 张",Not only output 'zhang',in fact it will output:hello world zhang * </pre> * * @param c * @param style * @return Map */ public Map<String, String[]> toPinYinWithMapMixModul(String c, ResourceType.OutPutStyle style) { if (style == null) { style = ResourceType.OutPutStyle.NOTHING; } LinkedHashMap<String, String[]> map = new LinkedHashMap<String, String[]>(); if (c.equals("") || c == null) { map.put(null, new String[] {"null"}); return map; } String temp = c.trim(); // if(utils.hasChinese(temp)){ // temp = utils.onlyChinese(temp); // } for (int j = 0, length1 = temp.length(); j < length1; j++) { String cc = temp.substring(j, j + 1); if (pinYinJsonObject.containsKey(cc)) { String[] type = pinYinJsonObject.getString(cc).split(","); for (int i = 0, length = type.length; i < length; i++) { type[i] = handleType(type[i], style); } map.put(String.valueOf(j) + cc, type); } else { map.put(String.valueOf(j) + cc, new String[] {cc}); } } return map; }
private String[] toPinYinWithStringArray( String c, PinyinStyle pinyinStyle, PinYinStyles pinYinStyles) { if (pinYinJsonObject.containsKey(c)) { String[] type = pinYinJsonObject.getString(c).split(","); switch (pinyinStyle) { case POLYPHONE: for (int i = 0, length = type.length; i < length; i++) { type[i] = handleType(type[i], ResourceType.OutPutStyle.NOTHING); } return type; case SINGTON: String temp[] = {handleType(type[0], ResourceType.OutPutStyle.NOTHING)}; return temp; } } /** */ switch (pinYinStyles) { case ONLYCHINEASE: return new String[] {"null"}; case COMPLETE: return new String[] {c}; } return new String[] {"null"}; }
/** * Parses the raw response from Google * * @param rawResponse The raw, unparsed response from Google * @return Returns the parsed response. */ void parseResponse(String rawResponse, GoogleResponse googleResponse) { try { JSONObject json = JSONObject.fromObject(rawResponse); int status = json.getInt("status"); if (status == 0) { JSONArray hypotheses = json.getJSONArray("hypotheses"); for (int index = 0; index < hypotheses.size(); index++) { JSONObject hypothese = (JSONObject) hypotheses.get(index); if (hypothese.containsKey(CONFIDENCE)) { googleResponse.setResponse(hypothese.getString("utterance")); googleResponse.setConfidence(hypothese.getDouble(CONFIDENCE) + ""); } else { googleResponse.getOtherPossibleResponses().add(hypothese.getString("utterance")); } } } else { Logger.getLogger(Recognizer.class.getName()).log(Level.WARNING, "status: {0}", status); } } catch (JSONException e) { Logger.getLogger(Recognizer.class.getName()).log(Level.WARNING, e.getLocalizedMessage(), e); } }
/** * 获取jsapi_ticket * * @param accesstoken * @return */ public static void getjsTicket(String accesstoken) { String jsapi_ticketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi"; String url = jsapi_ticketUrl.replace("ACCESS_TOKEN", accesstoken); System.out.println("查看js_url:" + url); try { if (jsTicket.equals("")) { String result = HttpUtil.getInstance().execGet(url); logger.debug("result==" + result); JSONObject obj = JSONObject.fromObject(result); if (obj.containsKey("ticket")) { jsTicket = obj.get("ticket").toString(); System.out.println("ticket====" + obj.get("ticket")); } else { getAccessToken(); getjsTicket(accessToken); return; } } else { } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
// 根据openId获取粉丝信息 public static AccountFans syncAccountFans(String openId, String appId, String appSecret) { String token = WxApi.getToken(appId, appSecret).getAccessToken(); String url = WxApi.getFansInfoUrl(token, openId); JSONObject jsonObj = WxApi.httpsRequest(url, "GET", null); if (null != jsonObj) { if (jsonObj.containsKey("errcode")) { int errorCode = jsonObj.getInt("errcode"); System.out.println( String.format("获取用户信息失败 errcode:{} errmsg:{}", errorCode, ErrCode.errMsg(errorCode))); } else { AccountFans fans = new AccountFans(); fans.setSubscribeStatus( new Integer(jsonObj.getInt("subscribe"))); // 关注状态(1是关注,0是未关注),未关注时获取不到其余信息 fans.setOpenId(jsonObj.getString("openid")); // 用户的标识 fans.setGender(jsonObj.getInt("sex")); // 用户的性别(1是男性,2是女性,0是未知) fans.setNickname(jsonObj.getString("nickname")); // 昵称 fans.setLanguage(jsonObj.getString("language")); // 用户的语言,简体中文为zh_CN fans.setCity(jsonObj.getString("city")); // 用户所在城市 fans.setProvince(jsonObj.getString("province")); // 用户所在省份 fans.setCountry(jsonObj.getString("country")); // 用户所在国家 fans.setHeadimgurl(jsonObj.getString("headimgurl")); // 用户头像 fans.setSubscribeTime(jsonObj.getString("subscribe_time")); // 用户关注时间 fans.setRemark(jsonObj.getString("remark")); return fans; } } return null; }
public static Namelist fromJSONtoNamelist(JSONObject jsonObj) { logger.info("Convert json object to namelist..."); if (jsonObj != null) { String name = jsonObj.getString("_name"); String species = jsonObj.getString("_species"); if (species == null) { JSONObject metadataJSONObj = jsonObj.getJSONObject("metadata"); if (metadataJSONObj != null) { species = metadataJSONObj.getString("species"); } } int size = jsonObj.getInt("_size"); JSONArray data = jsonObj.containsKey("_data") ? jsonObj.getJSONArray("_data") : jsonObj.getJSONArray("gaggle-data"); String[] names = new String[data.size()]; for (int i = 0; i < data.size(); i++) { logger.info("Data item: " + data.getString(i)); names[i] = data.getString(i); } logger.info("Species: " + species + " Names: " + names); Namelist nl = new Namelist(name, species, names); return nl; } return null; }
public static void logCommandResult( InputStream inputStream, ConsoleLogger console, String errMessage) { BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); String line = null; try { while ((line = in.readLine()) != null) { console.logInfo(line); JSONObject jsonResponse = JSONObject.fromObject(line); if (jsonResponse.containsKey("error") || jsonResponse.containsKey("errorDetail")) { throw new DockerException(line, 200); } } } catch (IOException e) { throw new DockerException(line == null ? errMessage : line, 200, e); } }
@Override public void handle(HttpExchange arg0) throws IOException { try { String jsons = IOUtils.toString(arg0.getRequestBody()); JSONObject json = (JSONObject) JSONSerializer.toJSON(jsons); if (!json.containsKey("valid")) return; Email response = new SimpleEmail(); response.setHostName(properties.getProperty("org.iplantc.tnrs.mail.host")); response.setSmtpPort( Integer.parseInt(properties.getProperty("org.iplantc.tnrs.mail.port"))); response.setFrom("*****@*****.**"); response.setSubject("TNRS support Ticket"); response.setMsg( "TNRS support ticket from: " + json.getString("name") + " (" + json.getString("email") + "). " + "\n\n\n" + json.getString("contents")); response.addTo("*****@*****.**"); response.send(); } catch (Exception ex) { log.error(ExceptionUtils.getFullStackTrace(ex)); throw new IOException(ex); } }
/** * This method updates the template structure by adding to it the current dashboard's style and * renderer type. * * <p>This is done by getting the current dashboard from within the json structure, loading it's * wcdfDescriptor and fetching its stored style and renderer type. * * <p>These values then are added to the template structure itself. * * <p> * * @param origStructure original template structure * @return original template structure updated to include the dashboard's style and renderer type * @throws DashboardStructureException */ protected String addDashboardStyleAndRendererTypeToTemplate(String origStructure) throws DashboardStructureException { if (origStructure == null) { return origStructure; // nothing to do here } try { String updatedStructure = origStructure; // starts off as the original one JSONObject jsonObj = JSONObject.fromObject(origStructure); if (jsonObj != null && jsonObj.containsKey("filename")) { DashboardWcdfDescriptor wcdf = loadWcdfDescriptor(jsonObj.getString("filename")); if (wcdf != null) { // update the template structure jsonObj.put("style", wcdf.getStyle()); jsonObj.put("rendererType", wcdf.getRendererType()); updatedStructure = jsonObj.toString(2); } } return updatedStructure; } catch (Exception e) { logger.error(e); throw new DashboardStructureException(e.getMessage()); } }
/** * A help method for {@code findSimplyPinYinWithHanZi} * * @param code * @param styles * @return String */ @SuppressWarnings("incomplete-switch") public String handleType(String code, ResourceType.OutPutStyle styles) { StringBuilder sb = new StringBuilder(); String tone = null; String nothing = ""; if (styles == null) { styles = ResourceType.OutPutStyle.NOTHING; } for (int i = 0, length = code.length(); i < length; i++) { String c = code.substring(i, i + 1); switch (styles) { case SHENGMU: int num = 0; for (int j = 0, length1 = SHENGMU.length; j < length1; j++) { num = code.indexOf(SHENGMU[j]); if (num == 0) { sb.append(SHENGMU[j]); } } return sb.toString(); case YUNMU: int num1 = 0; for (int j = 0, length1 = SHENGMU.length; j < length1; j++) { num1 = code.indexOf(SHENGMU[j]); if (!(num1 == 0)) { sb.append(code.substring(SHENGMU[j].length())); break; } } return sb.toString(); } if (soundMarkJsonObject.containsKey(c)) { // System.out.println("code[i]="+i+ " "+ c); tone = (String) soundMarkJsonObject.get(c); // System.out.println("tone="+tone); nothing = tone.replaceAll("[0-9]", ""); switch (styles) { /* Without Tone,Without Number */ case WITHTONE: sb.append(c); break; /* With Number */ case NUMBER: sb.append(tone); break; /* With Tone */ case NOTHING: sb.append(nothing); break; default: sb.append(tone.replaceAll("[0-9]", "")); break; } } else { sb.append(c); } } return sb.toString(); }
void sendTokenInfo(MTWebSocket mtws, String inResponseTo, JSONObject data) { if (data.containsKey("propertyNames")) { sendTokenProperties(mtws, inResponseTo, data); } else { sendTokenRegisterdProperties(mtws, inResponseTo, data); } }
@Override public boolean configure(StaplerRequest req, JSONObject formData) { super.configure(req, formData); if (formData.containsKey("triggerScript")) { this.triggerScript = formData.optString("triggerScript", ""); } return true; }
Object read(InputStream in) throws IOException { Object result = null; JSONObject json = parse(in); // @hack - this should return a ImportTask if (json.containsKey("target")) { result = fromJSON(json.getJSONObject("target"), DataStoreInfo.class); } return result; }
@Override @SuppressWarnings("unchecked") @Put public Representation put(Representation entity) { Form form = new Form(entity); String name = (String) getRequestAttributes().get("name"); String operation = null; boolean flag = true; String message = "操作成功!"; try { operation = URLDecoder.decode(form.getQueryString(), "utf-8"); operation = new String(operation.getBytes("iso-8859-1"), "utf-8"); JSONObject json = JSONObject.fromObject(operation); String roleName = json.getString("roleName"); Role role = new Role(); String moduels = json.containsKey("modules") == false ? "" : json.getString("modules"); String roleDesc = json.containsKey("roleDesc") == false ? "" : json.getString("roleDesc"); role.setRoleName(roleName); role.setModules(moduels); role.setRoleDesc(roleDesc); if (name != null && name.equals("update")) { flag = service.updateRole(role); if (!flag) message = "操作失败!"; } else { if (service.getRoleByName(roleName) == null) { flag = service.saveRole(role); if (!flag) message = "操作失败!"; } else { message = "此角色已经存在,请重新填写!"; flag = false; } } } catch (Exception e) { e.printStackTrace(); message = e.getMessage(); } Map<String, Object> map = new HashMap<String, Object>(); map.put("message", message); map.put("success", flag); if (!flag) getResponse().setStatus(new Status(600), message); return new JsonRepresentation(JSONObject.fromObject(map)); }
Mosaic mosaic(JSONObject json) throws IOException { Mosaic m = new Mosaic( json.has("location") ? new File(json.getString("location")) : Directory.createNew(importer.getUploadRoot()).getFile()); if (json.has("name")) { m.setName(json.getString("name")); } if (json.containsKey("time")) { JSONObject time = json.getJSONObject("time"); if (!time.containsKey("mode")) { throw new IllegalArgumentException( "time object must specific mode property as " + "one of " + TimeMode.values()); } m.setTimeMode(TimeMode.valueOf(time.getString("mode").toUpperCase())); m.getTimeHandler().init(time); } return m; }
@SuppressWarnings("unchecked") private Authentication toAuthentication(Object credentials, JSONObject json) { List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); if (json.containsKey("ro")) { JSONArray roLayers = json.getJSONArray("ro"); authorities.add(new LayersGrantedAuthority(roLayers, LayerMode.READ_ONLY)); } if (json.containsKey("rw")) { JSONArray rwLayers = json.getJSONArray("rw"); authorities.add(new LayersGrantedAuthority(rwLayers, LayerMode.READ_WRITE)); } if (json.getBoolean("is_superuser")) { authorities.add(new GrantedAuthorityImpl(GeoNodeDataAccessManager.ADMIN_ROLE)); } final Authentication authentication; if (json.getBoolean("is_anonymous")) { authorities.add(new GrantedAuthorityImpl("ROLE_ANONYMOUS")); String key = "geonode"; Object principal = "anonymous"; GrantedAuthority[] grantedAuthorities = authorities.toArray(new GrantedAuthority[authorities.size()]); authentication = new AnonymousAuthenticationToken(key, principal, grantedAuthorities); } else { String userName = ""; if (json.containsKey("name")) { userName = json.getString("name"); } GrantedAuthority[] grantedAuthorities = authorities.toArray(new GrantedAuthority[authorities.size()]); authentication = new UsernamePasswordAuthenticationToken(userName, credentials, grantedAuthorities); } return authentication; }
public String getCodeByCategoryJson( MobileServerConfig mobileServerConfig, Document doc, String urlPara) { String json = ""; String paraJson = urlPara; JSONObject jsonObject = JSONObject.fromObject(paraJson); String category = ""; if (jsonObject.containsKey("category")) { category = jsonObject.opt("category").toString(); } JSONObject jsonObjectResult = new JSONObject(); try { if (category != null && !category.equals("")) { List<Code> list = getCodeCacheListByCategory(category); if (list != null && list.size() > 0) { JSONArray jsonArray = new JSONArray(); for (Code code : list) { JSONObject jsonObjectData = new JSONObject(); jsonObjectData.put("codeName", code.getCodeName()); jsonObjectData.put("description", code.getDescription()); jsonArray.add(jsonObjectData); } jsonObjectResult.put("result", "1"); jsonObjectResult.put("data", jsonArray); } } else { jsonObjectResult.put("result", "0"); jsonObjectResult.put("message", "缺少必要参数"); } } catch (Exception e) { // TODO: handle exception jsonObjectResult.put("result", "0"); jsonObjectResult.put("message", e.getMessage()); } json = jsonObjectResult.toString(); return json; }
/** * 判断token是否过期 * * @param token * @return */ public static boolean isTokenExpired(String token) { boolean rs = true; NameValuePair[] params = { new NameValuePair("access_token", token), }; try { JSONObject json = JSONObject.fromObject(HttpUtils.getMethod(GmailConstants.IS_AUTH_EXPIRED_URL, params)); rs = json.containsKey("error"); } catch (IOException e) { e.printStackTrace(); } return rs; }
/** * accessToken * * @return */ public static void getAccessToken() { String uri = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appScret; try { String result = HttpUtil.getInstance().execGet(uri); JSONObject obj = JSONObject.fromObject(result); if (obj.containsKey("access_token")) { accessToken = obj.getString("access_token"); System.out.println(accessToken + "*******"); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
/** * Invoke this method we can get a key-value * * <pre> * key : Your Hanzi * value: PinYin ,Default output style is * {@code ResourceType.OutPutStyle.NOTHING} * * </pre> * * To save duplicate,So the key is consist of hanzi and a serial number; More * information,please @see {@code DictTest} * * @param c * @return Map */ public Map<String, String[]> toPinYinWithMap(String c) { LinkedHashMap<String, String[]> map = new LinkedHashMap<String, String[]>(); if (c.equals("") || c == null) { map.put(null, new String[] {"null"}); return map; } String temp = c.trim(); for (int j = 0, length1 = temp.length(); j < length1; j++) { String cc = temp.substring(j, j + 1); if (pinYinJsonObject.containsKey(cc)) { String[] type = pinYinJsonObject.getString(cc).split(","); for (int i = 0, length = type.length; i < length; i++) { type[i] = handleType(type[i], ResourceType.OutPutStyle.NOTHING); } map.put(String.valueOf(j) + cc, type); } } return map; }
public static final String wxGetJsapiTicket() { Cache cache = Cache.getInstance(); long now = new Date().getTime() / 1000; if (!cache.exist("wxJsapiTicket") || now - (long) cache.get("wxJsapiTicketTime") > Constant.W_EXPIRE_IN) { String accessToken = Constant.wxGetAccessToken(); if (accessToken == null) { return null; } String url = Constant.W_GET_JSAPI_TICKET + "?access_token=" + accessToken + "&type=jsapi"; String ret = Web.sendGet(url); JSONObject json = JSONObject.fromObject(ret); if (json.containsKey("errcode") && json.getInt("errcode") != 0) { return null; } cache.set("wxJsapiTicket", json.getString("ticket")); cache.set("wxJsapiTicketTime", now); Constant.W_EXPIRE_IN = json.getInt("expires_in") - 200; } return (String) cache.get("wxJsapiTicket"); }
/** * Most of time,please use this method; More details information please see {@link MainTest} * * @param inputSource * @param styles * @return String */ public String findSingtonPinYinByHanZi(String inputSource, ResourceType.OutPutStyle styles) { int length = inputSource.length(); StringBuilder sb = new StringBuilder(); String tempString = null; String toneString = ""; for (int i = 0; i < length; i++) { String c = inputSource.substring(i, i + 1); tempString = (String) pinYinJsonObject.get(c); if (pinYinJsonObject.containsKey(c)) { toneString = tempString.split(",")[0]; sb.append(handleType(toneString, styles)).append(" "); } else { sb.append(c); } } String pinYin = sb.toString(); tempString = null; return pinYin; }