List of usage examples for org.json.simple JSONObject putAll
void putAll(Map<? extends K, ? extends V> m);
From source file:edu.vt.vbi.patric.portlets.ExperimentListPortlet.java
@SuppressWarnings("unchecked") public void serveResource(ResourceRequest request, ResourceResponse response) throws PortletException, IOException { String sraction = request.getParameter("sraction"); if (sraction != null && sraction.equals("save_params")) { Map<String, String> key = new HashMap<>(); String genomeId = request.getParameter("genomeId"); String taxonId = ""; String cType = request.getParameter("context_type"); String cId = request.getParameter("context_id"); if (cType != null && cId != null && cType.equals("taxon") && !cId.equals("")) { taxonId = cId;//from w w w.jav a 2 s.c om } String keyword = request.getParameter("keyword"); String state = request.getParameter("state"); String ncbi_taxon_id = request.getParameter("ncbi_taxon_id"); if (genomeId != null && !genomeId.equalsIgnoreCase("")) { key.put("genomeId", genomeId); } if (!taxonId.equalsIgnoreCase("")) { key.put("taxonId", taxonId); } if (keyword != null) { key.put("keyword", keyword.trim()); } if (ncbi_taxon_id != null) { key.put("ncbi_taxon_id", ncbi_taxon_id); } if (state != null) { key.put("state", state); } long pk = (new Random()).nextLong(); SessionHandler.getInstance().set(SessionHandler.PREFIX + pk, jsonWriter.writeValueAsString(key)); PrintWriter writer = response.getWriter(); writer.write("" + pk); writer.close(); } else { String need = request.getParameter("need"); JSONObject jsonResult = new JSONObject(); switch (need) { case "0": { // Experiments String pk = request.getParameter("pk"); Map data = processExperimentTab(request); Map<String, String> key = (Map) data.get("key"); int numFound = (Integer) data.get("numFound"); List<Map> experiments = (List<Map>) data.get("experiments"); JSONArray docs = new JSONArray(); for (Map item : experiments) { JSONObject doc = new JSONObject(); doc.putAll(item); docs.add(doc); } if (data.containsKey("facets")) { JSONObject facets = FacetHelper.formatFacetTree((Map) data.get("facets")); key.put("facets", facets.toJSONString()); SessionHandler.getInstance().set(SessionHandler.PREFIX + pk, jsonWriter.writeValueAsString(key)); } jsonResult.put("results", docs); jsonResult.put("total", numFound); response.setContentType("application/json"); PrintWriter writer = response.getWriter(); writer.write(jsonResult.toString()); writer.close(); break; } case "1": { // Comparisons Map data = processComparisonTab(request); int numFound = (Integer) data.get("numFound"); List<Map> comparisons = (List<Map>) data.get("comparisons"); JSONArray docs = new JSONArray(); for (Map item : comparisons) { JSONObject doc = new JSONObject(); doc.putAll(item); docs.add(doc); } // key.put("keyword", orig_keyword); jsonResult.put("results", docs); jsonResult.put("total", numFound); response.setContentType("application/json"); PrintWriter writer = response.getWriter(); jsonResult.writeJSONString(writer); writer.close(); break; } case "tree": { String pk = request.getParameter("pk"); Map<String, String> key = jsonReader .readValue(SessionHandler.getInstance().get(SessionHandler.PREFIX + pk)); String state; if (key.containsKey("state")) { state = key.get("state"); } else { state = request.getParameter("state"); } key.put("state", state); SessionHandler.getInstance().set(SessionHandler.PREFIX + pk, jsonWriter.writeValueAsString(key)); JSONArray tree = new JSONArray(); try { if (key.containsKey("facets") && !key.get("facets").equals("{}")) { JSONObject facet_fields = (JSONObject) new JSONParser().parse(key.get("facets")); DataApiHandler dataApi = new DataApiHandler(request); tree = FacetHelper.processStateAndTree(dataApi, SolrCore.TRANSCRIPTOMICS_EXPERIMENT, key, need, facet_fields, key.get("facet"), state, null, 4); } } catch (ParseException e) { LOGGER.error(e.getMessage(), e); } response.setContentType("application/json"); PrintWriter writer = response.getWriter(); tree.writeJSONString(writer); writer.close(); break; } case "download": { List<String> tableHeader = new ArrayList<>(); List<String> tableField = new ArrayList<>(); JSONArray tableSource = new JSONArray(); String fileName = "Transcriptomics"; String fileFormat = request.getParameter("fileformat"); String aT = request.getParameter("aT"); switch (aT) { case "0": { // experiments Map data = processExperimentTab(request); List<Map> experiments = (List<Map>) data.get("experiments"); for (Map item : experiments) { JSONObject doc = new JSONObject(); doc.putAll(item); tableSource.add(doc); } tableHeader.addAll(DownloadHelper.getHeaderForTranscriptomicsExperiment()); tableField.addAll(DownloadHelper.getFieldsForTranscriptomicsExperiment()); break; } case "1": { // comparisons Map data = processComparisonTab(request); List<Map> comparisons = (List<Map>) data.get("comparisons"); for (Map item : comparisons) { JSONObject doc = new JSONObject(); doc.putAll(item); tableSource.add(doc); } tableHeader.addAll(DownloadHelper.getHeaderForTranscriptomicsComparison()); tableField.addAll(DownloadHelper.getFieldsForTranscriptomicsComparison()); break; } } ExcelHelper excel = new ExcelHelper("xssf", tableHeader, tableField, tableSource); excel.buildSpreadsheet(); if (fileFormat.equalsIgnoreCase("xlsx")) { response.setContentType("application/octetstream"); response.addProperty("Content-Disposition", "attachment; filename=\"" + fileName + "." + fileFormat + "\""); excel.writeSpreadsheettoBrowser(response.getPortletOutputStream()); } else if (fileFormat.equalsIgnoreCase("txt")) { response.setContentType("application/octetstream"); response.addProperty("Content-Disposition", "attachment; filename=\"" + fileName + "." + fileFormat + "\""); response.getPortletOutputStream().write(excel.writeToTextFile().getBytes()); } break; } } } }
From source file:de.dailab.plistacontest.client.ContestHandlerOfflineCheating.java
/** * Method to handle incoming messages from the server. * /*ww w . ja v a 2 s . co m*/ * @param messageType * the messageType of the incoming contest server message. * @param properties * * @param entities * @return the response to the contest server */ @SuppressWarnings("unchecked") private String handleIdomaarMessage(final String messageType, final String properties, final String entities) { // write all data from the server to a file // logger.info(messageType + "\t" + properties + "\t" + entities); // create an jSON object from the String final JSONObject jOP = (JSONObject) JSONValue.parse(properties); final JSONObject jOE = (JSONObject) JSONValue.parse(entities); // merge the different jsonObjects and correct missing itemIDs jOP.putAll(jOE); Object itemID = jOP.get("itemID"); if (itemID == null) { jOP.put("itemID", 0); } // define a response object String response = null; if ("impression".equalsIgnoreCase(messageType)) { // parse the type of the event final RecommenderItem item = RecommenderItem.parseEventNotification(jOP.toJSONString()); final String eventNotificationType = messageType; // impression refers to articles read by the user if ("impression".equalsIgnoreCase(eventNotificationType)) { // we mark this information in the article table if (item.getItemID() != null) { response = "handle impression eventNotification successful"; boolean recommendationExpected = false; if (properties.contains("\"event_type\": \"recommendation_request\"")) { recommendationExpected = true; } if (recommendationExpected) { List<Long> suggestedItemIDs = recommenderItemTable.getFutureItems(item.getTimeStamp(), item.getDomainID(), item.getUserID()); response = "{" + "\"recs\": {" + "\"ints\": {" + "\"3\": " + suggestedItemIDs + "}" + "}}"; } } // click refers to recommendations clicked by the user } else if ("click".equalsIgnoreCase(eventNotificationType)) { // we mark this information in the article table if (item.getItemID() != null) { response = "handle impression eventNotification successful"; } response = "handle click eventNotification successful"; } else { System.out.println("unknown event-type: " + eventNotificationType + " (message ignored)"); } } else if ("error_notification".equalsIgnoreCase(messageType)) { System.out.println("error-notification: " + jOP.toString() + jOE.toJSONString()); } else { System.out.println("unknown MessageType: " + messageType); // Error handling logger.info(jOP.toString() + jOE.toJSONString()); // this.contestRecommender.error(jObj.toString()); } return response; }
From source file:edu.vt.vbi.patric.proteinfamily.FIGfamData.java
@SuppressWarnings("unchecked") public void getGenomeDetails(ResourceRequest request, PrintWriter writer) throws IOException { String cType = request.getParameter("context_type"); String cId = request.getParameter("context_id"); String keyword = ""; if (cType != null && cType.equals("taxon") && cId != null && !cId.equals("")) { keyword = "patric_cds:[1 TO *] AND taxon_lineage_ids:" + cId; } else if (request.getParameter("keyword") != null) { keyword = request.getParameter("keyword"); }/*from w w w . ja v a 2s . c o m*/ String fields = request.getParameter("fields"); DataApiHandler dataApi = new DataApiHandler(request); SolrQuery query = new SolrQuery(keyword); if (fields != null && !fields.equals("")) { query.addField(fields); } query.setRows(DataApiHandler.MAX_ROWS).addSort("genome_name", SolrQuery.ORDER.asc); String pk = request.getParameter("param_key"); Map<String, String> key = null; if (pk != null) { key = jsonReader.readValue(SessionHandler.getInstance().get(SessionHandler.PREFIX + pk)); } if (key != null && key.containsKey("genomeIds") && !key.get("genomeIds").equals("")) { query.addFilterQuery("genome_id:(" + key.get("genomeIds").replaceAll(",", " OR ") + ")"); } LOGGER.trace("getGenomeDetails(): [{}] {}", SolrCore.GENOME.getSolrCoreName(), query); String apiResponse = dataApi.solrQuery(SolrCore.GENOME, query); Map resp = jsonReader.readValue(apiResponse); Map respBody = (Map) resp.get("response"); int numFound = (Integer) respBody.get("numFound"); List<Map> sdl = (List<Map>) respBody.get("docs"); JSONArray docs = new JSONArray(); for (Map doc : sdl) { JSONObject item = new JSONObject(); item.putAll(doc); docs.add(item); } JSONObject jsonResult = new JSONObject(); jsonResult.put("results", docs); jsonResult.put("total", numFound); jsonResult.writeJSONString(writer); }
From source file:net.duckling.ddl.web.controller.team.ConfigTeamController.java
private void uploadMailListCommon(String fileName, InputStream in, HttpServletResponse response) throws IOException { String fileType = fileName.substring(fileName.indexOf('.') + 1); List<Map<String, String>> list = EmailAddressFileAnalysisUtil.getContactsFromStream(in, fileType.toUpperCase());/* www . j a v a 2 s . com*/ JSONArray jsonList = new JSONArray(); JSONObject result = new JSONObject(); if (null == list) { result.put("success", false); } else { for (int i = 0; i < list.size(); i++) { Map<String, String> map = list.get(i); map.put("index", String.valueOf(i)); JSONObject jsonMap = new JSONObject(); jsonMap.putAll(map); jsonList.add(jsonMap); } result.put("success", true); result.put("list", jsonList); } in.close(); response.setStatus(HttpServletResponse.SC_OK); JsonUtil.writeJSONObject(response, result); }
From source file:com.tresys.jalop.utils.jnltest.PublisherImpl.java
/** * Write status information about a record out to disk. * @param lri The {@link LocalRecordInfo} object output stats for. * @return <code>true</code> If the data was successfully written out. * <code>false</code> otherwise. *//*from w w w . j av a 2 s .c o m*/ @SuppressWarnings("unchecked") final boolean dumpStatus(final String serialId, final Map<String, String> statusMap) { final JSONParser p = new JSONParser(); JSONObject status; File statusFile; BufferedOutputStream w; final File serialDir = new File(this.inputRoot, SID_FORMATER.format(Long.valueOf(serialId))); try { statusFile = new File(serialDir, STATUS_FILENAME); if (!statusFile.exists()) { if (LOGGER.isInfoEnabled()) { LOGGER.info("The '" + STATUS_FILENAME + "' file does not exist so creating it."); } statusFile.createNewFile(); status = new JSONObject(); } else { status = (JSONObject) p.parse(new FileReader(statusFile)); } status.putAll(statusMap); w = new BufferedOutputStream(new FileOutputStream(statusFile)); w.write(status.toJSONString().getBytes("utf-8")); w.close(); } catch (final FileNotFoundException e) { LOGGER.error("Failed to open status file for writing:" + e.getMessage()); return false; } catch (final ParseException e) { if (LOGGER.isInfoEnabled()) { LOGGER.info("'" + STATUS_FILENAME + "' file"); } status = new JSONObject(); } catch (final UnsupportedEncodingException e) { LOGGER.error("cannot find UTF-8 encoder?"); return false; } catch (final IOException e) { LOGGER.error("failed to write to the status file, aborting"); return false; } return true; }
From source file:com.cabserver.handler.Driver.java
@GET @Path("locations") @Produces(MediaType.TEXT_HTML)/*from w ww . j a va 2 s . com*/ public Response getDriversLocation() { // String data = ""; JSONArray jsonArray = null; try { // log.info("Inside Driver >> getDriversLocation"); if (CacheBuilder.driversDataMap.size() > 0) { Set<Long> keys = CacheBuilder.driversDataMap.keySet(); jsonArray = new JSONArray(); for (long key : keys) { try { DriverMaster dm = CacheBuilder.driversDataMap.get(key); long currentTime = MyUtil.getCalanderFromDateStr(MyUtil.getCurrentDateFormattedString()) .getTimeInMillis(); long driverLastLocUpdateTime = dm.getLocationUpdateTime().getTime(); long driverInActiveTimeDiff = currentTime - driverLastLocUpdateTime; if (driverInActiveTimeDiff < Long .parseLong(ConfigDetails.constants.get("DRIVER_MAP_ICON_DISABLE_TIME"))) { HashMap<String, String> map = new HashMap<String, String>(); map.put("driverId", dm.getDriverId() + ""); map.put("firstName", dm.getFirstName()); map.put("phoneNumber", dm.getPhoneNumber()); map.put("driverStatus", dm.getDriverStatus()); map.put("currAddr", dm.getCurrAddr()); map.put("currLongt", dm.getCurrLongt()); map.put("currLat", dm.getCurrLat()); map.put("bookingId", dm.getBookingId()); map.put("code", "200"); map.put("msg", "Driver details fetched."); JSONObject obj = new JSONObject(); obj.putAll(map); jsonArray.add(obj); } else { log.info("getDriversLocation >> DriverId= " + dm.getDriverId() + " is Inactive"); } } catch (Exception e) { } } } else { HashMap<String, String> map = new HashMap<String, String>(); map.put("code", ConfigDetails.constants.get("BOOKING_FAILED_CODE")); map.put("msg", "No drivers are provisioned."); JSONObject obj = new JSONObject(); obj.putAll(map); jsonArray.add(obj); } } catch (Exception e) { e.printStackTrace(); } if (jsonArray.size() < 1) { log.info("getDriversLocation >> Bookings Error. HTTP bookingStatus code is " + ConfigDetails.constants.get("BOOKING_FAILED_CODE") + "."); HashMap<String, String> map = new HashMap<String, String>(); map.put("code", ConfigDetails.constants.get("BOOKING_FAILED_CODE")); map.put("msg", "Server Error."); JSONObject obj = new JSONObject(); obj.putAll(map); jsonArray.add(obj); return Response.status(200).entity(jsonArray.toJSONString()).build(); } else { return Response.status(200).entity(jsonArray.toJSONString()).build(); } }
From source file:hoot.services.controllers.osm.MapResource.java
@GET @Path("/tags") @Produces(MediaType.APPLICATION_JSON)/*from ww w .j ava 2 s .com*/ public Response getTags(@QueryParam("mapid") String mapId) { JSONObject json = new JSONObject(); try (Connection connection = DbUtils.createConnection()) { if (!StringUtils.isEmpty(mapId)) { long mapIdNum = -2; try { mapIdNum = Long.parseLong(mapId); } catch (NumberFormatException ignored) { // a map name string could also be passed in here } if (mapIdNum != -1) // not OSM API db { mapIdNum = ModelDaoUtils.getRecordIdForInputString(mapId, connection, maps, maps.id, maps.displayName); logger.info("Retrieving map tags for map with ID: {} ...", mapIdNum); try { java.util.Map<String, String> tags = DbUtils.getMapsTableTags(mapIdNum, connection); if (tags != null) { logger.debug(tags.toString()); } json.putAll(tags); Object oInput1 = json.get("input1"); if (oInput1 != null) { String dispName = DbUtils.getDisplayNameById(connection, Long.valueOf(oInput1.toString())); json.put("input1Name", dispName); } Object oInput2 = json.get("input2"); if (oInput2 != null) { String dispName = DbUtils.getDisplayNameById(connection, Long.valueOf(oInput2.toString())); json.put("input2Name", dispName); } } catch (Exception e) { throw new RuntimeException("Error getting map tags. :" + e.getMessage(), e); } } } } catch (Exception e) { handleError(e, mapId, ""); } return Response.ok(json.toString()).build(); }
From source file:com.cabserver.handler.Admin.java
String jsonCreater(Map mp) { JSONObject obj = new JSONObject(); // obj.put("code", "200"); // obj.put("msg", "Login Succesful."); obj.putAll(mp); // log.info("Formed JSON = "+ obj.toJSONString()); return obj.toJSONString(); }
From source file:com.pari.nm.modules.jobs.CompareDeviceConfigJob.java
public void processGearmanJob(Set<Integer> deviceIds, Map<Integer, Map<String, Object>> perDeviceInputMap, JSONObject configObj) throws Exception { Gearman gearman = Gearman.createGearman(); GearmanServer server = gearman.createGearmanServer("localhost", 4730); GearmanClient client = gearman.createGearmanClient(); client.addServer(server);/*from www. j a v a2s . com*/ ExecutorService executor = Executors.newFixedThreadPool(100); List<Future<JSONObject>> list = new ArrayList<Future<JSONObject>>(); List<String> definedOSTypes = null; boolean isApplicableToAllDevices = true; try { definedOSTypes = GoldenConfigDBHelper.getDefinedOSTypes(); // if (definedOSTypes == null || definedOSTypes.size() == 0) // { // logMsg("Global definations are not defined for any OS types, hence exiting."); // throw new Exception("Global definations are not defined for any OS types."); // } } catch (Exception e1) { logger.error("Unable to load defined OS Types" + e1); gearman.shutdown(); executor.shutdown(); throw new Exception("Unable to load global OS definitions or NO OS definitions are added"); } try { for (Integer deviceId : deviceIds) { NetworkNode node = NetworkNodeCache.getInstance().getNodeByID(deviceId); if (node != null) { String runConfig = node.getRunningConfig(); String osName = node.getVersion().getOsTypeDetails().getOsName(); if (runConfig == null || runConfig.trim().isEmpty()) { logMsg(CspcXMLUtils.logMsgInStdFormat("", node.getNodeId(), node.getIpAddr().toString(), System.currentTimeMillis(), " Running Config has no Data . Skipping for this Device ." + node.getIpAddr().toString())); continue; } configObj.put("config", runConfig); String ipAddress = NetworkNodeCache.getInstance().getNodeByID(deviceId).getIpAddr().toString(); String hostName = NetworkNodeCache.getInstance().getNodeByID(deviceId).getNodeName(); configObj.put("DeviceIp", ipAddress); configObj.put("DeviceId", deviceId); configObj.put("HostName", hostName); List<String> reportType = (List<String>) configObj.get("type"); if (golbalDefinitionPerOS.get(osName) != null && !golbalDefinitionPerOS.get(osName).isEmpty()) { configObj.putAll(golbalDefinitionPerOS.get(osName)); } String template = configObj.get("template").toString(); if (perDeviceInputMap.get(deviceId) != null) { template = replacePerDeviceInput(template, perDeviceInputMap.get(deviceId)); } configObj.put("template", template); boolean isAdded = GoldenConfigManagerImpl.getInstance().addDeviceConfigResult(jobName, jobId, jobRunId, deviceId, reportType, null, template, runConfig); if (isAdded) { logger.info("Added template and running config for this device " + deviceId); } logMsg(CspcXMLUtils.logMsgInStdFormat("", (int) deviceId, ipAddress, System.currentTimeMillis(), "Started - Compared Device Configuration for device- " + ipAddress)); JSONObject newConfObject = new JSONObject(configObj); Future<JSONObject> future = executor.submit(new CompareConfigJobSubmit(client, newConfObject)); newConfObject = null; list.add(future); } } jobState = isApplicableToAllDevices ? JobStatus.SUCCESS : JobStatus.FAILED; for (Future<JSONObject> fut : list) { try { JSONObject obj = fut.get(); int code = Integer.parseInt(obj.get("code").toString()); // int deviceId = Integer.parseInt((String) // obj.get("DeviceId")); long deviceId = (long) obj.get("DeviceId"); String ipAddress = obj.get("DeviceIp").toString(); String reportName = obj.get("reportName").toString(); if (code == 10) { Map<String, String> configResult = (Map<String, String>) obj.get("output"); GoldenConfigManagerImpl.getInstance().updateDeviceConfigResult(jobName, jobId, jobRunId, (int) deviceId, configResult, reportName); logMsg(CspcXMLUtils.logMsgInStdFormat("", (int) deviceId, ipAddress, System.currentTimeMillis(), "Completed - Compared Device Configuration for device- " + ipAddress)); } else if (code == -10) { String msg = obj.get("msg").toString(); logMsg(CspcXMLUtils.logMsgInStdFormat("", (int) deviceId, ipAddress, System.currentTimeMillis(), msg + ipAddress)); } else if (code == -20) { String msg = obj.get("msg").toString(); logMsg(CspcXMLUtils.logMsgInStdFormat("", (int) deviceId, ipAddress, System.currentTimeMillis(), msg + ipAddress)); jobState = JobStatus.FAILED; } } catch (Exception e) { logger.error("Exception while getting Object from Worker.", e); } } } catch (Exception ex) { logger.error("Unable to load Process Compare Job" + ex); } finally { executor.shutdown(); gearman.shutdown(); if (templateBundleExtract != null && templateBundleExtract.exists()) { templateBundleExtract.delete(); } } jobStatus.setState(jobId, JobStageConstants.DefaultJobStages.COMPLETED, 0, "Execution Completed."); context.setResult("Completed"); JobRun.logJobCompletionStatus(jobId, jobRunId, ((jobState == JobStatus.SUCCESS) ? true : false)); }
From source file:org.alfresco.module.org_alfresco_module_rm.jscript.app.JSONConversionComponent.java
/** * Helper method to set the RM node values * * @param nodeRef node reference * @param useShortQName indicates whether the short QName are used or not * @return {@link JSONObject} JSON object containing values *//*ww w. j a v a2s .c om*/ @SuppressWarnings("unchecked") private JSONObject setRmNodeValues(final NodeRef nodeRef, final boolean useShortQName) { JSONObject rmNodeValues = new JSONObject(); // UI convenience type rmNodeValues.put("uiType", getUIType(nodeRef)); // Get the 'kind' of the file plan component FilePlanComponentKind kind = filePlanService.getFilePlanComponentKind(nodeRef); rmNodeValues.put("kind", kind.toString()); // set the primary parent node reference ChildAssociationRef assoc = nodeService.getPrimaryParent(nodeRef); if (assoc != null) { rmNodeValues.put("primaryParentNodeRef", assoc.getParentRef().toString()); } Map<String, Object> values = AuthenticationUtil.runAsSystem(new RunAsWork<Map<String, Object>>() { public Map<String, Object> doWork() throws Exception { Map<String, Object> result = new HashMap<String, Object>(); // File plan node reference NodeRef filePlan = filePlanService.getFilePlan(nodeRef); result.put("filePlan", filePlan.toString()); // Unfiled container node reference NodeRef unfiledRecordContainer = filePlanService.getUnfiledContainer(filePlan); if (unfiledRecordContainer != null) { result.put("unfiledRecordContainer", unfiledRecordContainer.toString()); result.put("properties", propertiesToJSON(unfiledRecordContainer, nodeService.getProperties(unfiledRecordContainer), useShortQName)); QName type = fileFolderService.getFileInfo(unfiledRecordContainer).getType(); result.put("type", useShortQName ? type.toPrefixString(namespaceService) : type.toString()); } return result; } }); rmNodeValues.putAll(values); // Set the indicators array setIndicators(rmNodeValues, nodeRef); // Set the actions array setActions(rmNodeValues, nodeRef); return rmNodeValues; }