Java Code Examples for net.sf.json.JSONArray#add()
The following examples show how to use
net.sf.json.JSONArray#add() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ChartController.java From JavaWeb with Apache License 2.0 | 7 votes |
@OnOpen public void onOpen(Session session,@PathParam("username") String username) { try{ client.add(session); user.put(URLEncoder.encode(username, "UTF-8"),URLEncoder.encode(username, "UTF-8")); JSONObject jo = new JSONObject(); JSONArray ja = new JSONArray(); //获得在线用户列表 Set<String> key = user.keySet(); for (String u : key) { ja.add(u); } jo.put("onlineUser", ja); session.getBasicRemote().sendText(jo.toString()); }catch(Exception e){ //do nothing } }
Example 2
Source File: CatalogRestTest.java From mobi with GNU Affero General Public License v3.0 | 6 votes |
@Test public void updateInProgressCommitWithErrorTest() { // Setup: JSONArray adds = new JSONArray(); adds.add(new JSONObject().element("@id", "http://example.com/add").element("@type", new JSONArray().element("http://example.com/Add"))); FormDataMultiPart fd = new FormDataMultiPart(); fd.field("additions", adds.toString()); doThrow(new MobiException()).when(catalogManager).updateInProgressCommit(eq(vf.createIRI(LOCAL_IRI)), eq(vf.createIRI(RECORD_IRI)), any(User.class), any(Model.class), any(Model.class)); Response response = target().path("catalogs/" + encode(LOCAL_IRI) + "/records/" + encode(RECORD_IRI) + "/in-progress-commit") .request().put(Entity.entity(fd, MediaType.MULTIPART_FORM_DATA)); assertEquals(response.getStatus(), 500); doThrow(new IllegalStateException()).when(catalogManager).updateInProgressCommit(eq(vf.createIRI(LOCAL_IRI)), eq(vf.createIRI(RECORD_IRI)), any(User.class), any(Model.class), any(Model.class)); response = target().path("catalogs/" + encode(LOCAL_IRI) + "/records/" + encode(RECORD_IRI) + "/in-progress-commit") .request().put(Entity.entity(fd, MediaType.MULTIPART_FORM_DATA)); assertEquals(response.getStatus(), 500); }
Example 3
Source File: CatalogRestTest.java From mobi with GNU Affero General Public License v3.0 | 6 votes |
@Test public void updateInProgressCommitTest() { // Setup: JSONArray adds = new JSONArray(); adds.add(new JSONObject().element("@id", "http://example.com/add").element("@type", new JSONArray().element("http://example.com/Add"))); JSONArray deletes = new JSONArray(); deletes.add(new JSONObject().element("@id", "http://example.com/delete").element("@type", new JSONArray().element("http://example.com/Delete"))); FormDataMultiPart fd = new FormDataMultiPart(); fd.field("additions", adds.toString()); fd.field("deletions", deletes.toString()); Response response = target().path("catalogs/" + encode(LOCAL_IRI) + "/records/" + encode(RECORD_IRI) + "/in-progress-commit") .request().put(Entity.entity(fd, MediaType.MULTIPART_FORM_DATA)); assertEquals(response.getStatus(), 200); verify(bNodeService, atLeastOnce()).deskolemize(any(Model.class)); verify(catalogManager).updateInProgressCommit(eq(vf.createIRI(LOCAL_IRI)), eq(vf.createIRI(RECORD_IRI)), any(User.class), any(Model.class), any(Model.class)); }
Example 4
Source File: QueryFormulateServiceImpl.java From Criteria2Query with Apache License 2.0 | 6 votes |
/** * translate a list of CdmCriteria to JSON * */ public JSONArray formulateInclusionRules(List<CdmCriteria> clist) { JSONArray json_arr = new JSONArray(); for (int i = 0; i < clist.size(); i++) { JSONObject jo = new JSONObject(); CdmCriteria cdmc = clist.get(i); System.out.println("is include?"+cdmc.isIncluded()); String inctag=cdmc.isIncluded()?"[INC]":"[EXC]"; jo.accumulate("name", inctag+cdmc.getText()); jo.accumulate("description", cdmc.getDesc()); JSONObject expression = formulateOneCdmCriteria(cdmc); System.out.println(expression); jo.accumulate("expression", expression); json_arr.add(jo); } return json_arr; }
Example 5
Source File: CgReportQueryParamUtil.java From jeecg with Apache License 2.0 | 6 votes |
/** * 将结果集转化为列表json格式(不含分页信息) * @param result 结果集 * @param size 总大小 * @return 处理好的json格式 */ public static String getJson(List<Map<String, Object>> result){ JSONArray rows = new JSONArray(); for(Map m:result){ JSONObject item = new JSONObject(); Iterator it =m.keySet().iterator(); while(it.hasNext()){ String key = (String) it.next(); String value =String.valueOf(m.get(key)); key = key.toLowerCase(); if(key.contains("time")||key.contains("date")){ value = datatimeFormat(value); } item.put(key,value ); } rows.add(item); } return rows.toString(); }
Example 6
Source File: GlobalConfigurationServiceTest.java From sonar-quality-gates-plugin with MIT License | 5 votes |
@Test public void testGetGlobalConfigsArrayWhenObject() { jsonArray = new JSONArray(); doReturn(jsonArray).when(spyGlobalConfigurationService).createJsonArrayFromObject(JSONObject.fromObject(globalDataConfigs)); String objectString = "{\"name\":\"Sonar\",\"url\":\"http://localhost:9000\",\"account\":\"admin\",\"password\":\"admin\"}"; globalDataConfigs = JSONSerializer.toJSON(objectString); jsonArray.add(globalDataConfigs); assertEquals(jsonArray, spyGlobalConfigurationService.getGlobalConfigsArray(globalDataConfigs)); }
Example 7
Source File: QueryFormulateServiceImpl.java From Criteria2Query with Apache License 2.0 | 5 votes |
public JSONArray defaultInitialEvent() { JSONArray jacriterialist = new JSONArray(); JSONObject jo = new JSONObject(); // JSONObject jnull=new JSONObject(); JSONObject jvo = new JSONObject(); jvo.accumulate("VisitSourceConcept", null); jvo.accumulate("First", null); jo.accumulate("VisitOccurrence", jvo); jacriterialist.add(jo); return jacriterialist; }
Example 8
Source File: CgformTransController.java From jeewx with Apache License 2.0 | 5 votes |
public static String getJson(List<String> result, Integer size) { JSONObject main = new JSONObject(); JSONArray rows = new JSONArray(); main.put("total", size); for (String m : result) { JSONObject item = new JSONObject(); item.put("id", m); rows.add(item); } main.put("rows", rows); return main.toString(); }
Example 9
Source File: UserTest.java From jmeter-bzm-plugins with Apache License 2.0 | 5 votes |
@org.junit.Test public void testFlow() throws Exception { StatusNotifierCallbackTest.StatusNotifierCallbackImpl notifier = new StatusNotifierCallbackTest.StatusNotifierCallbackImpl(); BlazeMeterReport report = new BlazeMeterReport(); BlazeMeterHttpUtilsEmul emul = new BlazeMeterHttpUtilsEmul(notifier, "test_address", "test_data_address", report); User user = new User(emul); emul.addEmul(new JSONObject()); user.ping(); JSONObject acc = new JSONObject(); acc.put("id", "accountId"); acc.put("name", "accountName"); JSONArray result = new JSONArray(); result.add(acc); result.add(acc); JSONObject response = new JSONObject(); response.put("result", result); emul.addEmul(response); List<Account> accounts = user.getAccounts(); assertEquals(2, accounts.size()); for (Account account : accounts) { assertEquals("accountId", account.getId()); assertEquals("accountName", account.getName()); } }
Example 10
Source File: CatalogRestTest.java From mobi with GNU Affero General Public License v3.0 | 5 votes |
@Test public void mergeForUserThatDoesNotExistTest() { // Setup: when(engineManager.retrieveUser(anyString())).thenReturn(Optional.empty()); JSONArray adds = new JSONArray(); adds.add(new JSONObject().element("@id", "http://example.com/add").element("@type", new JSONArray().element("http://example.com/Add"))); FormDataMultiPart fd = new FormDataMultiPart(); fd.field("additions", adds.toString()); Response response = target().path("catalogs/" + encode(LOCAL_IRI) + "/records/" + encode(RECORD_IRI) + "/branches/" + encode(BRANCH_IRI) + "/conflicts/resolution") .queryParam("targetId", BRANCH_IRI).request().post(Entity.entity(fd, MediaType.MULTIPART_FORM_DATA)); assertEquals(response.getStatus(), 401); }
Example 11
Source File: FileShareServlet.java From weiyunpan with Apache License 2.0 | 5 votes |
/** * 分享文件操作 * * @param request * @param response * @throws IOException * @throws ServletException */ public void shareFile(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { PrintWriter out = response.getWriter(); // 获取用户id以及文件id HttpSession session = request.getSession(); String username = session.getAttribute("username").toString(); IUserService userService = new UserServiceImpl(); Integer userid = userService.getUserIdByUsername(username); int fileid = Integer.parseInt(request.getParameter("fileid")); // 根据文件id查出文件信息 IFileInfoService fileInfoService = new FileInfoServiceImpl(); FileInfo fileInfo = fileInfoService.findSimpleFileByid(fileid); fileInfo.setIsshare(2); // 1代表未分享,2代表已分享 // 更新分享文件信息 IFileShareService fileShareService = new FileShareServiceImpl(); boolean isShare = fileShareService.shareFile(fileInfo, userid.intValue(), fileid); // json解析 JSONObject jsonObject = new JSONObject(); JSONArray jsonArray = new JSONArray(); if (isShare) { // 分享成功 System.out.println("分享成功"); // 如果已经收藏,则不能再次收藏 jsonObject.put("isshare", "分享成功!"); jsonArray.add(jsonObject); System.out.println(jsonArray); out.write(jsonArray.toString()); /*request.getRequestDispatcher("RedirectBase.do?method=panForward") .forward(request, response);*/ } }
Example 12
Source File: DelimitedRest.java From mobi with GNU Affero General Public License v3.0 | 5 votes |
/** * Converts the specified number rows of a CSV file into JSON and returns * them as a String. * * @param input the CSV file to convert into JSON * @param numRows the number of rows from the CSV file to convert * @param separator a character with the character to separate the columns by * @return a string with the JSON of the CSV rows * @throws IOException csv file could not be read */ private String convertCSVRows(File input, int numRows, char separator) throws IOException { Charset charset = getCharset(Files.readAllBytes(input.toPath())); try (CSVReader reader = new CSVReader(new InputStreamReader(new FileInputStream(input), charset.name()), separator)) { List<String[]> csvRows = reader.readAll(); JSONArray returnRows = new JSONArray(); for (int i = 0; i <= numRows && i < csvRows.size(); i++) { returnRows.add(i, csvRows.get(i)); } return returnRows.toString(); } }
Example 13
Source File: JSONConverter.java From jmeter-bzm-plugins with Apache License 2.0 | 5 votes |
public static JSONArray getLabels(List<SampleResult> accumulatedValues, List<SampleResult> intervalValues) { JSONArray jsonArray = new JSONArray(); jsonArray.add(caclucateMetrics(accumulatedValues, intervalValues, SUMMARY_LABEL)); Map<String, List<SampleResult>> sortedAccumulatedSamples = sortSamplesByLabel(accumulatedValues); Map<String, List<SampleResult>> sortedIntervalSamples = sortSamplesByLabel(intervalValues); for (String label : sortedIntervalSamples.keySet()) { jsonArray.add(caclucateMetrics(sortedAccumulatedSamples.get(label), sortedIntervalSamples.get(label), label)); } return jsonArray; }
Example 14
Source File: JiraClientSvcImpl.java From jira-ext-plugin with Apache License 2.0 | 5 votes |
@Override public void updateMultiSelectField(String jiraIssueKey, String jiraFieldName, String... values) throws JiraException { logger.fine("Update ticket: " + jiraIssueKey + " field name: " + jiraFieldName + " with values " + values); JiraClient client = newJiraClient(); Issue issue = client.getIssue(jiraIssueKey); Validate.notNull(issue); RestClient restClient = client.getRestClient(); try { JSONObject payload = new JSONObject(); JSONObject fields = new JSONObject(); JSONArray valueList = new JSONArray(); for (String value : values) { JSONObject shittyApi = new JSONObject(); shittyApi.put("value", value); valueList.add(shittyApi); } fields.put(jiraFieldName, valueList); payload.put("fields", fields); restClient.put("/rest/api/latest/issue/" + jiraIssueKey, payload); } catch (Throwable t) { String msg = "Error updating multi-select issue field"; logger.log(Level.WARNING, msg, t); throw new JiraException(msg, t); } }
Example 15
Source File: LoginController.java From jeecg with Apache License 2.0 | 5 votes |
/** * AdminLTE返回:用户权限菜单 */ @RequestMapping(params = "getPrimaryMenuForAdminlte", method = {RequestMethod.GET, RequestMethod.POST}) @ResponseBody public AjaxJson getPrimaryMenuForAdminlte(String functionId, HttpServletRequest request) { AjaxJson j = new AjaxJson(); try { //List<TSFunction> functions = this.systemService.findByProperty(TSFunction.class, "TSFunction.id", functionId); String userid = ResourceUtil.getSessionUser().getId(); List<TSFunction> functions = userService.getSubFunctionList(userid, functionId); JSONArray jsonArray = new JSONArray(); if(functions != null && functions.size() > 0) { for (TSFunction function : functions) { JSONObject jsonObjectInfo = new JSONObject(); jsonObjectInfo.put("id", function.getId()); jsonObjectInfo.put("text",oConvertUtils.getString(MutiLangUtil.getLang(function.getFunctionName()))); jsonObjectInfo.put("url",oConvertUtils.getString(function.getFunctionUrl())); jsonObjectInfo.put("targetType", "iframe-tab"); jsonObjectInfo.put("icon", "fa " + oConvertUtils.getString(function.getFunctionIconStyle())); jsonObjectInfo.put("children", getChildOfAdminLteTree(function)); jsonArray.add(jsonObjectInfo); } } j.setObj(jsonArray); } catch (Exception e) { e.printStackTrace(); } return j; }
Example 16
Source File: WorkspaceTest.java From jmeter-bzm-plugins with Apache License 2.0 | 5 votes |
@org.junit.Test public void testFlow() throws Exception { StatusNotifierCallbackTest.StatusNotifierCallbackImpl notifier = new StatusNotifierCallbackTest.StatusNotifierCallbackImpl(); BlazeMeterHttpUtilsEmul emul = new BlazeMeterHttpUtilsEmul(notifier, "test_address", "test_data_address", new BlazeMeterReport()); JSONObject result = new JSONObject(); result.put("id", "999"); result.put("name", "NEW_PROJECT"); JSONObject response = new JSONObject(); response.put("result", result); Workspace workspace = new Workspace(emul, "888", "workspace_name"); emul.addEmul(response); Project project = workspace.createProject("NEW_PROJECT"); assertEquals("999", project.getId()); assertEquals("NEW_PROJECT", project.getName()); response.clear(); JSONArray results = new JSONArray(); results.add(result); results.add(result); response.put("result", results); emul.addEmul(response); List<Project> projects = workspace.getProjects(); assertEquals(2, projects.size()); for (Project p :projects) { assertEquals("999", p.getId()); assertEquals("NEW_PROJECT", p.getName()); } }
Example 17
Source File: ScheduleController.java From JavaWeb with Apache License 2.0 | 4 votes |
@PostMapping(value="/getSchedule",produces=MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public String getSchedule(HttpServletRequest request, HttpServletResponse response, @RequestBody JsonNode jsonNode) { JSONObject jo = new JSONObject(); final String pattern = "yyyy-MM-dd"; final String pattern2 = "MM月dd日"; try{ String getYear = jsonNode.get("year").asText(); String getMonth = jsonNode.get("month").asText(); String yearMonth = getYear+"-"+getMonth+"-"; String startDate = yearMonth+ConstantUtil.FIRST_DAY_OF_MONTH_STRING; String endDate = yearMonth+DateUtil.getLastDayOfMonth(Integer.parseInt(getYear),Integer.parseInt(getMonth)); List<String> finalList = getDateList(startDate, endDate, pattern); Map<String,String> map = new HashMap<String,String>(); map.put("startDate", finalList.get(0)); map.put("endDate", finalList.get(finalList.size()-1)); List<CompanySchedule> companyScheduleList = scheduleService.getScheduleByDate(map); JSONArray ja = new JSONArray(); for (int i = 0; i < finalList.size(); i++) { JSONObject innerjo = new JSONObject(); String date = finalList.get(i); boolean continueFlag = true; for(int j=0;j<companyScheduleList.size();j++){ String companyDate = companyScheduleList.get(j).getCompanyDate(); if(date.equals(companyDate)){ date = DateUtil.getStringDate(date, pattern, pattern2); innerjo.put("date", date); innerjo.put("scheduleType", companyScheduleList.get(j).getCompanyScheduleType()); continueFlag = false; break; } } if(continueFlag){ int weekendsFlag = DateUtil.isWeekends(date, pattern)==true?1:2; date = DateUtil.getStringDate(date, pattern, pattern2); innerjo.put("date", date); innerjo.put("scheduleType", weekendsFlag); } ja.add(innerjo); } jo.put("dateList", ja); }catch(Exception e){ jo.put("dateList", ""); } return jo.toString(); }
Example 18
Source File: PluginServiceImpl.java From TrackRay with GNU General Public License v3.0 | 4 votes |
/** * 查找WEBSOCKET插件方法 * @return */ @Override public JSONArray findWebsocketPlugins(){ WebApplicationContext context = getContext(); Map<String, WebSocketPlugin> bean = context.getBeansOfType(WebSocketPlugin.class); JSONArray arr = new JSONArray(); for (Map.Entry<String, WebSocketPlugin> entry : bean.entrySet()) { JSONObject obj = new JSONObject(); AbstractPlugin plugin = entry.getValue(); Rule rule = plugin.currentRule(); Plugin p = plugin.currentPlugin(); if (p==null || rule == null) continue; obj.put("plugin_key",entry.getKey()); JSONObject base = new JSONObject(); base.put("author",p.author()); base.put("title",p.title()); base.put("desc",p.desc()); base.put("link",p.link()); base.put("time",p.time()); obj.put("base_info",base); JSONObject rules = new JSONObject(); rules.put("sync",rule.sync()); ArrayList<String> ruleparam = new ArrayList<>(); ArrayList<String> defparam = new ArrayList<>(); ArrayList<String> descparam = new ArrayList<>(); Param[] params = rule.params(); if (!rule.defParam() && params[0].key().equals("RHOST") && params[3].key().equals("SSL")){ }else{ for (Param param : params) { ruleparam.add(param.key()); defparam.add(param.defaultValue()); descparam.add(param.desc()); } } rules.put("params",ruleparam); rules.put("def_params",defparam); rules.put("desc_params",descparam); rules.put("enable",rule.enable()); rules.put("websocket",rule.websocket()); obj.put("plugin_rule",rules); arr.add(obj); } return arr; }
Example 19
Source File: ReplyServlet.java From mytwitter with Apache License 2.0 | 4 votes |
@Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); resp.setContentType("text/html;charset=UTF-8"); String page = req.getParameter("page"); String tid = req.getParameter("tid"); List<Replyall> replys = replysDao.getAllReply(Integer.parseInt(tid), Integer.parseInt(page)); if (replys == null) { return; } JSONArray js = new JSONArray(); for (Replyall reply : replys) { Timestamp rtime = reply.getRtime(); SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日 HH:mm"); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm"); SimpleDateFormat sdf3 = new SimpleDateFormat("HH:mm"); Calendar cal = Calendar.getInstance(); int day = cal.get(Calendar.DATE); int month = cal.get(Calendar.MONTH) + 1; int year = cal.get(Calendar.YEAR); String nowyear = year + "-01-01 00:00:00"; Timestamp yeardate = Timestamp.valueOf(nowyear); String nowday = year + "-" + month + "-" + day + " 00:00:00"; Timestamp date = Timestamp.valueOf(nowday); // 此处转换为毫秒数 long millionSeconds = rtime.getTime();// 毫秒 long nowSeconds = System.currentTimeMillis(); long chazhi = nowSeconds - millionSeconds; if (chazhi < 60000) { reply.setTime("现在"); } else if (chazhi < 3600000) { long n = chazhi / 60000; reply.setTime(n + "分钟"); } else if (rtime.after(date)) { reply.setTime(sdf3.format(rtime)); } else if (rtime.after(yeardate)) { reply.setTime(sdf.format(rtime)); } else { reply.setTime(sdf2.format(rtime)); } js.add(getJsonObj(reply.getRid(), reply.getUid(), reply.getTid(), reply.getRcontent(), reply.getTime(), reply.getUname(), reply.getUrealname(), reply.getUaite(), reply.getUlogo())); } resp.getWriter().print(js.toString()); }
Example 20
Source File: TSSmsController.java From jeecg with Apache License 2.0 | 4 votes |
/** * 取得可读的消息 * * @param user * @param req * @return */ @RequestMapping(params = "getMessageList") @ResponseBody public AjaxJson getMessageList(HttpServletRequest req) { AjaxJson j = new AjaxJson(); try { j.setObj(0); List<TSSmsEntity> list = new ArrayList<TSSmsEntity>(); //1. 取得系统当前登录人ID String curUser = ResourceUtil.getSessionUser().getUserName(); //2.查询当前登录人的消息类型为"3" // //当前时间 // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // String curDate = sdf.format(new Date()); String isSend = ResourceUtil.getConfigByName("sms.tip.control"); if("1".equals(isSend)){ DataGrid dataGrid = new DataGrid(); dataGrid.setRows(20);//查出最新20条记录 CriteriaQuery cq = new CriteriaQuery(TSSmsEntity.class, dataGrid); cq.eq("esType", "3"); cq.eq("esReceiver", curUser); cq.eq("isRead", 0); cq.addOrder("esSendtime", SortDirection.desc); cq.add(); this.tSSmsService.getDataGridReturn(cq, true); // list = this.tSSmsService.getMsgsList(curUser,curDate); list = dataGrid.getResults(); //将List转换成JSON存储 JSONArray result = new JSONArray(); if(list!=null && list.size()>0){ for(int i=0;i<list.size();i++){ JSONObject jsonParts = new JSONObject(); jsonParts.put("id", list.get(i).getId()); jsonParts.put("esTitle", list.get(i).getEsTitle()); jsonParts.put("esSender", list.get(i).getEsSender()); jsonParts.put("esContent", list.get(i).getEsContent()); jsonParts.put("esSendtime", list.get(i).getEsSendtime()); jsonParts.put("esStatus", list.get(i).getEsStatus()); if(list.get(i).getEsSendtime()!=null){ SimpleDateFormat sdformat = new SimpleDateFormat("h:mm a"); jsonParts.put("esSendtimeTxt", sdformat.format(list.get(i).getEsSendtime())); } result.add(jsonParts); } j.setObj(list.size()); } Map<String,Object> attrs = new HashMap<String, Object>(); attrs.put("messageList", result); String tip = MutiLangUtil.getLang("message.tip"); attrs.put("tip", tip); String seeAll = MutiLangUtil.getLang("message.seeAll"); attrs.put("seeAll", seeAll); j.setAttributes(attrs); } } catch (Exception e) { j.setSuccess(false); } return j; }