public static byte[] responseJsonResult(boolean success, Map<String, Object> dataMap) { if (success) { Map<String, Object> jsonMap = new java.util.HashMap<String, Object>(); jsonMap.put("statusCode", 200); Set<Entry<String, Object>> entrySet = dataMap.entrySet(); for (Entry<String, Object> entry : entrySet) { String key = entry.getKey(); Object value = entry.getValue(); jsonMap.put(key, value); } JSONObject object = new JSONObject(jsonMap); try { return object.toString().getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { } } else { Map<String, Object> jsonMap = new java.util.HashMap<String, Object>(); jsonMap.put("statusCode", 500); Set<Entry<String, Object>> entrySet = dataMap.entrySet(); for (Entry<String, Object> entry : entrySet) { String key = entry.getKey(); Object value = entry.getValue(); jsonMap.put(key, value); } JSONObject object = new JSONObject(jsonMap); try { return object.toString().getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { } } return null; }
public void get() throws ClassNotFoundException, SQLException, IOException { Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/cpsystem"; String usernameMysql = "root"; String passwordMysql = "root"; Connection conn = DriverManager.getConnection(url, usernameMysql, passwordMysql); Statement stmt = conn.createStatement(); HttpServletRequest request = ServletActionContext.getRequest(); JSONObject dt = JSONObject.parseObject(request.getParameter("dt")); String account = (String) dt.get("account"); String sql = "select * from user where phone='" + account + "'"; ResultSet userinfo = stmt.executeQuery(sql); JSONObject json = new JSONObject(); JSONObject info = new JSONObject(); if (userinfo.next()) { if (userinfo.getInt("type") == 1) { // driver info.put("id", userinfo.getInt("id")); info.put("phone", userinfo.getString("phone")); info.put("email", userinfo.getString("email")); info.put("name", userinfo.getString("name")); info.put("type", userinfo.getInt("type")); sql = "select * from driver_info where id=" + userinfo.getInt("id"); stmt = conn.createStatement(); ResultSet driverinfo = stmt.executeQuery(sql); if (driverinfo.next()) { info.put("success_count", driverinfo.getInt("success_count")); info.put("success_thismonth", driverinfo.getInt("success_thismonth")); info.put("send_count", driverinfo.getInt("send_count")); info.put("send_thismonth", driverinfo.getInt("send_thismonth")); } json.put("info", info); HttpServletResponse response = ServletActionContext.getResponse(); response.setCharacterEncoding("utf-8"); response.getWriter().write(json.toString()); } else if (userinfo.getInt("type") == 2) { // passenger info.put("id", userinfo.getInt("id")); info.put("phone", userinfo.getString("phone")); info.put("email", userinfo.getString("email")); info.put("type", userinfo.getString("type")); sql = "select * from passenger_info where id=" + userinfo.getInt("id"); stmt = conn.createStatement(); ResultSet passengerinfo = stmt.executeQuery(sql); if (passengerinfo.next()) { info.put("take_count", passengerinfo.getInt("take_count")); info.put("take_thismonth", passengerinfo.getInt("take_thismonth")); } json.put("info", info); HttpServletResponse response = ServletActionContext.getResponse(); response.setCharacterEncoding("utf-8"); response.getWriter().write(json.toString()); } } }
@Override protected String toJsonData(Object data, String provider, String desc, int code) throws JSONException { JSONObject ret = new JSONObject(); ret.put("errno", code); ret.put("errText", StringUtils.isEmpty(desc) ? "OK" : desc); ret.put("data", data); return ret.toString(); }
public String toJSONString() { JSONObject jsonObject = new JSONObject(); jsonObject.put("name", name); jsonObject.put("size", size); jsonObject.put("url", url); jsonObject.put("thumbnailUrl", thumbnailUrl); jsonObject.put("deleteUrl", deleteUrl); jsonObject.put("deleteType", deleteType); return jsonObject.toString(); }
@Override public Card getCard(JSONObject params) throws IOException { Object cardId = params.get("card_id"); Assert.notNull(cardId, "卡券ID不能为空"); String jsonString = params.toString(); String token = this.weixinProxy.httpToken().getAccessToken(); String url = String.format(CARD_URL, token); byte[] bytes = HttpClientUtil.httpPost(url, jsonString); return JSON.parseObject(bytes, Card.class); }
/** * 设置用户备注名 * * @param openid 用户openid * @param remark 新的备注名,长度必须小于30字符 * @return * @throws WeChatException */ public void updateRemark(String openId, String remark) throws WeChatException { JSONObject jsonObject = new JSONObject(); jsonObject.put("openid", openId); jsonObject.put("remark", remark); String requestData = jsonObject.toString(); logger.info("request data " + requestData); String resultStr = HttpUtils.post(USER_UPDATE_REMARK_POST_URL + this.accessToken, requestData); logger.info("return data " + resultStr); WeChatUtil.isSuccess(resultStr); }
/** * 批量移动用户分组 * * @param openids 用户唯一标识符openid的列表(size不能超过50) * @param toGroupid 分组id * @return 是否修改成功 * @throws WeChatException */ public void membersDatchUpdateGroup(String[] openIds, int groupId) throws WeChatException { JSONObject jsonObject = new JSONObject(); jsonObject.put("openid_list", openIds); jsonObject.put("to_groupid", groupId); String requestData = jsonObject.toString(); logger.info("request data " + requestData); String resultStr = HttpUtils.post(GROUP_MEMBERS_DATCHUPDATE_POST_URL + this.accessToken, requestData); logger.info("return data " + resultStr); WeChatUtil.isSuccess(resultStr); }
/** * 创建分组 * * @param name 分组名字(30个字符以内) * @return * @throws WeChatException */ public Group createGroup(String name) throws WeChatException { JSONObject nameJson = new JSONObject(); JSONObject groupJson = new JSONObject(); nameJson.put("name", name); groupJson.put("group", nameJson); String requestData = groupJson.toString(); logger.info("request data " + requestData); String resultStr = HttpUtils.post(GROUP_CREATE_POST_URL + this.accessToken, requestData); logger.info("return data " + resultStr); WeChatUtil.isSuccess(resultStr); return JSONObject.parseObject(resultStr).getObject("group", Group.class); }
/** * 修改分组名 * * @param groupId 分组id * @param name 分组名称 * @throws WeChatException */ public void updateGroup(int groupId, String name) throws WeChatException { JSONObject nameJson = new JSONObject(); JSONObject groupJson = new JSONObject(); nameJson.put("id", groupId); nameJson.put("name", name); groupJson.put("group", nameJson); String requestData = groupJson.toString(); logger.info("request data " + requestData); String resultStr = HttpUtils.post(GROUP_UPDATE_POST_URL + this.accessToken, requestData); logger.info("return data " + resultStr); WeChatUtil.isSuccess(resultStr); }
public Notification build() { Notification notification = new Notification(); if (token != null) { notification.setToken(token); } else { throw new IllegalArgumentException("token is null!"); } notification.setPriority(priority); // TODO 这里是否把没有设置过期时间的通知都设置成无限的? notification.setExpirationDate(expirationDate); /** * * * <pre> * 因为这里有两种格式,一种是: * "aps" : { * "alert" : "You got your emails.", * "badge" : 9, * "sound" : "bingbong.aiff" * }, * * 另一种是: * "aps" : { * "alert" : { * "body" : "Bob wants to play poker", * "action-loc-key" : "PLAY" * }, * "badge" : 5, * }, * </pre> */ if (alert != null) { aps.put("alert", alert); } else { aps.put("alert", alertObject); } if (alert != null && !alertObject.isEmpty()) { logger.warn( "can not set alert and alertObject both!, https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html#//apple_ref/doc/uid/TP40008194-CH100-SW12"); } payload.put("aps", aps); byte[] bytes = payload.toString().getBytes(utf8); if (bytes.length > MAX_PAYLOAD_SIZE) { throw new IllegalArgumentException("payload.length >" + MAX_PAYLOAD_SIZE); } notification.setPayload(bytes); return notification; }
public static byte[] responseJsonResult(boolean success, String message) { if (success) { Map<String, Object> jsonMap = new java.util.HashMap<String, Object>(); jsonMap.put("statusCode", 200); jsonMap.put("message", message); JSONObject object = new JSONObject(jsonMap); try { return object.toString().getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { } } else { Map<String, Object> jsonMap = new java.util.HashMap<String, Object>(); jsonMap.put("statusCode", 500); jsonMap.put("message", message); JSONObject object = new JSONObject(jsonMap); try { return object.toString().getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { } } return null; }
@RequestMapping(value = "dologin") public String doLogin( @RequestParam(value = "username") String username, @RequestParam(value = "password") String password, ModelMap model, HttpSession httpSession) { JSONObject property = new JSONObject(); JSONObject property2 = new JSONObject(); property2.put("username", username); property2.put("password", password); property.put("where", property2); Resource resource = new Resource(Init.appId, Init.appKey, ""); JSONObject json = resource.doFilterSearch("admin", property.toString()); JSONArray array = json.getJSONArray("data"); JSONObject admin = new JSONObject(); if (array.size() > 0) { admin = array.getJSONObject(0); httpSession.setAttribute("admin", admin.toString()); httpSession.setAttribute("username", username); return "redirect:/"; } else { return "redirect:login"; } }
/** * 查询用户所在分组 * * @param openId 用户的OpenID * @return 用户所属的groupid */ public Integer getIdGroup(String openId) { JSONObject jsonObject = new JSONObject(); jsonObject.put("openid", openId); String requestData = jsonObject.toString(); logger.info("request data " + requestData); String resultStr = HttpUtils.post(GROUP_GETID_POST_URL + this.accessToken, requestData); logger.info("return data " + resultStr); try { WeChatUtil.isSuccess(resultStr); } catch (WeChatException e) { logger.error(e.getMessage()); e.printStackTrace(); return null; } JSONObject resultJson = JSONObject.parseObject(resultStr); int groupId = resultJson.getIntValue("groupid"); return groupId; }
// 发送一个request请求给服务器,基于HttpUrlConnection public static String sendDataByGetRequest3(String address, String params, String encoding) throws UnsupportedEncodingException, IOException { StringBuilder sb = new StringBuilder(address); sb.append(params); // 接下来用url发送数据 URL url = new URL(sb.toString()); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setConnectTimeout(5000); if (con.getResponseCode() == 200) { InputStream iis = con.getInputStream(); byte[] bs = readFromStream(iis); String message = new String(bs, encoding); return message; } else { JSONObject result = new JSONObject(); result.put("code", "10001"); result.put("text", "小j会努力学好语文的,争取下次能明白您说的话!O(∩_∩)O~~"); return result.toString(); } }
/** * 创建语义 * * @param accessToken * @param queryStr 语义搜索串, 即用户输入的文本串 * @param category 需要使用的服务类型,多个用“,”隔开,不能为空 * @param city 城市名称 * @param region 区域名称 * @param appid 公众号唯一标识i * @param uid 用户唯一id(非开发者id),用户区分公众号下的不同用户(建议填入用户openid), * 如果为空,则无法使用上下文理解功能。appid和uid同时存在的情况下,才可以使用上下文理解功能。 * @return * @throws IOException * @throws WechatExceprion */ @Bizlet("createGrammer") public static WechatGrammer createGrammer( String accessToken, String queryStr, String category, String city, String appid, String uid) throws IOException, WechatExceprion { String uri = "https://api.weixin.qq.com/semantic/semproxy/search"; NameValuePair[] apiQueryStr = new NameValuePair[1]; apiQueryStr[0] = new NameValuePair("access_token", accessToken); JSONObject jsonObj = new JSONObject(); jsonObj.put("query", queryStr); jsonObj.put("category", category); jsonObj.put("city", city); jsonObj.put("appid", appid); jsonObj.put("uid", uid); String postData = jsonObj.toString(); RequestEntity requestEntity = new StringRequestEntity( postData, IWechatConstants.CONTENT_TYPE, IWechatConstants.DEFAULT_CHARSET); String result = HttpExecuter.executePostAsString(uri, apiQueryStr, requestEntity); String returnCode = JSONObject.parseObject(result).getString(IWechatConstants.ERROR_CODE); if (returnCode == null || IWechatConstants.RETURN_CODE_SUCCESS.equals(returnCode)) { return JSONObject.parseObject(result, WechatGrammer.class); } else throw new WechatExceprion("[AdvanceOperations#createGrammer]" + result); }
@Override public byte[] encode() { JSONObject jsonObject = new JSONObject(); if (!TextUtils.isEmpty(base64ImgContent)) { jsonObject.put("imgContent", this.base64ImgContent); } if (remoteVideoUri != null && !TextUtils.isEmpty(remoteVideoUri.toString())) { jsonObject.put("videoUrl", this.remoteVideoUri.toString()); } else if (localVideoUri != null && !TextUtils.isEmpty(localVideoUri.toString())) { jsonObject.put("videoUrl", this.localVideoUri.toString()); } if (isUploadExp) { jsonObject.put("exp", true); } if (this.getJSONUserInfo() != null) { jsonObject.put("user", this.getJSONUserInfo()); } this.base64ImgContent = null; return jsonObject.toString().getBytes(); }
@Override public String toString() { String str = jsonObject.toString(); TestFrameWork.setRequestJson(str); return str; }
/** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html"); // 获得输入的Json格式字符串 StringBuffer sb = new StringBuffer(); String line = null; try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { sb.append(line); } } catch (Exception e) { } // 解析json,然后构造Course对象 Course course = JSON.parseObject(sb.toString(), WrapCourse.class).getCourse(); Time time = course.getTime(); String courseId = course.getCourseId(); System.out.println("courseId=" + courseId); String teacherName = course.getTeacherName(); String location = course.getLocation(); // 根据add的返回值以json格式返回结果信息 PrintWriter out = response.getWriter(); JSONObject object = new JSONObject(); DataAccessInterface<Course> courseDAC = DACFactory.getInstance().createDAC(Course.class); courseDAC.beginTransaction(); // 判断输入的选课号是否存在 Condition<Course> condition1 = new Condition<Course>() { @Override public boolean assertBean(Course course) { return course.getCourseId().equals(courseId); } }; Condition<Course> condition2 = new Condition<Course>() { @Override public boolean assertBean(Course course) { return course.getTime().getWeekday() == time.getWeekday() && course.getTime().getPeriod() == time.getPeriod() && course.getLocation().equals(location); } }; Condition<Course> condition3 = new Condition<Course>() { @Override public boolean assertBean(Course course) { return course.getTeacherName().equals(teacherName) && course.getTime().getWeekday() == time.getWeekday() && course.getTime().getPeriod() == time.getPeriod(); } }; if (courseDAC.selectByCondition(condition1).size() != 0) { object.put("success", false); object.put("failReason", "选课号已存在"); } else if ((courseDAC.selectByCondition(condition2).size() != 0)) { object.put("success", false); object.put("failReason", "时间地点冲突"); } else if ((courseDAC.selectByCondition(condition3).size() != 0)) { object.put("success", false); object.put("failReason", "教师时间冲突"); } else { courseDAC.add(course); object.put("success", true); object.put("failReason", ""); } System.out.println(object.toString()); out.write(object.toString()); out.flush(); out.close(); System.out.println(courseDAC.commit()); }
public static void dispatchWork(long id, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("textml"); // 获得输入的json格式字符串 StringBuffer sb = new StringBuffer(); String line = null; try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { sb.append(line); } } catch (Exception e) { } // 解析json School school = (School) JSON.parseObject(sb.toString(), School.class); String schoolName = school.getSchoolName(); try { Producer p = new Producer( "addSchoolConflictionProducer", "G4-addSchoolConfliction", "TagAll", "" + id, schoolName); } catch (MQClientException | InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(MyManager.getMap(id, null)); /* while(("0").equals(MyManager.getMap(id,null))){ System.out.println(MyManager.getMap(id,null)); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } }*/ while (true) { synchronized (MyManager.lockObject) { while (("0").equals(MyManager.getMap(id, null))) { try { System.out.println("yes"); (MyManager.lockObject).wait(); System.out.println("yes1"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("yes1"); } System.out.println(MyManager.getMap(id, null)); if (("1").equals(MyManager.getMap(id, null))) { // 表示没有冲突的情况 try { Producer p2 = new Producer("addSchoolProducer", "G4-addSchool", "TagA", "" + id, schoolName); } catch (MQClientException | InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } PrintWriter out = response.getWriter(); JSONObject object = new JSONObject(); object.put("success", true); object.put("failReason", ""); out.write(object.toString()); out.flush(); out.close(); } else if (("2").equals(MyManager.getMap(id, null))) { // 表示存在冲突,院系已经存在 PrintWriter out = response.getWriter(); JSONObject object = new JSONObject(); object.put("success", false); object.put("failReason", "院系名称已存在"); out.write(object.toString()); out.flush(); out.close(); } } }