List of usage examples for org.json.simple JSONObject toString
@Override
public String toString()
From source file:com.burakgon.gcmsender.GCMSenderUI.java
private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendButtonActionPerformed CloseableHttpClient httpClient = HttpClientBuilder.create().build(); //Use this instead try {/*from w w w . j ava 2 s. c o m*/ HttpPost request = new HttpPost("https://gcm-http.googleapis.com/gcm/send"); JSONObject json = new JSONObject(); StringEntity params = new StringEntity( "{ \"notification\": { \"title\":" + "\"" + notificationTitleText.getText() + "\"" + ", \"text\":" + "\"" + notificationMessageText.getText() + "\"" + "}, \"to\" :" + "\"" + toDevice.getText() + "\"" + "}"); request.addHeader("content-type", "application/json"); request.addHeader("authorization", "key=" + gcmAPIText.getText()); StringEntity se = new StringEntity(json.toString()); request.setEntity(params); HttpResponse response = httpClient.execute(request); resultText.setText(response.getStatusLine().toString()); // handle response here... } catch (Exception ex) { // handle exception here Logger.getLogger(GCMSenderUI.class.getName()).log(Level.SEVERE, null, ex); } finally { try { httpClient.close(); } catch (IOException ex) { Logger.getLogger(GCMSenderUI.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:com.rackspacecloud.blueflood.outputs.handlers.HttpHistogramQueryHandler.java
@Override public void handle(ChannelHandlerContext ctx, HttpRequest request) { Tracker.track(request);/*from w ww . j av a 2 s.com*/ final String tenantId = request.getHeader("tenantId"); final String metricName = request.getHeader("metricName"); if (!(request instanceof HTTPRequestWithDecodedQueryParams)) { sendResponse(ctx, request, "Missing query params: from, to, points", HttpResponseStatus.BAD_REQUEST); return; } HTTPRequestWithDecodedQueryParams requestWithParams = (HTTPRequestWithDecodedQueryParams) request; final Timer.Context histFetchTimerContext = histFetchTimer.time(); try { RollupsQueryParams params = PlotRequestParser.parseParams(requestWithParams.getQueryParams()); JSONObject metricData; if (params.isGetByPoints()) { metricData = GetHistogramByPoints(tenantId, metricName, params.getRange().getStart(), params.getRange().getStop(), params.getPoints()); } else if (params.isGetByResolution()) { metricData = GetHistogramByResolution(tenantId, metricName, params.getRange().getStart(), params.getRange().getStop(), params.getResolution()); } else { throw new InvalidRequestException( "Invalid rollups query. Neither points nor resolution specified."); } final JsonElement element = parser.parse(metricData.toString()); final String jsonStringRep = gson.toJson(element); sendResponse(ctx, request, jsonStringRep, HttpResponseStatus.OK); } catch (InvalidRequestException e) { sendResponse(ctx, request, e.getMessage(), HttpResponseStatus.BAD_REQUEST); } catch (SerializationException e) { sendResponse(ctx, request, e.getMessage(), HttpResponseStatus.INTERNAL_SERVER_ERROR); } catch (Exception e) { sendResponse(ctx, request, e.getMessage(), HttpResponseStatus.INTERNAL_SERVER_ERROR); } finally { histFetchTimerContext.stop(); } }
From source file:at.ac.sbg.icts.spacebrew.client.SpacebrewClient.java
/** * Sends a JSON message to the server.//w w w. jav a2 s.com * * @param message The message to send */ private void publish(JSONObject message) { if (connected) { webSocketClient.send(message.toString()); } else { log.warn("Could not send message, not connected!"); } }
From source file:com.gae.ChannelAPIServlet.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { String rv = req.getParameter("rv"); String idb = req.getParameter("id"); String valb = req.getParameter("val"); String[] id = idb.split(","); String[] val = valb.split("<p>"); Date date1 = new Date(); SimpleDateFormat df = new SimpleDateFormat("yyyy''MM''dd''kk''mm''ss''"); String date = df.format(date1); //Add to detastore if (!req.getParameter("kind").equals("none")) { /*/*from ww w . j av a2s.c om*/ * CRUD ? */ DirectBeans_textjson dbeans = new DirectBeans_textjson(); String kind = req.getParameter("kind"); String key = req.getParameter("clientId"); dbeans.addDirect(kind, key, id, val, "deli"); } JSONObject jsonobj = new JSONObject(); for (int i = 0; i < id.length; i++) { // Add 2011-12-24 for Text data if (id[i].charAt(2) == ':') { id[i] = id[i].substring(3); } // Add 2011-12-24 for Text data jsonobj.put(id[i], val[i]); } jsonobj.put("date", date); byte[] clientList_b = (byte[]) cache.get("uidKey"); String clientList = new String(clientList_b, "UTF-8"); String[] clientList_a = clientList.split(","); try { for (int i = 0; i < clientList_a.length; i++) { channelService.sendMessage(new ChannelMessage(clientList_a[i], jsonobj.toString())); } } catch (ChannelFailureException e) { throw new RuntimeException(e); } String clients = ""; for (int i = 0; i < clientList_a.length; i++) { clients += clientList_a[i] + ","; } clients = clients.substring(0, clients.length() - 1); resp.getWriter().write(clients); }
From source file:com.megacasting_ppe.web.Servletloadpageflux.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* www .j a v a 2s . co m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json; charset=ISO-8859-1"); HttpSession session = request.getSession(); JSONObject global = new JSONObject(); Diffuseur diffuseur = (Diffuseur) session.getAttribute("DiffuseurObject"); String connecterOk = (String) session.getAttribute("ConnecterDiffuseur"); if (diffuseur != null && connecterOk != null) { JSONObject infoAuth = new JSONObject(); infoAuth.put("Entreprise", diffuseur.getNomEntreprise()); infoAuth.put("connecter", connecterOk); global.put("infoauth", infoAuth); } else { JSONObject infoAuth = new JSONObject(); infoAuth.put("connecter", "false"); global.put("infoauth", infoAuth); } ; try (PrintWriter out = response.getWriter()) { out.println(global.toString()); } }
From source file:io.personium.test.jersey.cell.ctl.ExtRoleCreateTest.java
/** * ????????ExtRole??./*from www .j a v a 2 s. co m*/ * @param relationNameEmpty _Relation.Name??? * @param relationBoxNameEmpty _Relation._Box.Name??? */ @SuppressWarnings("unchecked") private void createExtRole(boolean relationNameEmpty, boolean relationBoxNameEmpty) { JSONObject body = new JSONObject(); body.put("ExtRole", EXTROLE_PATH_DEFAULT); if (!relationNameEmpty) { body.put("_Relation.Name", null); } if (!relationBoxNameEmpty) { body.put("_Relation._Box.Name", null); } Http.request("cell/extRole/extRole-create.txt").with("token", AbstractCase.MASTER_TOKEN_NAME) .with("cellPath", cellName).with("body", body.toString()).returns() .statusCode(HttpStatus.SC_BAD_REQUEST); }
From source file:cloudworker.Animoto.java
@SuppressWarnings("unchecked") public void run() { //Get queue url GetQueueUrlResult urlResult = sqs.getQueueUrl(responseQName); String QueueUrl = urlResult.getQueueUrl(); JSONObject result = new JSONObject(); Runtime runtime = Runtime.getRuntime(); try {/*from w w w .j a v a2s . com*/ String[] urls = task.split(" "); for (String url : urls) { //System.out.println(url); Process p = runtime.exec("wget " + url); p.waitFor(); } Process rename = runtime.exec("./rename.sh"); rename.waitFor(); runtime.exec("ffmpeg -f image2 -i img%03d.jpg movie.mpg"); File movie = new File("movie.mpg"); S3Service s3 = new S3Service(); URL url = s3.put(movie.getName(), movie); //result.put("task_id", task_id); result.put("URL", url.toString()); sqs.sendMessage(new SendMessageRequest(QueueUrl, result.toString())); //System.out.println(Thread.currentThread().getName()+" sleep done!"); } catch (Exception e) { //result.put("task_id", task_id); result.put("URL", "Failed!"); sqs.sendMessage(new SendMessageRequest(QueueUrl, result.toString())); } }
From source file:com.fujitsu.dc.test.jersey.concurrent.ConcurrentODataRequestTest.java
/** * Role??./*from ww w . jav a 2 s . co m*/ * @param roleName ?? * @param boxName Box?? * @return */ @SuppressWarnings("unchecked") Http createRoleRequest(String roleName, String boxName) { JSONObject body = new JSONObject(); body.put("Name", roleName); body.put("_Box.Name", boxName); return Http.request("role-create.txt").with("cellPath", CELL_NAME) .with("token", AbstractCase.MASTER_TOKEN_NAME).with("body", body.toString()); }
From source file:MemoryController.java
@RequestMapping("/memory") public @ResponseBody Memory memory( @RequestParam(value = "authentication", required = false, defaultValue = "Error") String authentication, @RequestParam(value = "hostid", required = false, defaultValue = "") String hostid, @RequestParam(value = "metricType", required = false, defaultValue = "") String name) throws FileNotFoundException, UnsupportedEncodingException, IOException { Properties props = new Properties(); FileInputStream fis = new FileInputStream("properties.xml"); //loading properites from properties file props.loadFromXML(fis);// w w w.j a v a 2 s .c om String server_ip = props.getProperty("server_ip"); String ZABBIX_API_URL = "http://" + server_ip + "/api_jsonrpc.php"; // 1.2.3.4 is your zabbix_server_ip JSONParser parser = new JSONParser(); HttpClient client = new HttpClient(); PutMethod putMethod = new PutMethod(ZABBIX_API_URL); putMethod.setRequestHeader("Content-Type", "application/json-rpc"); // content-type is controlled in api_jsonrpc.php, so set it like this // create json object for apiinfo.version JSONObject jsonObj = new JSONObject(); jsonObj.put("jsonrpc", "2.0"); jsonObj.put("method", "item.get"); JSONObject params = new JSONObject(); params.put("output", "extend"); params.put("hostid", hostid); JSONObject search = new JSONObject(); search.put("key_", "memory"); params.put("search", search); params.put("sortfield", "name"); jsonObj.put("params", params); jsonObj.put("auth", authentication);// todo jsonObj.put("id", new Integer(1)); putMethod.setRequestBody(jsonObj.toString()); // put the json object as input stream into request body PutMethod putMethod2 = new PutMethod(ZABBIX_API_URL); putMethod2.setRequestHeader("Content-Type", "application/json-rpc"); // content-type is controlled in api_jsonrpc.php, so set it like this // create json object for apiinfo.version JSONObject jsonObj2 = new JSONObject(); jsonObj2.put("jsonrpc", "2.0"); jsonObj2.put("method", "item.get"); JSONObject params2 = new JSONObject(); params2.put("output", "extend"); params2.put("hostid", hostid); JSONObject search2 = new JSONObject(); search2.put("key_", "swap"); params2.put("search", search2); params2.put("sortfield", "name"); jsonObj2.put("params", params2); jsonObj2.put("auth", authentication);// todo jsonObj2.put("id", new Integer(1)); putMethod2.setRequestBody(jsonObj2.toString()); String loginResponse = ""; String loginResponse2 = ""; String memory = ""; String clock = ""; String metricType = ""; try { client.executeMethod(putMethod); // send to request to the zabbix api loginResponse = putMethod.getResponseBodyAsString(); // read the result of the response Object obj = parser.parse(loginResponse); JSONObject obj2 = (JSONObject) obj; String jsonrpc = (String) obj2.get("jsonrpc"); JSONArray array = (JSONArray) obj2.get("result"); client.executeMethod(putMethod2); // send to request to the zabbix api loginResponse2 = putMethod2.getResponseBodyAsString(); // read the result of the response Object obj3 = parser.parse(loginResponse2); JSONObject obj4 = (JSONObject) obj3; String jsonrpc2 = (String) obj4.get("jsonrpc"); JSONArray array2 = (JSONArray) obj4.get("result"); for (int i = 0; i < array.size(); i++) { JSONObject tobj = (JSONObject) array.get(i); // lastValue = getLastValue(tobj); // lastClock = getLastClock(tobj); if (!tobj.get("hostid").equals(hostid)) continue; if (name.equals("totalMemory") && tobj.get("name").equals("Total memory")) { memory = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "Total Memeory"; return new Memory(hostid, metricType, memory, clock); } else if (name.equals("cachedMemory") && tobj.get("name").equals("Cached memory")) { memory = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "Cached Memory"; return new Memory(hostid, metricType, memory, clock); } else if (name.equals("freeMemory") && tobj.get("name").equals("Free memory")) { memory = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "Free Memory"; return new Memory(hostid, metricType, memory, clock); } else if (name.equals("bufferedMemory") && tobj.get("name").equals("Buffers memory")) { memory = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "Buffered Memory"; return new Memory(hostid, metricType, memory, clock); } else if (name.equals("sharedMemory") && tobj.get("name").equals("Shared memory")) { memory = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "Shared Memory"; return new Memory(hostid, metricType, memory, clock); } else { continue; } } for (int i = 0; i < array2.size(); i++) { JSONObject tobj2 = (JSONObject) array2.get(i); if (!tobj2.get("hostid").equals(hostid)) continue; if (name.equals("freeSwap") && tobj2.get("name").equals("Free swap space")) { memory = (String) tobj2.get("lastvalue"); clock = (String) tobj2.get("lastclock"); metricType = "Free Swap Space"; return new Memory(hostid, metricType, memory, clock); } else { continue; } } } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException pe) { System.out.println("Error"); } return new Memory( "Error: please provide the appropriate input parameters of the metric you are looking for its corresponding monitoring data:"); }
From source file:com.ba.reports.outStanding.BAOutStandingAction.java
public ActionForward baView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { System.out.println("view()"); JSONObject json = new JSONObject(); BAOutStandingDTO vo = new BAOutStandingDTO(); try {/*from w w w. j a v a 2 s.c o m*/ logger.info(" view method starts here"); String fromDate = request.getParameter("fromDate"); String toDate = request.getParameter("toDate"); List hashMpRoomItemDet = BAOutStandingFactory.getInstanceOfBAOutStandingFactory().getRoomDtls(fromDate, toDate); json.put("exception", ""); json.put("hashMpRoomItemDet", hashMpRoomItemDet); json.put("hashMpRoomItemDetExit", hashMpRoomItemDet.size()); } catch (Exception ex) { logger.error("The Exception is :" + ex); ex.printStackTrace(); json.put("exception", BAHandleAllException.exceptionHandler(ex)); } response.getWriter().write(json.toString()); return null; }