// 获得所有菜单评论的集合 public void getMenuMsgList() throws IOException { String pageStr = req.getParameter("page"); String rowStr = req.getParameter("rows"); Integer page = 1; Integer row = 5; if (pageStr != null && !"".equals(pageStr)) { page = Integer.parseInt(pageStr); } if (rowStr != null && !"".equals(rowStr)) { row = Integer.parseInt(rowStr); } menumsglist = mymmsg.getMenuMsgList(page, row); int num = 0; if (mymmsg.MenuMsgCount() % row == 0) { num = mymmsg.MenuMsgCount() / row; } else { num = mymmsg.MenuMsgCount() / row + 1; } PrintWriter out = res.getWriter(); JSONObject json = new JSONObject(); json.put("pages", page); json.put("total", num); json.put("rows", menumsglist); out.write(json.toString()); out.flush(); out.close(); }
private static JSONObject extractPercentileTransactionSet( Map<Integer, TreeMap<String, PercentileTransactionWholeRun>> graphData, HashSet<String> transactions) { JSONObject graphDataSet = new JSONObject(); JSONArray labels = new JSONArray(); HashMap<String, ArrayList<Number>> percentileTrtData = new HashMap<String, ArrayList<Number>>(0); for (String transaction : transactions) { percentileTrtData.put(transaction, new ArrayList<Number>(0)); } for (Map.Entry<Integer, TreeMap<String, PercentileTransactionWholeRun>> result : graphData.entrySet()) { labels.add(result.getKey()); for (String transaction : transactions) { if (!result.getValue().containsKey(transaction)) { percentileTrtData.get(transaction).add(null); // TODO:change to null continue; } percentileTrtData .get(transaction) .add((result.getValue()).get(transaction).getActualValue()); } } graphDataSet.put(LABELS, labels); graphDataSet.put(SERIES, createGraphDatasets(percentileTrtData)); return graphDataSet; }
/** * 创建直播 * * @param url * @param currUser * @param sourceId * @param groupName * @param groupLogoUrl * @return * @throws XueWenServiceException */ public Live create( String url, User currUser, String sourceId, String groupName, String groupLogoUrl) throws XueWenServiceException { List<JSONObject> groupList = new ArrayList<JSONObject>(); JSONObject group = new JSONObject(); group.put("groupId", sourceId); group.put("groupName", groupName); group.put("groupLogoUrl", groupLogoUrl); groupList.add(group); if (!this.exiseByUrl(url)) { if (!StringUtil.isBlank(url)) { // 判断此url是否已经被创建 if (url.contains(Config.LIVE_URL_VHSTART)) { try { return this.createVhLive(url, groupList, currUser); } catch (Exception e) { throw new XueWenServiceException(Config.STATUS_201, "创建直播错误", null); } } } } else { Live l = this.findByLiveUrl(url); List<JSONObject> groups = l.getGroup(); for (JSONObject g : groups) { if (sourceId.equals(g.getString("groupId"))) { throw new XueWenServiceException(Config.STATUS_201, "此直播已存在", null); } } groups.addAll(groupList); return liveRepo.save(l); } throw new XueWenServiceException(Config.STATUS_201, "创建直播失败", null); }
@POST @At("/ht/pamsave") @Ok("json") public JSONObject save(@Param("..") Parameter params) { JSONObject json = new JSONObject(); json.put(Constant.SUCCESS, false); try { if (StringUtil.checkNotNull(params.getStationID())) { baseService.dao.insert(params.getStationID(), cov(params, true)); // baseService.dao.insert(params) ; json.put(Constant.SUCCESS, true); dls.insert("01", tableName, getHTLoginUserName()); dls.insertNDY(tableName, params.getStationID(), null, params.getCreateDate()); json.put(Constant.INFO, "操作成功"); } else { json.put(Constant.INFO, "请选择观测站或观测站ID错误"); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); json.put(Constant.INFO, e.getMessage()); } finally { return json; } }
private static JSONObject extractAvgTrtData( Map<Integer, TreeMap<String, AvgTransactionResponseTime>> graphData, HashSet<String> transactions) { HashMap<String, ArrayList<Number>> averageTRTData = new HashMap<String, ArrayList<Number>>(0); JSONObject graphDataSet = new JSONObject(); JSONArray labels = new JSONArray(); for (String transaction : transactions) { averageTRTData.put(transaction, new ArrayList<Number>(0)); } for (Map.Entry<Integer, TreeMap<String, AvgTransactionResponseTime>> result : graphData.entrySet()) { labels.add(result.getKey()); for (String transaction : transactions) { if (!result.getValue().containsKey(transaction)) { averageTRTData.get(transaction).add(null); // TODO:change to null continue; } averageTRTData .get(transaction) .add((result.getValue()).get(transaction).getActualValueAvg()); } } graphDataSet.put(LABELS, labels); JSONArray datasets = createGraphDatasets(averageTRTData); graphDataSet.put(SERIES, datasets); return graphDataSet; }
@Override protected void onTextMessage(CharBuffer message) throws IOException { String temp = message.toString(); JSONObject json = (JSONObject) JSONSerializer.toJSON(temp); String type = json.getString("type").toLowerCase().replaceAll(" ", ""); String location = json.getString("location"); String lat = json.getString("lat"); String lng = json.getString("lng"); String radius = json.getString("radius"); String keywords = json.getString("keywords"); String result = null; try { if (type.equals("overview")) result = getOverViewData(location, lat, lng, radius, keywords); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); JSONObject jsonResult = new JSONObject(); jsonResult.put("error", "true"); result = jsonResult.toString(); } if (result == null || result.equals("")) { JSONObject jsonResult = new JSONObject(); jsonResult.put("error", "true"); result = jsonResult.toString(); } Charset charset = Charset.forName("ISO-8859-1"); CharsetDecoder decoder = charset.newDecoder(); CharsetEncoder encoder = charset.newEncoder(); CharBuffer uCharBuffer = CharBuffer.wrap(result); ByteBuffer bbuf = encoder.encode(uCharBuffer); CharBuffer cbuf = decoder.decode(bbuf); getWsOutbound().writeTextMessage(cbuf); }
// 上传文件 public String upLoadOne() throws Exception { JSONObject jsonObject = new JSONObject(); String id = ((String[]) formMap.get("id"))[0] + ""; // 获取id String uploadName = ((String[]) formMap.get("uploadName"))[0] + ""; // 获取id ReptTechDtl rt = techReptDtlService.get(Long.parseLong(id)); // dtl try { String targetDirectory = getTechPath() + rt.getTechReptDef().getId() + rt.getTechReptDef().getName(); String temArr[] = uploadName.split("\\."); String fileName = UUID.randomUUID().toString(); // 读取 if (temArr.length != 0) { fileName = fileName + "." + temArr[temArr.length - 1]; } File target = new File(targetDirectory, fileName); FileUtils.copyFile(formFile, target); // 更新技办人 和上传名称和实际存放的名称 rt.setTekofficer(getCurUser().getName()); // rt.setUploadName(uploadName); rt.setSaveName(fileName); rt.setUpdDate(DateUtil.dateToDateByFormat(utilService.getSysTime(), DateUtil.FORMAT)); techReptDtlService.save(rt); } catch (Exception e) { e.printStackTrace(); jsonObject.put("result", false); json = jsonObject.toString(); return EASYFILE; } jsonObject.put("result", true); json = jsonObject.toString(); return EASYFILE; }
public String execute() throws Exception { response.setCharacterEncoding("UTF-8"); // 编码 int count = memberFriendService.findMemberCountByInsertDate(insertDate); // 统计数量 List list = memberFriendService.findMemerFriendListByTime(page, rows, insertDate); // 根据投票选项编号,查找详情列表 PrintWriter out = response.getWriter(); try { JsonConfig cfg = new JsonConfig(); cfg.registerJsonValueProcessor( java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd")); JSONArray arr = JSONArray.fromObject(list, cfg); JSONObject jsonObj = new JSONObject(); jsonObj.put("rows", arr); jsonObj.put("total", count); out.write(jsonObj.toString()); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } return null; }
public void download_link() { List<MonitorSysCommonLink> commonLink = commonDAO.find(Inquiry.forClass(MonitorSysCommonLink.class)); String[] links = new String[commonLink.size()]; String tempLink; for (int i = 0; i < links.length; i++) { // 字符串拼接 tempLink = "http://" + MemoryData.localIpAddress + ":" + MemoryData.portNum + "/" + MemoryData.projectName + "/uploadfile/activefile/"; tempLink += commonLink.get(i).getResourceLink(); links[i] = tempLink; } JSONObject jo = new JSONObject(); jo.put("links", links); jo.put("commonLink", commonLink); try { response.getWriter().write(jo.toString()); } catch (IOException e) { e.printStackTrace(); } }
public String getUserAuthorization() { User user = userService.findUserById(userid); if (user == null) { ret.put("retCode", "1001"); ret.put("retMSG", "该用户不存在"); return "success"; } Integer userauth = user.getAuthorization(); List<Permission> pers = permissionService.findAllPermissions(); List<Permission> auth = new ArrayList<Permission>(); // magic here, don't touch for (int i = 0; i < pers.size(); i++) { Double d = Math.pow(2, pers.get(i).getValue()); if ((userauth & d.intValue()) != 0) { auth.add(pers.get(i)); } } JSONArray ja = JSONArray.fromObject(auth); ret.put("auth", ja); ret.put("retCode", "1000"); ret.put("retMSG", "操作成功"); return "success"; }
public String updateAuthorization() { User user = userService.findUserById(userid); if (user == null) { ret.put("retCode", "1001"); ret.put("retMSG", "该用户不存在"); return "success"; } Integer auth = 0; String[] newauths = newauthorization.split(","); for (int i = 0; i < newauths.length; i++) { Permission per = permissionService.findPermissionByValue(Integer.parseInt(newauths[i])); if (per != null) { Double d = Math.pow(2, per.getValue()); auth += d.intValue(); } } user.setAuthorization(auth); userService.updateUser(user); ret.put("retCode", "1000"); ret.put("retMSG", "权限更新成功"); return "success"; }
private String jsonArtistes(Map<String, Artiste> artistes) { Map<String, Artiste> artistesTrie = new TreeMap<String, Artiste>(artistes); JSONObject jsonResultat = new JSONObject(); JSONArray jsonArtistes = new JSONArray(); for (String nome : artistesTrie.keySet()) { Artiste artiste = artistesTrie.get(nome); JSONObject jsonArtiste = new JSONObject(); jsonArtiste.put("nom", nome); JSONArray jsonAlbums = new JSONArray(); for (Integer annee : artiste.getAlbums().keySet()) { Album album = artiste.getAlbums().get(annee); JSONObject newAlbum = new JSONObject(); newAlbum.put("id", album.getId()); newAlbum.put("titre", album.getTitre()); newAlbum.put("annee", album.getAnnee()); newAlbum.put("qte", album.getQuantite()); jsonAlbums.add(newAlbum); } jsonArtiste.accumulate("albums", jsonAlbums); jsonArtistes.add(jsonArtiste); } jsonResultat.accumulate("artistes", jsonArtistes); return jsonResultat.toString(2); }
/** * get roles assigned to particular user. * * @param userId * @return */ public JSONObject getUserRoles(String userId) { JSONObject jObj = null; List<UserRoleEntity> userRoleList = userRoleDaoService.getRolesByUserId(userId); if (userRoleList != null && userRoleList.size() > 0) { log.info(">>> User role list: " + userRoleList); jObj = new JSONObject(); jObj.put("userRoleList", userRoleList); // for (UserRoleEntity ent : userRoleList) { // if ("SUPERUSER".equals(ent.getRoleName())) { // jObj.put("managementUrl", "vwg-admin/vwUserRole.jsp"); // break; // } // } jObj.put("returnCode", "SUCCESS"); jObj.put("returnMessage", "SUCCESS"); } else { jObj = new JSONObject(); jObj.put("returnCode", "SUCCESS"); jObj.put("returnMessage", "No available users is found."); } return jObj; }
/** * Consulta las lineas de credito 24x7 del cliente, solo se puede tener una linea por cliente * * @param request Datos de entrada de la peticion, se recibe un json * @param response Datos de salida de la petcion * @return regresa la respuesta del servicio en formato json */ public ModelAndView consultarDatosLinea24X7( HttpServletRequest request, HttpServletResponse response) { ClienteBean cliente = (ClienteBean) request.getSession().getAttribute("cliente"); JSONResponseBean responseBean = new JSONResponseBean(); JSONObject jsonObject = new JSONObject(); CreditoConsumoBean linea = null; try { linea = lineas24x7Service.consultarDatosLinea24X7("", cliente); jsonObject.put("autorizado", linea.getSaldos().getMontoAutorizado()); jsonObject.put("disponible", linea.getSaldos().getMontoDisponible()); jsonObject.put("vigencia", linea.getFechas().getFechaVencimientoLinea()); jsonObject.put("credito", linea.getNumCredito()); jsonObject.put("montoMinimo", linea.getSaldos().getMontoMinimo()); jsonObject.put("entidad", linea.getProducto().getIdEntidad()); responseBean.setError(ErrorBean.SUCCESS); responseBean.setDto(JSONObject.fromBean(jsonObject).toString()); } catch (BusinessException e) { responseBean.setError(e.getError()); } return getResponseView(responseBean); }
private String getOverViewData( String location, String lat, String lng, String radius, String keywords) { JSONObject json = new JSONObject(); SensorManager sensorManager = new SensorManager(); ArrayList<Sensor> sensors = sensorManager.getAllSpecifiedSensorAroundPlace("traffic", lng, lat, radius); ArrayList<String> arr = new ArrayList<>(); for (Sensor sensor : sensors) { arr.add(sensor.getSource()); } json.put("traffic", arr); sensors = sensorManager.getAllSpecifiedSensorAroundPlace("airport", lng, lat, "20"); arr = new ArrayList<>(); for (Sensor sensor : sensors) { arr.add(sensor.getSource()); } json.put("airport", arr); sensors = sensorManager.getAllSpecifiedSensorAroundPlace("railwaystation", lng, lat, radius); arr = new ArrayList<>(); for (Sensor sensor : sensors) { arr.add(sensor.getSource()); } json.put("railwaystation", arr); String sindice = DatabaseUtilities.getSindiceSearch(keywords); JSONObject jsonSindice = (JSONObject) JSONSerializer.toJSON(sindice); String[] aryStrings = {"Title", "Formats", "Updated"}; jsonSindice.put("vars", aryStrings); json.put("sindice", jsonSindice); return json.toString(); }
@Override public void handle(HttpExchange arg0) throws IOException { try { JSONObject request = (JSONObject) JSONSerializer.toJSON(IOUtils.toString(arg0.getRequestBody())); String email = request.getString("email"); String key = request.getString("key"); for (int i = 0; i < jobs.size(); i++) { TnrsJob job = jobs.get(i); if (job.getRequest().getId().equals(key) && job.getRequest().getEmail().equals(email)) { JSONObject json = (JSONObject) JSONSerializer.toJSON(job.toJsonString()); json.put("status", "incomplete"); json.put("progress", job.progress()); HandlerHelper.writeResponseRequest(arg0, 200, json.toString(), "application/json"); return; } } if (JobHelper.jobFileExists(baseFolder, email, key)) { TnrsJob job = JobHelper.readJobInfo(baseFolder, email, key); HandlerHelper.writeResponseRequest(arg0, 200, job.toJsonString(), "application/json"); } else { HandlerHelper.writeResponseRequest( arg0, 500, "No such job exists o it might have expired", "text/plain"); } } catch (Exception ex) { log.error(ExceptionUtils.getFullStackTrace(ex)); throw new IOException(ex); } }
private JSONObject reformLastestTrafficData(String sensorURL, JSONArray filterArr) { JSONObject result = new JSONObject(); try { SensorManager sensorManager = new SensorManager(); Sensor sensor = sensorManager.getSpecifiedSensorWithSensorId(sensorURL); if (sensor == null) return result; Observation obs = sensorManager.getNewestObservationForOneSensor(sensorURL); JSONObject metaJson = new JSONObject(); metaJson.put("name", sensor.getName()); metaJson.put("source", sensor.getSource()); metaJson.put("sourceType", sensor.getSourceType()); metaJson.put("city", sensor.getPlace().getCity()); metaJson.put("country", sensor.getPlace().getCountry()); OutputStream out = null; out = DatabaseUtilities.getNewestSensorData(sensorURL); JSONObject json = (JSONObject) JSONSerializer.toJSON(out.toString()); json.put("updated", DateUtil.date2StandardString(new Date())); json.put("ntriples", JSONUtil.JSONToNTriple(json.getJSONObject("results"))); json.put("error", "false"); json.put("meta", metaJson); System.out.println(json); result = json; } catch (Exception e) { e.printStackTrace(); JSONObject jsonResult = new JSONObject(); jsonResult.put("error", "true"); jsonResult.put("ntriples", ""); result = jsonResult; } return result; }
private void databases(HttpServletResponse response) { try { JSONArray json = new JSONArray(); for (String dbName : DBUtils.getLocalDBNames()) { JSONArray tables = new JSONArray(); for (String tableName : DBUtils.getTableNames(new TemplateLocalhostConnection(), dbName)) { JSONObject table = new JSONObject(); table.put("table", tableName); table.put( "size", DBUtils.getTableCount(new TemplateLocalhostConnection(), dbName, tableName)); tables.add(table); } JSONObject database = new JSONObject(); database.put("name", dbName); database.put("tables", tables); json.add(database); } response.setContentType("application/json"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println(json); } catch (Exception e) { new TalesException(new Throwable(), e); } }
// 删除文件 public String delLoadOne() throws Exception { String id = ((String[]) formMap.get("id"))[0] + ""; // 获取id ReptTechDtl rt = techReptDtlService.get(Long.parseLong(id)); // dtl JSONObject jsonObject = new JSONObject(); try { if (deleteFile( rt.getTechReptDef().getId() + rt.getTechReptDef().getName(), rt.getSaveName())) { // 删除文件 rt.setTekofficer(getCurUser().getName()); // 更新技办人 和上传名称和实际存放的名称 rt.setUploadName(null); rt.setSaveName(null); rt.setUpdDate(DateUtil.dateToDateByFormat(utilService.getSysTime(), DateUtil.FORMAT)); techReptDtlService.save(rt); } else { jsonObject.put("result", false); json = jsonObject.toString(); return EASY; } } catch (Exception e) { jsonObject.put("result", false); json = jsonObject.toString(); return EASY; } jsonObject.put("result", true); json = jsonObject.toString(); return EASY; }
private void createMaxMissFiles( JSONObject miss1, JSONObject miss2, JSONObject miss3, JSONObject miss4, JSONObject miss5) { JSONObject root = new JSONObject(); Map<String, Integer> missDataMap = MapSortUtil.sortByIntegerValueDesc(miss1); root.put("num_1_b", getMaxMissObj(missDataMap)); missDataMap = MapSortUtil.sortByIntegerValueAsc(miss1); root.put("num_1_s", getMaxMissObj(missDataMap)); missDataMap = MapSortUtil.sortByIntegerValueDesc(miss2); root.put("num_2_b", getMaxMissObj(missDataMap)); missDataMap = MapSortUtil.sortByIntegerValueAsc(miss2); root.put("num_2_s", getMaxMissObj(missDataMap)); missDataMap = MapSortUtil.sortByIntegerValueDesc(miss3); root.put("num_3_b", getMaxMissObj(missDataMap)); missDataMap = MapSortUtil.sortByIntegerValueAsc(miss3); root.put("num_3_s", getMaxMissObj(missDataMap)); missDataMap = MapSortUtil.sortByIntegerValueDesc(miss4); root.put("num_4_b", getMaxMissObj(missDataMap)); missDataMap = MapSortUtil.sortByIntegerValueAsc(miss4); root.put("num_4_s", getMaxMissObj(missDataMap)); missDataMap = MapSortUtil.sortByIntegerValueDesc(miss5); root.put("num_5_b", getMaxMissObj(missDataMap)); missDataMap = MapSortUtil.sortByIntegerValueAsc(miss5); root.put("num_5_s", getMaxMissObj(missDataMap)); WriteHTMLUtil.writeHtm( "/js/analyse/" + getLottery().getKey() + "/", "qyh_max_miss.js", "qyh_max_miss=" + root + ";", "UTF-8"); }
public String getSuccessString(String API_CODE, JSONObject temp) { JSONArray jarray = new JSONArray(); temp.put("status", "0"); temp.put("msg", API_CODE + "00"); jarray.add(temp); return jarray.toString(); }
/** 获得时间树的天数和便签数 */ @RequestMapping("returnTreeDay") public void returnTreeDay( HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException { User user = (User) session.getAttribute(Constant.USER); String year = request.getParameter("year"); String month = request.getParameter("month"); String condition = "createDate >= '" + year + "-" + month + "-01 00:00:00' and createDate <= '" + year + "-" + month + "-31 23:59:59'"; Note note = new Note(); note.setUserId(user.getUserId()); note.setCondition(condition); List<Map<String, Object>> noteList = noteMapperService.selectDay(note); JSONObject jsonObject = new JSONObject(); jsonObject.put("result", "success"); jsonObject.put("data", noteList); response.getWriter().write(jsonObject.toString()); }
@Override public void handleData() { // TODO Auto-generated method stub Message message = MessageManager.createMessage(cassandraClient, appId, userId, toUserId, messageContent); String messageId = message.getMessageId(); MessageManager.createUserPostIndex(cassandraClient, userId, toUserId, messageId); List<HColumn<String, String>> clist = cassandraClient.getColumnKey( DBConstants.USER, toUserId, DBConstants.F_NICKNAME, DBConstants.F_AVATAR); String nickName = null; String avatar = null; for (int i = 0; i < clist.size(); i++) { HColumn<String, String> column = clist.get(i); if (column.getName().equals(DBConstants.F_NICKNAME)) { nickName = column.getValue(); } else if (column.getName().equals(DBConstants.F_AVATAR)) { avatar = column.getValue(); } } String createDate = message.getCreateDate(); JSONObject obj = new JSONObject(); obj.put(ServiceConstant.PARA_MESSAGE_ID, messageId); obj.put(ServiceConstant.PARA_NICKNAME, nickName); obj.put(ServiceConstant.PARA_AVATAR, avatar); obj.put(ServiceConstant.PARA_CREATE_DATE, createDate); resultData = obj; }
/** * 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()); } }
private static JSONObject extractVuserResult(Map<Integer, TreeMap<String, Integer>> graphData) { JSONObject graphDataSet; graphDataSet = new JSONObject(); JSONArray labels = new JSONArray(); HashMap<String, ArrayList<Number>> vUserState = new HashMap<String, ArrayList<Number>>(0); vUserState.put("Passed", new ArrayList<Number>(0)); vUserState.put("Failed", new ArrayList<Number>(0)); vUserState.put("Stopped", new ArrayList<Number>(0)); vUserState.put("Error", new ArrayList<Number>(0)); for (Map.Entry<Integer, TreeMap<String, Integer>> run : graphData.entrySet()) { Number tempVUserCount = run.getValue().get("Count"); if (tempVUserCount != null && tempVUserCount.intValue() > 0) { labels.add(run.getKey()); vUserState.get("Passed").add(run.getValue().get("Passed")); vUserState.get("Failed").add(run.getValue().get("Failed")); vUserState.get("Stopped").add(run.getValue().get("Stopped")); vUserState.get("Error").add(run.getValue().get("Error")); } } graphDataSet.put(LABELS, labels); graphDataSet.put(SERIES, createGraphDatasets(vUserState)); return graphDataSet; }
private void loadFiles(final IBasicFile[] jsonFiles, final JSONArray result, final String type) throws IOException { Arrays.sort( jsonFiles, new Comparator<IBasicFile>() { @Override public int compare(IBasicFile file1, IBasicFile file2) { if (file1 == null && file2 == null) { return 0; } else { return file1.getFullPath().toLowerCase().compareTo(file2.getFullPath().toLowerCase()); } } }); IReadAccess access = CdeEnvironment.getPluginSystemReader(SYSTEM_CDF_DD_TEMPLATES); for (int i = 0; i < jsonFiles.length; i++) { final JSONObject template = new JSONObject(); String imgResourcePath = resoureUrl + "unknown.png"; if (access.fileExists(jsonFiles[i].getName().replace(".cdfde", ".png"))) { imgResourcePath = resoureUrl + jsonFiles[i].getName().replace(".cdfde", ".png"); } template.put("img", imgResourcePath); template.put("type", type); template.put("structure", JsonUtils.readJsonFromInputStream(jsonFiles[i].getContents())); result.add(template); } }
/** 我的购物车列表 */ public void myStore() throws IOException { id = Integer.parseInt(ServletActionContext.getRequest().getParameter("id")); List<GoodStore> listgoostore = goodStoreService.getMyStore(id); for (GoodStore goodStore : listgoostore) { JSONObject jsonObj = new JSONObject(); Goods good = goodsService.getGoods(goodStore.getGoodId()); jsonObj.put("goodStoreid", goodStore.getGoodStoreid()); jsonObj.put("title", good.getTitle()); jsonObj.put("price", good.getPrice()); jsonObj.put("count", goodStore.getCount()); jsonObj.put("id", goodStore.getGoodId()); List<Image> listimage = imageServiceImpl.getimage(goodStore.getGoodId(), 3); Image image = new Image(); if (listimage.size() > 0) { image.setImageUrl(IpMain.IP + listimage.get(1).getImageUrl()); } else { image.setImageUrl(""); } jsonObj.put("imgUrl", image); array.add(jsonObj); } m.put("msg", array); ServletActionContext.getResponse().getWriter().write(JSON.toJSONString(m)); }
/** * 将集合元素封装成json对象并返回 * * @param list 要封装的数组集合 * @param config 类在转换成json数据时遵循的一些配置规则 * @param status 状态标识 * @return json对象 返回json对象的内部格式如下:data中的内容就是list集合中的内容,count表示data中的条数,也就是list集合中数据数 { status:1, * message:"ok", result:{ count:2, data:[ * {id:"2353sdkfhosdf",name:boat.jpg,type=1,savepath:"http://172.19.68.77:8080/zhushou/images/logo.jpg"}, * {id:"2353sdkfhosdf",name:boat.jpg,type=1,savepath:"http://172.19.68.77:8080/zhushou/images/logo.jpg"}, * <p>] } } */ @Deprecated public static <T> JSONObject createJsonObject(List<T> list, JsonConfig config, MyStatus status) { // 整个json JSONObject jsonObject = new JSONObject(); // result json JSONObject resultObject = new JSONObject(); // 数组json JSONArray jsonArray = new JSONArray(); int count = 0; if (list != null) { for (T entity : list) { JSONObject entityJson; if (config == null) entityJson = JSONObject.fromObject(entity); else entityJson = JSONObject.fromObject(entity, config); jsonArray.add(entityJson); count++; } } resultObject.put("count", count); resultObject.put("data", jsonArray); jsonObject.put("result", resultObject); JsonTool.putStatusJson(status, jsonObject); return jsonObject; }
/* * ajax修改角色 * 返回json */ @Action( value = "/role/editRole", interceptorRefs = {@InterceptorRef("roleInterceptor")}, results = { @Result(name = "noLogin", type = "chain", location = "loginErrorAjax"), @Result(name = "noRoleAuthority", type = "chain", location = "noAuthorityAjax") }) public String editRole() throws Exception { result = new JSONObject(); role = new Role(false); if (roleName != null && roleId != null) { role.setRoleId(Integer.parseInt(roleId)); role.setRoleName(roleName); if (roleDescription != null) { role.setRoleDescription(roleDescription); } role.setRoleStatus(roleState); StringUtil.String2RoleAuthority(roleAuthority, role); roleService.updateRole(role); result.put("result", 1); if (role.getRoleStatus() == 1) { request.getServletContext().setAttribute("role_" + roleId, role); } } else { result.put("result", 2); } return "json"; }
/** * Creates a JSON string for testing. * * @param workspaceId the workspace ID. * @param analysisId the analysis ID. * @param favorite true if the object should be placed in the user's workspace. * @return the JSON string. */ private String createJsonString(int workspaceId, String analysisId, boolean favorite) { JSONObject json = new JSONObject(); json.put("workspace_id", workspaceId); json.put("analysis_id", analysisId); json.put("user_favorite", favorite); return json.toString(); }