List of usage examples for org.json.simple JSONObject putAll
void putAll(Map<? extends K, ? extends V> m);
From source file:copter.ServerConnection.java
/** * this function make a post request to server and send the copter geo info *//*from w w w. j a v a 2 s . c o m*/ public String sendCopterGeoInfoToServer(CopterGpsData gpsData) { if (gpsData == null) { return "Empty gps data!"; } String copter_unique_id = Config.getInstance().getString("copter", "unique_id"); JSONObject obj = new JSONObject(); obj.putAll(gpsData.toMap()); String postUrl = Config.getInstance().getString("main", "send_gps_data_server_url"); Map parameters = new HashMap<String, String>(); parameters.put("unique_id", copter_unique_id); parameters.put("gps_data_json", obj.toJSONString()); return postToServer(postUrl, parameters); }
From source file:cloud.google.com.windows.example.ExampleCode.java
@SuppressWarnings("unchecked") private JSONObject buildKeyMetadata(KeyPair pair) throws NoSuchAlgorithmException, InvalidKeySpecException { // Object used for storing the metadata values. JSONObject metadataValues = new JSONObject(); // Encode the public key into the required JSON format. metadataValues.putAll(jsonEncode(pair)); // Add username and email. metadataValues.put("userName", USER_NAME); metadataValues.put("email", EMAIL); // Create the date on which the new keys expire. Date now = new Date(); Date expireDate = new Date(now.getTime() + EXPIRE_TIME); // Format the date to match rfc3339. SimpleDateFormat rfc3339Format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); rfc3339Format.setTimeZone(TimeZone.getTimeZone("UTC")); String dateString = rfc3339Format.format(expireDate); // Encode the expiration date for the returned JSON dictionary. metadataValues.put("expireOn", dateString); return metadataValues; }
From source file:com.opensoc.alerts.TelemetryAlertsBolt.java
@SuppressWarnings("unchecked") public void execute(Tuple tuple) { LOG.trace("[OpenSOC] Starting to process message for alerts"); JSONObject original_message = null;/*from w w w .j a v a 2 s . co m*/ String key = null; try { key = tuple.getStringByField("key"); original_message = (JSONObject) tuple.getValueByField("message"); if (original_message == null || original_message.isEmpty()) throw new Exception("Could not parse message from byte stream"); if (key == null) throw new Exception("Key is not valid"); LOG.trace("[OpenSOC] Received tuple: " + original_message); JSONObject alerts_tag = new JSONObject(); Map<String, JSONObject> alerts_list = _adapter.alert(original_message); JSONArray uuid_list = new JSONArray(); if (alerts_list == null || alerts_list.isEmpty()) { System.out.println("[OpenSOC] No alerts detected in: " + original_message); _collector.ack(tuple); _collector.emit("message", new Values(key, original_message)); } else { for (String alert : alerts_list.keySet()) { uuid_list.add(alert); LOG.trace("[OpenSOC] Checking alerts cache: " + alert); if (cache.getIfPresent(alert) == null) { System.out.println("[OpenSOC]: Alert not found in cache: " + alert); JSONObject global_alert = new JSONObject(); global_alert.putAll(_identifier); global_alert.putAll(alerts_list.get(alert)); global_alert.put("timestamp", System.currentTimeMillis()); _collector.emit("alert", new Values(global_alert)); cache.put(alert, ""); } else LOG.trace("Alert located in cache: " + alert); LOG.debug("[OpenSOC] Alerts are: " + alerts_list); if (original_message.containsKey("alerts")) { JSONArray already_triggered = (JSONArray) original_message.get("alerts"); uuid_list.addAll(already_triggered); LOG.trace("[OpenSOC] Messages already had alerts...tagging more"); } original_message.put("alerts", uuid_list); LOG.debug("[OpenSOC] Detected alerts: " + alerts_tag); _collector.ack(tuple); _collector.emit("message", new Values(key, original_message)); } /* * if (metricConfiguration != null) { emitCounter.inc(); * ackCounter.inc(); } */ } } catch (Exception e) { e.printStackTrace(); LOG.error("Failed to tag message :" + original_message); e.printStackTrace(); _collector.fail(tuple); /* * if (metricConfiguration != null) { failCounter.inc(); } */ JSONObject error = ErrorGenerator.generateErrorMessage("Alerts problem: " + original_message, e); _collector.emit("error", new Values(error)); } }
From source file:edu.vt.vbi.patric.portlets.GlobalSearch.java
private void processGlobalSearch(ResourceRequest request, ResourceResponse response) throws IOException { // String spellCheck = request.getParameter("spellcheck"); JSONObject result = new JSONObject(); try {/*from www . j a v a2s . co m*/ // if(Boolean.parseBoolean(spellCheck)){ // JSONObject a = solr.getSpellCheckerResult(keyword); // result.put("suggestion", a.get("suggestion")); // } // result.put("suggestion", new JSONArray()); JSONArray data = new JSONArray(); { Map resp = processGlobalSearchFeature(request); JSONObject obj = new JSONObject(); obj.putAll(resp); data.add(obj); } { Map resp = processGlobalSearchGenome(request); JSONObject obj = new JSONObject(); obj.putAll(resp); data.add(obj); } { Map resp = processGlobalSearchTaxonomy(request); JSONObject obj = new JSONObject(); obj.putAll(resp); data.add(obj); } { Map resp = processGlobalSearchExperiment(request); JSONObject obj = new JSONObject(); obj.putAll(resp); data.add(obj); } result.put("data", data); } catch (IOException e) { LOGGER.error(e.getMessage(), e); } response.setContentType("application/json"); result.writeJSONString(response.getWriter()); }
From source file:com.fujitsu.dc.core.rs.box.BoxResource.java
/** * box????????????????????.//from w w w . j a v a 2 s .co m * @return ?JSON */ @SuppressWarnings("unchecked") private JSONObject createResponse(JSONObject values) { JSONObject response = new JSONObject(); response.putAll(values); response.remove("cell_id"); response.remove("box_id"); response.put("schema", this.getBox().getSchema()); ProgressInfo.STATUS status = ProgressInfo.STATUS.valueOf((String) values.get("status")); if (status == ProgressInfo.STATUS.COMPLETED) { response.remove("progress"); String startedAt = (String) response.remove("started_at"); response.put("installed_at", startedAt); } response.put("status", status.value()); return response; }
From source file:edu.vt.vbi.patric.portlets.GlobalSearch.java
public void serveResource(ResourceRequest request, ResourceResponse response) throws PortletException, IOException { String need = request.getParameter("need"); switch (need) { case "search": processGlobalSearch(request, response); break;// ww w. ja va 2s.c o m case "download": { String category = request.getParameter("cat"); DataApiHandler dataApi = new DataApiHandler(request); List<String> tableHeader = new ArrayList<>(); List<String> tableField = new ArrayList<>(); JSONArray tableSource = new JSONArray(); String fileFormat = request.getParameter("fileformat"); String fileName = "GlobalSearch"; switch (category) { case "0": { tableHeader.addAll(DownloadHelper.getHeaderForFeatures()); tableField.addAll(DownloadHelper.getFieldsForFeatures()); Map resp = processGlobalSearchFeature(request); Map respBody = (Map) resp.get("response"); List<GenomeFeature> features = dataApi.bindDocuments((List<Map>) respBody.get("docs"), GenomeFeature.class); for (GenomeFeature feature : features) { tableSource.add(feature.toJSONObject()); } break; } case "1": { tableHeader.addAll(DownloadHelper.getHeaderForGenomes()); tableField.addAll(DownloadHelper.getFieldsForGenomes()); Map resp = processGlobalSearchGenome(request); Map respBody = (Map) resp.get("response"); List<Genome> genomes = dataApi.bindDocuments((List<Map>) respBody.get("docs"), Genome.class); for (Genome genome : genomes) { tableSource.add(genome.toJSONObject()); } break; } case "2": { tableHeader.addAll(Arrays.asList("Taxon ID", "Taxon Name", "# of Genomes")); tableField.addAll(Arrays.asList("taxon_id", "taxon_name", "genomes")); Map resp = processGlobalSearchTaxonomy(request); Map respBody = (Map) resp.get("response"); List<Taxonomy> taxonomies = dataApi.bindDocuments((List<Map>) respBody.get("docs"), Taxonomy.class); for (Taxonomy taxonomy : taxonomies) { tableSource.add(taxonomy.toJSONObject()); } break; } case "3": { tableHeader.addAll(DownloadHelper.getHeaderForTranscriptomicsExperiment()); tableField.addAll(DownloadHelper.getFieldsForTranscriptomicsExperiment()); Map resp = processGlobalSearchExperiment(request); Map respBody = (Map) resp.get("response"); List<Map> docs = (List<Map>) respBody.get("docs"); for (Map doc : docs) { JSONObject item = new JSONObject(); item.putAll(doc); tableSource.add(item); } 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:com.kyne.webby.rtk.web.WebServer.java
@SuppressWarnings("unchecked") public void printJSON(final Map<String, Object> data, final Socket clientSocket) { try {/* ww w .j av a 2 s.c o m*/ final DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream()); out.writeBytes("HTTP/1.1 200 OK\r\n"); out.writeBytes("Content-Type: application/json; charset=utf-8\r\n"); out.writeBytes("Cache-Control: no-cache \r\n"); out.writeBytes("Server: Bukkit Webby\r\n"); out.writeBytes("Connection: Close\r\n\r\n"); final JSONObject json = new JSONObject(); json.putAll(data); out.writeBytes(json.toJSONString()); out.flush(); out.close(); } catch (final SocketException e) { /* .. */ } catch (final Exception e) { LogHelper.error(e.getMessage(), e); } }
From source file:de.dailab.plistacontest.client.ClientAndContestHandler0MQ.java
/** * Method to handle incoming messages from the server. * //from ww w . j av a 2s . c o m * @param messageType * the messageType of the incoming contest server message. * @param properties * * @param entities * @return the response to the contest server */ 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 = item.getNotificationType(); // new items shall be added to the list of items if (item.getItemID() != null) { recommenderItemTable.handleItemUpdate(item); } response = "handle impression eventNotification successful"; // impression refers to articles read by the user if ("recommendation_request".equalsIgnoreCase(eventNotificationType)) { // we mark this information in the article table if (item.getItemID() != null) { item.setNumberOfRequestedResults(6); //List<Long> suggestedItemIDs = item.getListOfDisplayedRecs(); List<Long> suggestedItemIDs = recommenderItemTable.getLastItems(item); response = "{" + "\"recs\": {" + "\"ints\": {" + "\"3\": " + suggestedItemIDs + "}" + "}}"; } else { System.err.println("invalid itemID - requests are only valid for 'normal' articles"); } // 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) { // new items shall be added to the list of items recommenderItemTable.handleItemUpdate(item); 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:de.dailab.plistacontest.client.ContestHandler.java
/** * Method to handle incoming messages from the server. * //from w w w. java2 s . c o 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) || "recommendation".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) || "recommendation".equalsIgnoreCase(eventNotificationType)) { // we mark this information in the article table if (item.getItemID() != null) { // new items shall be added to the list of items recommenderItemTable.handleItemUpdate(item); item.setNumberOfRequestedResults(6); response = "handle impression eventNotification successful"; boolean recommendationExpected = false; if (properties.contains("\"event_type\": \"recommendation_request\"")) { recommendationExpected = true; } if (recommendationExpected) { List<Long> suggestedItemIDs = recommenderItemTable.getLastItems(item); 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) { // new items shall be added to the list of items recommenderItemTable.handleItemUpdate(item); 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.portlets.ProteomicsListPortlet.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 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;/* w ww .java2 s. co m*/ } String keyword = request.getParameter("keyword"); String state = request.getParameter("state"); if (!taxonId.equalsIgnoreCase("")) { key.put("taxonId", taxonId); } if (keyword != null) { key.put("keyword", keyword.trim()); } 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"); switch (need) { case "0": { 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> sdl = (List<Map>) data.get("experiments"); JSONArray docs = new JSONArray(); for (Map doc : sdl) { JSONObject item = new JSONObject(); item.putAll(doc); docs.add(item); } 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)); } JSONObject jsonResult = new JSONObject(); jsonResult.put("results", docs); jsonResult.put("total", numFound); response.setContentType("application/json"); PrintWriter writer = response.getWriter(); jsonResult.writeJSONString(writer); writer.close(); break; } case "1": { String pk = request.getParameter("pk"); // Map data = processProteinTab(request); Map<String, String> key = (Map) data.get("key"); int numFound = (Integer) data.get("numFound"); List<Map> sdl = (List<Map>) data.get("proteins"); JSONArray docs = new JSONArray(); for (Map doc : sdl) { JSONObject item = new JSONObject(doc); docs.add(item); } 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)); } JSONObject jsonResult = new JSONObject(); jsonResult.put("results", docs); jsonResult.put("total", numFound); response.setContentType("application/json"); PrintWriter writer = response.getWriter(); writer.write(jsonResult.toString()); writer.close(); break; } case "tree": { String pk = request.getParameter("pk"); String state; Map<String, String> key = jsonReader .readValue(SessionHandler.getInstance().get(SessionHandler.PREFIX + pk)); 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").isEmpty()) { JSONObject facet_fields = (JSONObject) new JSONParser().parse(key.get("facets")); DataApiHandler dataApi = new DataApiHandler(request); tree = FacetHelper.processStateAndTree(dataApi, SolrCore.PROTEOMICS_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 "getFeatureIds": { String keyword = request.getParameter("keyword"); Map<String, String> key = new HashMap<>(); key.put("keyword", keyword); DataApiHandler dataApi = new DataApiHandler(request); SolrQuery query = dataApi.buildSolrQuery(key, null, null, 0, -1, false); String apiResponse = dataApi.solrQuery(SolrCore.PROTEOMICS_PROTEIN, query); Map resp = jsonReader.readValue(apiResponse); Map respBody = (Map) resp.get("response"); JSONObject object = new JSONObject(respBody); // solr.setCurrentInstance(SolrCore.PROTEOMICS_PROTEIN); // JSONObject object = null; //solr.getData(key, null, facet, 0, -1, false, false, false); response.setContentType("application/json"); PrintWriter writer = response.getWriter(); object.writeJSONString(writer); // writer.write(object.get("response").toString()); writer.close(); break; } case "getPeptides": { String experiment_id = request.getParameter("experiment_id"); String na_feature_id = request.getParameter("na_feature_id"); Map<String, String> key = new HashMap<>(); key.put("keyword", "na_feature_id:" + na_feature_id + " AND experiment_id:" + experiment_id); key.put("fields", "peptide_sequence"); DataApiHandler dataApi = new DataApiHandler(request); SolrQuery query = dataApi.buildSolrQuery(key, null, null, 0, -1, false); String apiResponse = dataApi.solrQuery(SolrCore.PROTEOMICS_PEPTIDE, query); Map resp = jsonReader.readValue(apiResponse); Map respBody = (Map) resp.get("response"); JSONObject object = new JSONObject(); object.putAll(respBody); // solr.setCurrentInstance(SolrCore.PROTEOMICS_PEPTIDE); // JSONObject object = solr.getData(key, null, facet, 0, -1, false, false, false); // object = (JSONObject) object.get("response"); object.put("aa", FASTAHelper.getFASTASequence(request, Arrays.asList(na_feature_id), "protein")); response.setContentType("application/json"); PrintWriter writer = response.getWriter(); object.writeJSONString(writer); writer.close(); break; } } } }