public static MyResponse ok(Object content, boolean isEncryp) { MyResponse response = new MyResponse(); if (isEncryp) { response.encryp = true; JsonMapper jsonMapper = new JsonMapper(); String jsonContent = jsonMapper.toJson(content); try { // gzip压缩 ByteArrayOutputStream out = new ByteArrayOutputStream(); GZIPOutputStream gzip = new GZIPOutputStream(out); gzip.write(jsonContent.getBytes()); gzip.close(); byte[] vi = Cryptos.generateIV(); byte[] encryByte = Cryptos.aesEncrypt(out.toByteArray(), response.getCurrentToken(), vi); String encrypContent = Base64.encodeBase64String(encryByte); String viStr = Base64.encodeBase64String(vi); response.setContent(viStr + ":" + encrypContent); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { response.setContent(content); } response.setStatus(STATUS_OK); return response; }
@Test public void invalidInput() { // create Task titleBlankTask = new Task(); try { restTemplate.postForLocation(resourceUrl, titleBlankTask); fail("Create should fail while title is blank"); } catch (HttpStatusCodeException e) { assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); Map messages = jsonMapper.fromJson(e.getResponseBodyAsString(), Map.class); assertThat(messages).hasSize(1); assertThat(messages.get("title")).isIn("may not be empty", "不能为空"); } // update titleBlankTask.setId(1L); try { restTemplate.put(resourceUrl + "/1", titleBlankTask); fail("Update should fail while title is blank"); } catch (HttpStatusCodeException e) { assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); Map messages = jsonMapper.fromJson(e.getResponseBodyAsString(), Map.class); assertThat(messages).hasSize(1); assertThat(messages.get("title")).isIn("may not be empty", "不能为空"); } }
private synchronized void refreshAppList(boolean auto) { try { updating = true; Set<String> imgSet = getImgs(); List<Machine> machines = MachineUtils.getMachineList(); appDao.deleteAutoUpdatedRecords(); HashSet<String> set = new HashSet<String>(); for (Machine machine : machines) { String data = thirdAppService.getAppData(machine.getCode(), "3.0"); AppVO appVO = jsonMapper.fromJson(data, AppVO.class); if (appVO.getState().equals("0000")) { for (AppInfo appInfo : appVO.getZone()) { App app = new App(); app.setActionUrl(jsonMapper.toJson(appInfo.getData())); app.setUrl1080(upload(appInfo.getIcon())); app.setClientType(machine.getCode()); app.setTitle(jsonMapper.toJson(new String[] {appInfo.getName()})); app.setUpdateRefer("app:1"); if (auto) { User user = new User(); user.setId(1L); app.setUser(user); } else { app.setUser(UserUtils.getUser()); } appDao.save(app); set.add(app.getUpdateRefer()); } } } for (String ur : set) { templateService.evictTplByUpdateRefer(ur); } } catch (Exception e) { throw new RuntimeException(e); } finally { updating = false; } }
@RequestMapping("queryct") public void queryCosmeticsbytype( Long typeid, HttpServletResponse request, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); List<Map<String, String>> list = mpts.queryCosmeticsbytype(typeid); String json = mapper.toJson(list); out.write(json); out.close(); }
@RequestMapping("queryc") public void queryCosmetics(Long id, HttpServletResponse request, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); Cosmetics cos = mpts.getCos(id); String json = mapper.toJson(cos); out.write(json); out.close(); }
@RequestMapping("queryzixun") public void queryzixun(Long type, HttpServletResponse request, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); List<Map<String, String>> map = mpts.queryzixun(type); String json = mapper.toJson(map); out.write(json); out.close(); }
@RequestMapping("querytype") public void querytype(HttpServletResponse request, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); List<CosmeticType> list = mpts.getAll(); String json = mapper.toJson(list); out.write(json); out.close(); }
@RequestMapping("querydtall") public void querydtall(int user_id, HttpServletResponse request, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); List<Map<String, String>> map = mpts.querydtall(user_id); String json = mapper.toJson(map); out.write(json); out.close(); }
@RequestMapping("querycpp") public void querycospp(String name, HttpServletResponse request, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); System.out.println("121111111111111111111111111" + name); List<Map<String, String>> list = mpts.querycospp(name); String json = mapper.toJson(list); out.write(json); out.close(); }
/** 处理JSR311 Validation异常. */ @ExceptionHandler(value = {ConstraintViolationException.class}) public final ResponseEntity<?> handleException( ConstraintViolationException ex, WebRequest request) { Map<String, String> errors = BeanValidators.extractPropertyAndMessage(ex.getConstraintViolations()); String body = jsonMapper.toJson(errors); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType(MediaTypes.TEXT_PLAIN_UTF_8)); return handleExceptionInternal(ex, body, headers, HttpStatus.BAD_REQUEST, request); }
@RequestMapping("login") public void login(User user, HttpServletResponse request, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); User user1 = new User(); user1 = mpts.getuser(user); if (user1 == null || user1.getUsername() == null) { out.write("-1"); } else if (user1.getPassword().equals(user.getPassword())) { String json = mapper.toJson(user1); out.write(json); } else { out.write("-2"); } out.close(); }
/** * @param token * @param uid * @param count 单页返回的记录条数,最大不超过200。 * @param cursor 返回结果的游标,下一页用返回值里的next_cursor,上一页用previous_cursor,首页为0。 * @return */ public WeiboFriend getFriends(String token, String uid, int count, int cursor) { Assert.hasText(token); Assert.hasText(uid); Assert.state(count > 0); Assert.state(count <= 200); Assert.state(cursor >= 0); String url = String.format( "https://api.weibo.com/2/friendships/friends.json?uid=%s&count=%s&cursor=%s&access_token=%s", uid, count, cursor, token); String json = restTemplate.getForObject(url, String.class); WeiboFriend weiboFriend = jsonMapper.fromJson(json, WeiboFriend.class); if (weiboFriend == null || weiboFriend.getUsers() == null) { throw new RuntimeException("获取用户信息发生错误"); } return weiboFriend; }
/** * 访问新浪微博数据。 * * @author: Wei Liu Date: 13-9-9 Time: AM9:53 */ @Service public class WeiboService { protected final RestTemplate restTemplate = new RestTemplate(); private JsonMapper jsonMapper = JsonMapper.nonDefaultMapper(); public String getUid(String token) { String url = String.format("https://api.weibo.com/2/account/get_uid.json?access_token=" + token); return restTemplate.getForObject(url, Map.class).get("uid").toString(); } public Map getUserInfo(String token, String uid) { String url = String.format("https://api.weibo.com/2/users/show.json?uid=%s&access_token=%s", uid, token); Map userInfo = restTemplate.getForObject(url, Map.class); if (userInfo == null || userInfo.get("name") == null) { throw new RuntimeException("获取用户信息发生错误"); } return userInfo; } /* 例子: GET https://api.weibo.com/2/users/show.json?uid=3318605793&access_token=2.00txWacDz7QwTC832c8cafd1NOBqCD 响应: { "allow_all_act_msg": false, "allow_all_comment": true, "avatar_hd": "http://tp2.sinaimg.cn/3318605793/180/5667911042/1", "avatar_large": "http://tp2.sinaimg.cn/3318605793/180/5667911042/1", "bi_followers_count": 0, "block_word": 0, "city": "1", "class": 1, "created_at": "Thu Jul 04 21:12:05 +0800 2013", "description": "", "domain": "", "favourites_count": 0, "follow_me": false, "followers_count": 51, "following": false, "friends_count": 62, "gender": "m", "geo_enabled": true, "id": 3318605793, "idstr": "3318605793", "lang": "zh-cn", "location": "海外 美国", "mbrank": 0, "mbtype": 0, "name": "垃手", "online_status": 0, "profile_image_url": "http://tp2.sinaimg.cn/3318605793/50/5667911042/1", "profile_url": "u/3318605793", "province": "400", "ptype": 0, "remark": "", "screen_name": "垃手", "star": 0, "status": { "attitudes_count": 0, "bmiddle_pic": "http://ww2.sinaimg.cn/bmiddle/c5cde7e1jw1e8f9ft7aykj20c807igme.jpg", "comments_count": 0, "created_at": "Sun Sep 08 18:21:15 +0800 2013", "favorited": false, "geo": <null>, "id": 3620322777695001, "idstr": "3620322777695001", "in_reply_to_screen_name": "", "in_reply_to_status_id": "", "in_reply_to_user_id": "", "mid": "3620322777695001", "mlevel": 0, "original_pic": "http://ww2.sinaimg.cn/large/c5cde7e1jw1e8f9ft7aykj20c807igme.jpg", "pic_urls": [ { "thumbnail_pic": "http://ww2.sinaimg.cn/thumbnail/c5cde7e1jw1e8f9ft7aykj20c807igme.jpg" } ], "reposts_count": 0, "source": "<a href=\"http://app.weibo.com/t/feed/48buUD\" rel=\"nofollow\">晚九朝五</a>", "text": "夜幕降临,黑暗挑逗激情,霓红闪烁,狂欢驱走寂寞,这里是夜幕下的潮人圣殿,人人都是主角,此时此刻,你来主宰夜晚的开始,从晚九HIGH到天亮。晚上九点,让我们一起开始吧...http://t.cn/zYbfCUY", "thumbnail_pic": "http://ww2.sinaimg.cn/thumbnail/c5cde7e1jw1e8f9ft7aykj20c807igme.jpg", "truncated": false, "visible": { "list_id": 0, "type": 0 } }, "statuses_count": 3, "url": "", "verified": false, "verified_reason": "", "verified_type": -1.0, "weihao": "" } */ /** * @param token * @param uid * @param count 单页返回的记录条数,最大不超过200。 * @param cursor 返回结果的游标,下一页用返回值里的next_cursor,上一页用previous_cursor,首页为0。 * @return */ public WeiboFriend getFriends(String token, String uid, int count, int cursor) { Assert.hasText(token); Assert.hasText(uid); Assert.state(count > 0); Assert.state(count <= 200); Assert.state(cursor >= 0); String url = String.format( "https://api.weibo.com/2/friendships/friends.json?uid=%s&count=%s&cursor=%s&access_token=%s", uid, count, cursor, token); String json = restTemplate.getForObject(url, String.class); WeiboFriend weiboFriend = jsonMapper.fromJson(json, WeiboFriend.class); if (weiboFriend == null || weiboFriend.getUsers() == null) { throw new RuntimeException("获取用户信息发生错误"); } return weiboFriend; } /*需在开发者账号设置回调URL,iOS客户端在程序内写死了回调URL,不知修改是否有影响,暂不做web微博登录 private String weibo_redirect_uri = "/weibo_callback"; public String authorizeUrl(String baseurl) { return String.format("https://api.weibo.com/oauth2/authorize?response_type=code&client_id=%s&redirect_uri=%s", weibo_api_key, baseurl + weibo_redirect_uri); }*/ public static class WeiboFriend { private List<WeiboUser> users; private int next_cursor; private int previous_cursor; private int total_number; public List<WeiboUser> getUsers() { return users; } public void setUsers(List<WeiboUser> users) { this.users = users; } public int getNext_cursor() { return next_cursor; } public void setNext_cursor(int next_cursor) { this.next_cursor = next_cursor; } public int getPrevious_cursor() { return previous_cursor; } public void setPrevious_cursor(int previous_cursor) { this.previous_cursor = previous_cursor; } public int getTotal_number() { return total_number; } public void setTotal_number(int total_number) { this.total_number = total_number; } } public static class WeiboUser { private String id; private String screen_name; private String name; private String gender; private Boolean verified; private String profile_image_url; private String description; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getScreen_name() { return screen_name; } public void setScreen_name(String screen_name) { this.screen_name = screen_name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Boolean getVerified() { return verified; } public void setVerified(Boolean verified) { this.verified = verified; } public String getProfile_image_url() { return profile_image_url; } public void setProfile_image_url(String profile_image_url) { this.profile_image_url = profile_image_url; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } } }
@Service @Transactional("transactionManager") public class AppService extends BaseService { @Autowired private AppDao appDao; @Autowired private ThirdAppService thirdAppService; @Autowired private TemplateService templateService; private static boolean updating = false; private JsonMapper jsonMapper = JsonMapper.nonDefaultMapper(); private static final String DIR = "res/"; @Log(context = "资源管理", object = "App管理", action = 1, detail = "保存App") public void saveApp(App app) { appDao.save(app); } @Log(context = "资源管理", object = "App管理", action = 2, detail = "查询指定App") public App getApp(Long id) { return appDao.findOne(id); } @Log(context = "资源管理", object = "App管理", action = 2, detail = "查询App") public Page<App> getAllApp( int pageNumber, int pageSize, String sortType, Map<String, Object> searchParams) { PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortType); Specification<App> spec = buildSpecification(searchParams, App.class); return appDao.findAll(spec, pageRequest); } @Log(context = "资源管理", object = "App管理", action = 4, detail = "删除App") public void deleteApp(Long id) { appDao.deleteById(id); } @Log(context = "资源管理", object = "App管理", action = 4, detail = "删除App") public void deleteApp(String ids) { String[] idArray = ids.split(","); for (String id : idArray) { if (StringUtilsCustom.isNotBlank(id)) { App item = appDao.findOne(Long.valueOf(id)); appDao.delete(item); } } } public void autoRefreshAppList() { refreshAppList(true); } public void manualRefreshAppList() { refreshAppList(false); } private Set<String> getImgs() { Set<String> imgSet = new HashSet<String>(); List<App> apps = appDao.findAutoUpdatedList(); for (App app : apps) { String url1080 = app.getUrl1080(); if (url1080 != null && !url1080.equals("")) { imgSet.add(app.getUrl1080()); } } return imgSet; } private synchronized void refreshAppList(boolean auto) { try { updating = true; Set<String> imgSet = getImgs(); List<Machine> machines = MachineUtils.getMachineList(); appDao.deleteAutoUpdatedRecords(); HashSet<String> set = new HashSet<String>(); for (Machine machine : machines) { String data = thirdAppService.getAppData(machine.getCode(), "3.0"); AppVO appVO = jsonMapper.fromJson(data, AppVO.class); if (appVO.getState().equals("0000")) { for (AppInfo appInfo : appVO.getZone()) { App app = new App(); app.setActionUrl(jsonMapper.toJson(appInfo.getData())); app.setUrl1080(upload(appInfo.getIcon())); app.setClientType(machine.getCode()); app.setTitle(jsonMapper.toJson(new String[] {appInfo.getName()})); app.setUpdateRefer("app:1"); if (auto) { User user = new User(); user.setId(1L); app.setUser(user); } else { app.setUser(UserUtils.getUser()); } appDao.save(app); set.add(app.getUpdateRefer()); } } } for (String ur : set) { templateService.evictTplByUpdateRefer(ur); } } catch (Exception e) { throw new RuntimeException(e); } finally { updating = false; } } public String getUpdatedDate() { Date date = appDao.recentUpdatedDate(); if (date != null) { return DateUtilsCustom.formatDate(date, "yyyy年MM月dd日 HH:mm:ss"); } else { return ""; } } public App getNewApp() { App item = new App(); return item; } public static String upload(String url) throws IOException { if (url == null || url.length() == 0) { return null; } IOException ioe = null; String remoteName = DIR + System.currentTimeMillis() + "_" + IOUtils.getFileNameFromUrl(url); for (int i = 0; i < 5; i++) { try { FileStatus status = OSSClientTemplate.getInstance().uploadByUrl(url, remoteName); return status.getUrl(); } catch (Exception e) { e.printStackTrace(); System.out.println("get file failed,try again:" + url); ioe = new IOException(e + "\n file url = " + url); } try { Thread.sleep(1000L); } catch (InterruptedException e) { e.printStackTrace(); } } if (ioe != null) { throw ioe; } return null; } public static boolean isUpdating() { return updating; } }
@Controller @RequestMapping("mpt") public class MptControlle { @Autowired private MptService mpts; private static JsonMapper mapper = JsonMapper.nonDefaultMapper(); @RequestMapping("login") public void login(User user, HttpServletResponse request, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); User user1 = new User(); user1 = mpts.getuser(user); if (user1 == null || user1.getUsername() == null) { out.write("-1"); } else if (user1.getPassword().equals(user.getPassword())) { String json = mapper.toJson(user1); out.write(json); } else { out.write("-2"); } out.close(); } @RequestMapping("zc") public void zc(User user, HttpServletResponse request, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); try { User user1 = new User(); user1 = mpts.getuser(user); if (user1 != null) { out.write("-3"); } else { mpts.saveuser(user); out.write("1"); } } catch (Exception e) { out.write("-1"); e.printStackTrace(); } finally { out.close(); } } @RequestMapping("querytype") public void querytype(HttpServletResponse request, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); List<CosmeticType> list = mpts.getAll(); String json = mapper.toJson(list); out.write(json); out.close(); } @RequestMapping("queryct") public void queryCosmeticsbytype( Long typeid, HttpServletResponse request, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); List<Map<String, String>> list = mpts.queryCosmeticsbytype(typeid); String json = mapper.toJson(list); out.write(json); out.close(); } @RequestMapping("queryc") public void queryCosmetics(Long id, HttpServletResponse request, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); Cosmetics cos = mpts.getCos(id); String json = mapper.toJson(cos); out.write(json); out.close(); } @RequestMapping("querycpp") public void querycospp(String name, HttpServletResponse request, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); System.out.println("121111111111111111111111111" + name); List<Map<String, String>> list = mpts.querycospp(name); String json = mapper.toJson(list); out.write(json); out.close(); } @RequestMapping("queryzhuye") public void queryzhuye(String type, HttpServletResponse request, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); List<Map<String, String>> list = mpts.queryzhuye(type); String json = mapper.toJson(list); out.write(json); out.close(); } @RequestMapping("querycosq") public void querycosq(HttpServletResponse request, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); List<Cosmetics> list = mpts.queryCos(); String json = mapper.toJson(list); out.write(json); out.close(); } @RequestMapping("updatemm") public void updatemm( Long userid, String password, HttpServletResponse request, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); try { mpts.updatemm(userid, password); out.write("1"); } catch (Exception e) { out.write("-1"); e.printStackTrace(); } finally { out.close(); } } @RequestMapping("savecar") public void savecar( Long cosmetics_id, Integer buy_count, Integer comstics_count, Long user_id, HttpServletResponse request, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); try { mpts.savecar(cosmetics_id, buy_count, comstics_count, user_id); out.write("1"); } catch (Exception e) { out.write("-1"); e.printStackTrace(); } finally { out.close(); } } @RequestMapping("querycar") public void querycar(Long user_id, HttpServletResponse request, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); List<Map<String, String>> list = mpts.querycar(user_id); String json = mapper.toJson(list); out.write(json); out.close(); } @RequestMapping("deletecar") public void deletecar(String shoppid, HttpServletResponse request, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); try { mpts.deletecar(shoppid); out.write("1"); } catch (Exception e) { out.write("-1"); e.printStackTrace(); } finally { out.close(); } } @RequestMapping("deletecarsp") public void deletecarsp( String shoppid, String cosid, HttpServletResponse request, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); try { mpts.deletecarsp(shoppid, cosid); out.write("1"); } catch (Exception e) { out.write("-1"); e.printStackTrace(); } finally { out.close(); } } @RequestMapping("savedt") public void savedt(MyorderBen myorder, HttpServletResponse request, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); try { mpts.savedt(myorder); out.write("1"); } catch (Exception e) { out.write("-1"); e.printStackTrace(); } finally { out.close(); } } @RequestMapping("querydtall") public void querydtall(int user_id, HttpServletResponse request, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); List<Map<String, String>> map = mpts.querydtall(user_id); String json = mapper.toJson(map); out.write(json); out.close(); } @RequestMapping("queryzixun") public void queryzixun(Long type, HttpServletResponse request, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); List<Map<String, String>> map = mpts.queryzixun(type); String json = mapper.toJson(map); out.write(json); out.close(); } @RequestMapping("saveAdvice") public void saveAdvice( Advice advice, Long userid, HttpServletResponse request, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); try { User user = mpts.getuserid(userid); advice.setUser(user); mpts.saveadvice(advice); out.write("1"); } catch (Exception e) { out.write("-1"); e.printStackTrace(); } finally { out.close(); } } }