// 根据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; }
private void parseZeoTime(JSONObject stats, String key, ZeoSleepStatsFacet facet) { JSONObject o = stats.getJSONObject(key); int day = o.getInt("day"); int month = o.getInt("month"); int year = o.getInt("year"); int hours = o.getInt("hour"); int minutes = o.getInt("minute"); int seconds = o.getInt("second"); Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); c.set(Calendar.MILLISECOND, 0); c.set(year, month - 1, day, hours, minutes, seconds); if (key.equals("bedTime")) { facet.startTimeStorage = toTimeStorage(year, month, day, hours, minutes, seconds); facet.start = c.getTimeInMillis(); } else { facet.date = (new StringBuilder()) .append(year) .append("-") .append(pad(month)) .append("-") .append(pad(day)) .toString(); facet.endTimeStorage = toTimeStorage(year, month, day, hours, minutes, seconds); facet.end = c.getTimeInMillis(); } }
@Override public Builder newInstance(StaplerRequest req, JSONObject formData) throws FormException { String execDefIds = formData.getString("execDefIds"); // $NON-NLS-1$ int projectId = formData.getInt("projectId"); // $NON-NLS-1$ int delay = getOptionalIntValue(formData.getString("delay"), 0); // $NON-NLS-1$ boolean contOnErr = formData.getBoolean("continueOnError"); // $NON-NLS-1$ boolean collectResults = formData.getBoolean("collectResults"); // $NON-NLS-1$ boolean ignoreSetupCleanup = formData.getBoolean("ignoreSetupCleanup"); // $NON-NLS-1$ String jobName = ""; // $NON-NLS-1$ JSONObject buildNumberUsageOption = (JSONObject) formData.get("buildNumberUsageOption"); // $NON-NLS-1$ int optValue; if (buildNumberUsageOption == null) optValue = SCTMExecutor.OPT_NO_BUILD_NUMBER; else optValue = buildNumberUsageOption.getInt("value"); // $NON-NLS-1$ String version = null; switch (optValue) { case SCTMExecutor.OPT_USE_SPECIFICJOB_BUILDNUMBER: jobName = buildNumberUsageOption.getString("jobName"); // $NON-NLS-1$ case SCTMExecutor.OPT_USE_LATEST_SCTM_BUILDNUMBER: case SCTMExecutor.OPT_USE_THIS_BUILD_NUMBER: version = buildNumberUsageOption.getString("productVersion"); // $NON-NLS-1$ } return new SCTMExecutor( projectId, execDefIds, delay, optValue, jobName, contOnErr, collectResults, ignoreSetupCleanup, version); }
/** * 获取网页授权凭证 * * @param appId 公众号的唯一标识 * @param appSecret 公众号的秘钥 * @param code * @return WeixinAouth2Token */ public static WeixinOauth2Token getOauth2AccessToken( String appId, String appSecret, String code) { WeixinOauth2Token wat = null; String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code"; requestUrl = requestUrl.replace("APPID", appId); requestUrl = requestUrl.replace("SECRET", appSecret); requestUrl = requestUrl.replace("CODE", code); JSONObject jsonObject = WeixinUtil.httpRequest(requestUrl, "GET", null); if (null != jsonObject) { try { wat = new WeixinOauth2Token(); wat.setAccessToken(jsonObject.getString("access_token")); wat.setExpiresIn(jsonObject.getInt("expires_in")); wat.setOpenId(jsonObject.getString("openid")); wat.setRefreshToken(jsonObject.getString("refresh_token")); wat.setScope(jsonObject.getString("scope")); log.info( "获取网页授权凭证成功 access_token:{} errorMsg:{}", jsonObject.getString("access_token"), jsonObject.getString("openid")); } catch (Exception e) { wat = null; int errorCode = jsonObject.getInt("errcode"); String errorMsg = jsonObject.getString("errmsg"); log.error("获取网页授权凭证失败 errorCode:{} openid:{}", errorCode, errorMsg); } } return wat; }
/** * @Title: selectReplyByCommentId @Description: TODO(根据评论id查询回复列表) * * @author <a href="*****@*****.**">赖彩妙</a> * @date 2015-5-20 下午2:31:00 * @version 1.0.0 * @param @param data * @param @return * @return Object 返回类型 * @throws */ public Object selectReplyByCommentId(Object data) { log.info("start[MemberCommentService.selectReplyByCommentId]"); net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(data); Integer pageIndex = jsonObject.getInt("pageIndex"); Integer pageSize = jsonObject.getInt("pageSize"); Integer commentId = jsonObject.getInt("commentId"); PageHelper.startPage(pageIndex, pageSize); ResultPage<OrderCommentDetailDTO> commentPage = new ResultPage(orderCommentMapper.selectReplyByCommentId(commentId)); if (commentPage.getRows() != null && commentPage.getRows().size() >= 1) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (int i = 0; i < commentPage.getRows().size(); i++) { if (commentPage.getRows().get(i).getCreateTime() != null) { commentPage .getRows() .get(i) .setCommentDate(format.format(commentPage.getRows().get(i).getCreateTime())); } } } log.info("end[MemberCommentService.selectReplyByCommentId]"); // return new ResultObject(new HeadObject(ErrorCode.SUCCESS), // JSONObject.fromObject(commentPage)); return new ResultObject( new HeadObject(ErrorCode.SUCCESS), com.alibaba.fastjson.JSONObject.toJSON(commentPage)); }
private void retrieveTasks(UpdateInfo updateInfo, long since, boolean update) throws RateLimitReachedException, Exception { String key = getKey(updateInfo); String urlString = TOODLEDO_TASKS_GET + "?key=" + key + "&after=" + since; String tasksJson = restHelper.makeRestCall(connector(), updateInfo.getGuestId(), 1, urlString); JSONArray tasksArray = JSONArray.fromObject(tasksJson); JSONObject arrayInfo = tasksArray.getJSONObject(0); for (int i = 0; i < arrayInfo.getInt("total"); i++) { JSONObject task = tasksArray.getJSONObject(i + 1); if (task.has("total")) continue; long toodledo_id = task.getLong("id"); if (update) { ToodledoTaskFacet oldTask = jpaDaoService.findOne( "toodledo.task.byToodledoId", ToodledoTaskFacet.class, updateInfo.getGuestId(), toodledo_id); if (oldTask != null) jpaDaoService.remove(oldTask.getClass(), oldTask.getId()); } ToodledoTaskFacet taskFacet = new ToodledoTaskFacet(); taskFacet.guestId = updateInfo.getGuestId(); taskFacet.toodledo_id = toodledo_id; if (task.has("goal")) taskFacet.goal = task.getLong("goal"); taskFacet.modified = task.getLong("modified"); taskFacet.completed = task.getLong("completed"); if (taskFacet.completed != 0) { taskFacet.start = taskFacet.modified * 1000; taskFacet.end = taskFacet.modified * 1000; } taskFacet.title = task.getString("title"); taskFacet.api = connector().value(); taskFacet.objectType = 1; jpaDaoService.persist(taskFacet); } if (update) { urlString = TOODLEDO_TASKS_GET_DELETED + "?key=" + key + "&after=" + since; String tasksToDeleteJson = restHelper.makeRestCall(connector(), updateInfo.getGuestId(), 1, urlString); JSONArray tasksToDeleteArray = JSONArray.fromObject(tasksToDeleteJson); arrayInfo = tasksToDeleteArray.getJSONObject(0); for (int i = 0; i < arrayInfo.getInt("num"); i++) { JSONObject task = tasksToDeleteArray.getJSONObject(i + 1); long toodledo_id = task.getLong("id"); ToodledoTaskFacet taskToDelete = jpaDaoService.findOne( "toodledo.task.byToodledoId", ToodledoTaskFacet.class, updateInfo.getGuestId(), toodledo_id); if (taskToDelete != null) jpaDaoService.remove(taskToDelete.getClass(), taskToDelete.getId()); } } }
/** 新增 */ public void add() { CmsUser cmsuserForSession = getCmsUser(); String cmdAdduser = cmsuserForSession.getCmuName(); // 写日志 CmsLog log = UtilTools.buildLog("菜单管理", CmsLog.Add, "新增菜单", cmdAdduser); serviceDispatcher.getCmsLogService().add(log); // 返回值 ServletActionContext.getResponse().setCharacterEncoding("UTF-8"); net.sf.json.JSONObject js = net.sf.json.JSONObject.fromObject(rows); Integer cmmParentId = js.getInt("cmmParentId"); String cmmName = js.getString("cmmName"); String cmmDesc = js.getString("cmmDesc"); String cmmIcon = "".equals(js.getString("cmmIcon")) ? "workplace/image/icon/xitong.png" : js.getString("cmmIcon"); Integer cmmOrderNum = js.getInt("cmmOrderNum"); String cmmAdminUrl = js.getString("cmmAdminUrl"); Integer cmmType = js.getInt("cmmType"); Date cmmAddTime = UtilTools.getCurrrentDate1(); // 获取当前系统时间 String cmmAddUser = cmsuserForSession.getCmuName(); CmsMenu cm = new CmsMenu(); cm.setCmmParentId(cmmParentId); cm.setCmmName(cmmName); cm.setCmmDesc(cmmDesc); cm.setCmmIcon(cmmIcon); cm.setCmmOrderNum(cmmOrderNum); cm.setCmmAdminUrl(cmmAdminUrl); cm.setCmmType(cmmType); cm.setCmmAddUser(cmmAddUser); cm.setCmmAddTime(cmmAddTime); serviceDispatcher.getCmsMenuService().add(cm); // 获取数据 StringBuffer jsonString = new StringBuffer(); jsonString.append("{"); jsonString.append("success:true"); jsonString.append("}"); PrintWriter out; try { out = ServletActionContext.getResponse().getWriter(); out.print(jsonString); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } }
/** * WordListResponseを構築します。<br> * * @param json APIサーバからのレスポンス。<br> */ public WordListResponse(JSONObject json) { super(json); final JSONObject response = json.getJSONObject("response"); this.total = response.getInt(PARAM_KEY_TOTAL); final JSONArray wordsJson = response.getJSONArray(PARAM_KEY_WORDS); for (int i = 0; i < wordsJson.size(); i++) { final JSONObject wordJson = wordsJson.getJSONObject(i); this.words.add( new Word(wordJson.getString(PARAM_KEY_WORD), wordJson.getInt(PARAM_KEY_COUNT))); } }
private JSONResult parse(String jsonString) { JSONResult ret = new JSONResult(); JSON json = JSONSerializer.toJSON(jsonString); JSONObject jo = (JSONObject) json; ret.total = jo.getInt("totalCount"); Set<String> names; JSONArray arrResults = jo.optJSONArray("results"); if (arrResults != null) { names = getArray(arrResults); } else { JSONObject results = jo.optJSONObject("results"); if (results != null) { names = Collections.singleton(getSingle(results)); } else { LOGGER.warn("No results found"); names = Collections.EMPTY_SET; } } ret.names = names; ret.returnedCount = names.size(); return ret; }
int postNewTaskAsMultiPartForm(int imp, String data) throws Exception { File dir = unpack(data); List<Part> parts = new ArrayList<Part>(); for (File f : dir.listFiles()) { parts.add(new FilePart(f.getName(), f)); } MultipartRequestEntity multipart = new MultipartRequestEntity( parts.toArray(new Part[parts.size()]), new PostMethod().getParams()); ByteArrayOutputStream bout = new ByteArrayOutputStream(); multipart.writeRequest(bout); MockHttpServletRequest req = createRequest("/rest/imports/" + imp + "/tasks"); req.setContentType(multipart.getContentType()); req.addHeader("Content-Type", multipart.getContentType()); req.setMethod("POST"); req.setBodyContent(bout.toByteArray()); MockHttpServletResponse resp = dispatch(req); assertEquals(201, resp.getStatusCode()); assertNotNull(resp.getHeader("Location")); assertTrue(resp.getHeader("Location").matches(".*/imports/" + imp + "/tasks/\\d")); assertEquals("application/json", resp.getContentType()); JSONObject json = (JSONObject) json(resp); JSONObject task = json.getJSONObject("task"); return task.getInt("id"); }
int putNewTask(int imp, String data) throws Exception { File zip = getTestDataFile(data); byte[] payload = new byte[(int) zip.length()]; FileInputStream fis = new FileInputStream(zip); fis.read(payload); fis.close(); MockHttpServletRequest req = createRequest("/rest/imports/" + imp + "/tasks/" + new File(data).getName()); req.setHeader("Content-Type", MediaType.APPLICATION_ZIP.toString()); req.setMethod("PUT"); req.setBodyContent(payload); MockHttpServletResponse resp = dispatch(req); assertEquals(201, resp.getStatusCode()); assertNotNull(resp.getHeader("Location")); assertTrue(resp.getHeader("Location").matches(".*/imports/" + imp + "/tasks/\\d")); assertEquals("application/json", resp.getContentType()); JSONObject json = (JSONObject) json(resp); JSONObject task = json.getJSONObject("task"); return task.getInt("id"); }
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; }
/** * 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); } }
public static Integer getGameCode(String content) { if (StringUtils.isNotBlank(content)) { JSONObject obj = JSONObject.fromObject(content); return obj.getInt("code"); } return -1000; }
/** * 获取应用代理 * * @return */ public static Result<QiYeAgent> getAgent(String token, String agentid) { Result<QiYeAgent> result = new Result<QiYeAgent>(); JSONObject jo = UserAPI.getAgent(token, agentid); if (jo != null) { System.out.println(jo); result.setErrmsg(ErrorCodeText.errorMsg(jo.getString("errcode"))); result.setErrcode(jo.getString("errcode")); if (result.getErrcode().equals("0")) { QiYeAgent agent = new QiYeAgent(); agent.setName(jo.getString("name")); agent.setAgentid(jo.getString("agentid")); JSONObject jsonObject = jo.getJSONObject("allowpartys"); agent.setAllowpartys(new PartyContainer(jsonObject.getString("partyid"))); agent.setAllowusers(new UserContainer(jo.getString("allowusers"))); agent.setMode(jo.getString("mode")); if (agent.getMode() == "1") { agent.setCallbackurl(jo.getString("callbackurl")); agent.setUrltoken(jo.getString("urltoken")); agent.setReport_location_flag(jo.getString("report_location_flag")); } agent.setDescription(jo.getString("description")); agent.setRedirectdomain(jo.getString("redirectdomain")); agent.setRoundUrl(jo.getString("RoundUrl")); agent.setSquareUrl(jo.getString("SquareUrl")); agent.setUseridlist(jo.getString("useridlist")); agent.setClose(jo.getInt("close")); result.setObject(agent); } } return result; }
/** * 查询所有分组 * * @return 分组列表 */ public static List<UserGroup> getGroup() { List<UserGroup> list = new ArrayList<UserGroup>(); String url = GET_GROUP_URL.replace("ACCESS_TOKEN", WeixinUtil.getToken()); JSONObject jsonObject = WeixinUtil.httpsRequest(url, "POST", null); if (null != jsonObject) { if (StringUtil.isNotEmpty(jsonObject.get("errcode")) && jsonObject.get("errcode") != "0") { log.error( "获取分组失败,errcode:" + jsonObject.getInt("errcode") + ",errmsg:" + jsonObject.getString("errmsg")); } else { JSONArray arr = jsonObject.getJSONArray("groups"); for (int i = 0; i < arr.size(); i++) { UserGroup group = new UserGroup(); group.setId(arr.getJSONObject(i).getString("id")); group.setName(arr.getJSONObject(i).getString("name")); group.setCount(arr.getJSONObject(i).getInt("count")); list.add(group); } } } return list; }
public static void main(String[] args) { List<Map<String, Integer>> list = new ArrayList<Map<String, Integer>>(); for (int i = 24; i <= 28; i++) { Map<String, Integer> map = new HashMap<String, Integer>(); map.put("day", i); map.put("havedata", 0); list.add(map); } Random r = new Random(); for (int i = 1; i <= 31; i++) { Map<String, Integer> map = new HashMap<String, Integer>(); map.put("day", i); map.put("havedata", 1); map.put("nowfee", 3216 + r.nextInt(1000000)); map.put("oldfee", 3216 + r.nextInt(1000000)); map.put("dau", 3216 + r.nextInt(1000000)); map.put("dnu", 3216 + r.nextInt(1000000)); list.add(map); } for (int i = 1; i <= 6; i++) { Map<String, Integer> map = new HashMap<String, Integer>(); map.put("day", i); map.put("havedata", 0); list.add(map); } System.out.println(array2JsonString(list)); String json = "{\"code\":0,\"info\":\"success\",\"data\":{\"systemMail\":{\"mailVer\":19,\"target\":0,\"condition\":0,\"value\":2,\"title\":\"???è?????é??\",\"content\":\"???è?????é?????è?????é??\",\"sendTime\":1402555848,\"award\":{\"awardId\":0,\"gold\":2,\"heart\":2,\"diamond\":333,\"items\":[12,123],\"itemsCount\":[1,2]}}},\"sys_time\":1402555848}"; JSONObject obj = getObj(json); System.out.println(obj.getJSONObject("data").getJSONObject("systemMail").getInt("mailVer")); System.out.println(obj.getInt("code")); }
/** 删除 */ public void del() { CmsUser cmsuserForSession = getCmsUser(); String cmdAdduser = cmsuserForSession.getCmuName(); // 写日志 CmsLog log = UtilTools.buildLog("菜单管理", CmsLog.DELETE, "删除菜单", cmdAdduser); serviceDispatcher.getCmsLogService().add(log); net.sf.json.JSONArray objArr = net.sf.json.JSONArray.fromObject(rows); // 是否存在子目录 Boolean flag = false; for (int i = 0; i < objArr.size(); i++) { net.sf.json.JSONObject js = objArr.getJSONObject(i); // 是否包含子目录,如果包含则不允许删除 cmsMenu.setCmmId(js.getInt("cmmId")); List subList = serviceDispatcher.getCmsMenuService().query(cmsMenu); if (subList != null && subList.size() > 0) { flag = true; break; } else { serviceDispatcher.getCmsMenuService().del(js.getInt("cmmId")); } } // 获取数据 StringBuffer jsonString = new StringBuffer(); if (flag) { jsonString.append("{"); jsonString.append("failure:true,"); jsonString.append("msg:'对不起该目录包含子菜单,请先删除子菜单'"); jsonString.append("}"); } else { jsonString.append("{"); jsonString.append("success:true,"); jsonString.append( "msg:" + ApplicationResources.getText("admin.system.user.msg.deleteSuccess")); // '删除成功' jsonString.append("}"); } PrintWriter out; try { ServletActionContext.getResponse().setCharacterEncoding("UTF-8"); out = ServletActionContext.getResponse().getWriter(); out.print(jsonString.toString()); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } }
protected void charger(JSONObject jsonStatistique) { nbDeclarationsCompletes = jsonStatistique.getInt("declaration_completes"); nbDeclarationsIncompletesOuInvalide = jsonStatistique.getInt("declaration_incompletes_ou_invalide"); nbDeclarationsHommes = jsonStatistique.getInt("declaration_hommes"); nbDeclarationsFemmes = jsonStatistique.getInt("declaration_femmes"); nbDeclarationsSexeInconnu = jsonStatistique.getInt("declaration_sexe_inconnu"); initialiserMap(nbActivites, jsonStatistique.getJSONObject("activites")); initialiserMap( nbDeclarationsOrdreComplet, jsonStatistique.getJSONObject("declaratiion_ordre_valide_complete")); initialiserMap( nbDeclarationsOrdreIncomplet, jsonStatistique.getJSONObject("declaratiion_ordre_valide_incomplete")); nbDeclarationsNumeroInvalide = jsonStatistique.getInt("declaration_numero_invalide"); }
/** 首页管理:插入或更新 */ public void commit() { // Object[] arr = super.toJavaArr(info, FpageEvent.class); // FpageEvent[] events = castToFpageEvent(arr); JSONArray jsonArray = new JSONArray(); jsonArray = jsonArray.fromObject(info); FpageEvent[] events = new FpageEvent[jsonArray.size()]; if (jsonArray.size() > 0) { for (int i = 0; i < jsonArray.size(); i++) { events[i] = new FpageEvent(); JSONObject jsonObject = jsonArray.getJSONObject(i); events[i].setId(Long.parseLong(jsonObject.getString("id"))); events[i].setWeight(jsonObject.getInt("weight")); events[i].setTitle(jsonObject.getString("title")); events[i].setDescription(jsonObject.getString("description")); events[i].setPublicationId(jsonObject.getLong("publicationId")); events[i].setIssueId(jsonObject.getLong("issueId")); events[i].setPageNo(jsonObject.getInt("pageNo")); events[i].setEndPageNo(jsonObject.getInt("endPageNo")); events[i].setImgFile(jsonObject.getString("imgFile")); events[i].setWidth(Float.parseFloat(jsonObject.getString("width"))); events[i].setHeight(Float.parseFloat(jsonObject.getString("height"))); events[i].setStatus(jsonObject.getInt("status")); events[i].setIsPubCover(jsonObject.getInt("isPubCover")); events[i].setIsRecommend(jsonObject.getInt("isRecommend")); events[i].setIsSuitMobile(jsonObject.getInt("isSuitMobile")); } this.fpageEventService.commit(events); } }
@Override protected void execute(CommandEvent evt) throws Exception { String json = evt.getCmd()[1]; JSONObject obj = JSONObject.fromObject(json); int messID = obj.getInt("MID"); lokaServer.getDBQuery().setMessageRead(messID); sendResponse(evt.getResponse(), null); }
@Override protected void execute(CommandEvent cmdEvt) throws Exception { String json = cmdEvt.getCmd()[1]; JSONObject obj = JSONObject.fromObject(json); int userID = obj.getInt("UID"); lokaServer.getDBQuery().deleteAllMessagesForUser(userID); sendResponse(cmdEvt.getResponse(), null); }
/** * 创建菜单 * * @param token * @param menu * @return */ public static int createMenu(String token, String menu) { int result = 0; String url = CREATE_MENU_URL.replace("ACCESS_TOKEN", token); JSONObject jsonObject = doPostStr(url, menu); if (jsonObject != null) { result = jsonObject.getInt("errcode"); } return result; }
/** * 删除菜单 * * @param token * @param menu * @return */ public static int deleteMenu(String token) { int result = 0; String url = DELETE_MENU_URL.replace("ACCESS_TOKEN", token); JSONObject jsonObject = doGetStr(url); if (jsonObject != null) { result = jsonObject.getInt("errcode"); } return result; }
/** * 获取未关注成员列表 * * @return */ public static Result<QiYeUser[]> getNotConcernUser( String token, int departmentId, int fetch_child) { Result<QiYeUser[]> result = new Result<QiYeUser[]>(); JSONObject jo = UserAPI.getNotConcernUser(token, departmentId, fetch_child); if (jo != null) { result.setErrmsg(ErrorCodeText.errorMsg(jo.getString("errcode"))); result.setErrcode(jo.getString("errcode")); JSONArray ja = jo.getJSONArray("userlist"); if (ja != null && ja.size() > 0) { QiYeUser[] users = new QiYeUser[ja.size()]; for (int i = 0; i < ja.size(); i++) { JSONObject jsonObject = ja.getJSONObject(i); QiYeUser user = new QiYeUser(); user.setUserId(jsonObject.getString("userid")); user.setName(jsonObject.getString("name")); user.setDepartment(jsonObject.getString("department")); if (isEmpty(jo.toString(), "position", jo.getString("position"))) { user.setPosition(jo.getString("position")); } if (isEmpty(jo.toString(), "mobile", jo.getString("mobile"))) { user.setMobile(jo.getString("mobile")); } user.setGender(jo.getInt("gender")); if (isEmpty(jo.toString(), "tel", jo.getString("tel"))) { user.setTel(jo.getString("tel")); } if (isEmpty(jo.toString(), "email", jo.getString("email"))) { user.setEmail(jo.getString("email")); } if (isEmpty(jo.toString(), "weixinid", jo.getString("weixinid"))) { user.setWeixinid(jo.getString("weixinid")); } if (isEmpty(jo.toString(), "avatar", jo.getString("avatar"))) { user.setAvatar(jo.getString("avatar")); } user.setGender(jsonObject.getInt("gender")); user.setStatus(jsonObject.getInt("status")); users[i] = user; } result.setObject(users); } } return result; }
/** * @Title: selectOrderCommentByGoodsId @Description: TODO(根据商品id查询评论列表) * * @author <a href="*****@*****.**">赖彩妙</a> * @date 2015-5-13 下午2:19:50 * @version 1.0.0 * @param @param data * @param @return * @return Object 返回类型 * @throws */ public Object selectOrderCommentByGoodsId(Object data) { log.info("start[OrderCommentService.selectOrderCommentByGoodsId]"); net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(data); Integer pageIndex = jsonObject.getInt("pageIndex"); Integer pageSize = jsonObject.getInt("pageSize"); Integer goodsId = jsonObject.getInt("goodsId"); PageHelper.startPage(pageIndex, pageSize); ResultPage<OrderCommentDetailDTO> commentPage = new ResultPage(orderCommentMapper.selectOrderCommentByGoodsId(goodsId)); if (commentPage.getRows() != null && commentPage.getRows().size() >= 1) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); CommentPraiseExample example = null; for (int i = 0; i < commentPage.getRows().size(); i++) { if (commentPage.getRows().get(i).getOrderCreateTime() != null) { commentPage .getRows() .get(i) .setOrderCreateDate(format.format(commentPage.getRows().get(i).getOrderCreateTime())); } // 查询点赞数量 // example = new CommentPraiseExample(); // // example.createCriteria().andCommentIdEqualTo(commentPage.getRows().get(i).getCommentId().intValue()); // commentPage.getRows().get(i).setPraise(commentPraiseMapper.countByExample(example)); commentPage .getRows() .get(i) .setPraise( commentPraiseMapper.selectCountByCommentId( commentPage.getRows().get(i).getCommentId().intValue())); // 查询回复数量 commentPage .getRows() .get(i) .setReplyCount( orderCommentMapper.selectReplyCountByCommentId( commentPage.getRows().get(i).getCommentId().intValue())); } } return new ResultObject( new HeadObject(ErrorCode.SUCCESS), com.alibaba.fastjson.JSONObject.toJSON(commentPage)); }
void processMacro(JSONObject data) { // FIXME: need to check parameters. // FIXME: need to check permissions. if ("callMacro".equalsIgnoreCase(data.getString("command"))) { Token token = findTokenFromId(data.getString("tokenId")); MacroButtonProperties macro = token.getMacro(data.getInt("macroIndex"), false); macro.executeMacro(token.getId()); } }
/** * 获取access_token * * @return */ public static AccessToken getAccessToken() { AccessToken token = new AccessToken(); String url = ACCESS_TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET); JSONObject jsonObject = doGetStr(url); if (jsonObject != null) { token.setToken(jsonObject.getString("access_token")); token.setExpiresIn(jsonObject.getInt("expires_in")); } return token; }
public static void action() throws IOException, InterruptedException { // Connect to remote site String response = fetchTask(); System.out.println("JSON: " + response.trim()); JSONObject json = JSONObject.fromObject(response); int code = json.getInt("code"); String desc = json.getString("desc"); if (code != 0) { System.out.println("Code: " + code + " Desc: " + desc); } JSONObject task = json.getJSONObject("task"); String jar = task.getString("jar"); String cmd = task.getString("cmd"); // Create temporary directory File dir = createTempDirectory(); System.out.println("Temporary directory: " + dir.getAbsolutePath()); // Download current version System.out.println("Downloading: " + jar); String fileName = download(jar, dir); System.out.println("Unzipping: " + fileName); UnZip.unzip(dir.getAbsolutePath() + File.separator + fileName, dir.getAbsolutePath()); System.out.println("Executing: "); System.out.println(cmd); long startTime = System.currentTimeMillis(); Runtime rt = Runtime.getRuntime(); Process pr = rt.exec(cmd, null, dir); StreamWrapper errorStream = StreamWrapper.createStreamWrapper(pr.getErrorStream()); StreamWrapper inputStream = StreamWrapper.createStreamWrapper(pr.getInputStream()); int errorCode = pr.waitFor(); System.out.println(errorCode); System.out.println(errorStream); if (!ECHO) { System.out.println(inputStream); } long duration = System.currentTimeMillis() - startTime; task.put("duration", duration); String result = inputStream.toString() + errorStream.toString(); task.put("result", result); System.out.println("Sending results"); String status = sendResults(task); System.out.println(status.trim()); System.out.println("Cleaning up..."); deleteDirectory(dir); System.out.println("Done."); }
private ArrayList<AbstractFacet> extractStepFacets(final ApiData apiData) { ArrayList<AbstractFacet> facets = new ArrayList<AbstractFacet>(); /* burnJson is a JSONArray that contains a seperate JSONArray and calorie counts for each day */ JSONObject bodymediaResponse = JSONObject.fromObject(apiData.json); JSONArray daysArray = bodymediaResponse.getJSONArray("days"); if (bodymediaResponse.has("lastSync")) { DateTime d = form.parseDateTime(bodymediaResponse.getJSONObject("lastSync").getString("dateTime")); // Get timezone map from UpdateInfo context TimezoneMap tzMap = (TimezoneMap) updateInfo.getContext("tzMap"); // Insert lastSync into the updateInfo context so it's accessible to the updater updateInfo.setContext("lastSync", d); for (Object o : daysArray) { if (o instanceof JSONObject) { JSONObject day = (JSONObject) o; BodymediaStepsFacet steps = new BodymediaStepsFacet(apiData.updateInfo.apiKey.getId()); super.extractCommonFacetData(steps, apiData); steps.totalSteps = day.getInt("totalSteps"); steps.date = day.getString("date"); steps.json = day.getString("hours"); steps.lastSync = d.getMillis(); DateTime date = formatter.parseDateTime(day.getString("date")); steps.date = dateFormatter.print(date.getMillis()); if (tzMap != null) { // Create a LocalDate object which just captures the date without any // timezone assumptions LocalDate ld = new LocalDate(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth()); // Use tzMap to convert date into a datetime with timezone information DateTime realDateStart = tzMap.getStartOfDate(ld); // Set the start and end times for the facet. The start time is the leading midnight // of date according to BodyMedia's idea of what timezone you were in then. // Need to figure out what end should be... steps.start = realDateStart.getMillis(); int minutesLength = 1440; steps.end = steps.start + DateTimeConstants.MILLIS_PER_MINUTE * minutesLength; } else { TimeZone timeZone = metadataService.getTimeZone(apiData.updateInfo.getGuestId(), date.getMillis()); long fromMidnight = TimeUtils.fromMidnight(date.getMillis(), timeZone); long toMidnight = TimeUtils.toMidnight(date.getMillis(), timeZone); steps.start = fromMidnight; steps.end = toMidnight; } facets.add(steps); } else throw new JSONException("Days array is not a proper JSONObject"); } } return facets; }