List of usage examples for org.json.simple JSONObject toString
@Override
public String toString()
From source file:XBMCmote.java
/** * * @param title title of notification/*from w w w .jav a 2s. c om*/ * @param message body of notification * @param image icon to be displayed with notification * @param timeout time to display notification * @return command sent */ @Command public String notify(String title, String message, String image, int timeout) { JSONObject request = XBMC.guiNotify; LinkedHashMap params = new LinkedHashMap(); params.put("title", title); params.put("message", message); params.put("image", image); params.put("timeout", timeout); request.put("params", params); String response = XBMC.sendCommand(request); return String.format("%s\n%s", request.toString(), response); }
From source file:control.ProcesoVertimientosServlets.EliminarAnexosLodos.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*ww w . j a v a2 s . c om*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JSONObject resp = new JSONObject(); try { Integer codigoArchivo = Integer.parseInt(request.getParameter("codigoArchivo")); Integer codigoProceso = Integer.parseInt(request.getParameter("codigoProceso")); ManejoLodos manager = new ManejoLodos(); resp = manager.eliminarAnexos(codigoArchivo, codigoProceso); response.setContentType("application/json"); response.getWriter().write(resp.toString()); } catch (Exception ex) { resp.put("error", 0); response.getWriter().write(resp.toString()); } }
From source file:control.ProcesoVertimientosServlets.EliminarAnexosMonitoreo.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request// w ww. ja v a2 s. co m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JSONObject resp = new JSONObject(); try { Integer codigoArchivo = Integer.parseInt(request.getParameter("codigoArchivo")); Integer codigoMonitoreo = Integer.parseInt(request.getParameter("codigoMonitoreo")); ProgramarMonitoreo manager = new ProgramarMonitoreo(); resp = manager.eliminarAnexos(codigoArchivo, codigoMonitoreo); response.setContentType("application/json"); response.getWriter().write(resp.toString()); } catch (Exception ex) { resp.put("error", 0); response.getWriter().write(resp.toString()); } }
From source file:com.mycompany.jpegrenamer.MetaDataReader.java
private Map<String, String> getAddressByGpsCoordinates(String lat, String lng) throws MalformedURLException, IOException, org.json.simple.parser.ParseException { Map<String, String> res = new HashMap(); URL url = new URL( "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + lng + "&sensor=true"); logger.info(url.toString());/*from w w w. ja va2 s . co m*/ HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); String formattedAddress = null; PrintStream out = new PrintStream(System.out, true, "UTF-8"); try { InputStream in = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8")); String result; String line = reader.readLine(); result = line; while ((line = reader.readLine()) != null) { result += line; } JSONParser parser = new JSONParser(); JSONObject rsp = (JSONObject) parser.parse(result); logger.debug("JSON " + rsp.toString()); if (rsp.containsKey("error_message")) { JSONObject msg = (JSONObject) rsp.get("error_message"); logger.error("Error response from Google Maps: " + msg); res.put("formatted_address", msg.toString()); } else if (rsp.containsKey("results")) { JSONArray matches = (JSONArray) rsp.get("results"); String premise = null; String administrative_area_level_1 = null; String administrative_area_level_2 = null; String sublocality_level_1 = null; String locality = null; String postal_town = null; String country = null; List<String> types = null; String short_name = null; String long_name = null; for (int i = 0; i < matches.size(); i++) { JSONObject data = (JSONObject) matches.get(i); //TODO: check if idx=0 exists if (formattedAddress == null) { formattedAddress = (String) data.get("formatted_address"); res.put("formatted_address", formattedAddress); } JSONObject comp = (JSONObject) ((JSONArray) data.get("address_components")).get(0); logger.debug("JSON " + comp.toString()); types = (List<String>) ((JSONArray) comp.get("types")); short_name = (String) comp.get("short_name"); long_name = (String) comp.get("long_name"); logger.debug("JSON types" + types); logger.debug("JSON short_name" + short_name); logger.debug("JSON long_name" + long_name); if (types.contains("premise")) { premise = long_name; res.put("premise", premise); } else if (types.contains("sublocality_level_1")) { sublocality_level_1 = long_name; res.put("sublocality_level_1", sublocality_level_1); } else if (types.contains("postal_town")) { postal_town = long_name; res.put("postal_town", postal_town); } else if (types.contains("country")) { logger.debug("Setting country to " + long_name); country = long_name; res.put("country", country); } else if (types.contains("locality") && locality == null) { logger.debug("Setting locality to " + long_name); locality = long_name; res.put("locality", locality); } else if (types.contains("administrative_area_level_1")) { logger.debug("Setting administrative_area_level_1 to " + long_name); administrative_area_level_1 = long_name; res.put("administrative_area_level_1", administrative_area_level_1); } } } } finally { urlConnection.disconnect(); logger.debug("Reverse geocode returns " + res); logger.debug("Reverse geocode returns formatted_address = " + formattedAddress); return res; } }
From source file:kvadrere.pig.geo.TileGeometry.java
public DataBag exec(Tuple input) throws IOException { if (input == null || input.size() < 2 || input.isNull(0) || input.isNull(1)) return null; DataBag returnKeys = bagFactory.newDefaultBag(); // Extract function parameters String zlvl = input.get(0).toString(); int zoomLevel = Integer.parseInt(zlvl); String jsonBlob = input.get(1).toString(); JSONObject jsonObject = parseJSONString(jsonBlob); Reader reader = new StringReader(jsonObject.get("geometry").toString()); GeometryJSON gjson = new GeometryJSON(); Geometry geom = gjson.read(reader);/*from w w w. ja va 2 s .c o m*/ if (zoomLevel < 1 || zoomLevel > 23 || geom.isEmpty()) return null; //zoomLevel exceeds bounds or geometry is empty try { if (geom.getGeometryType().equals(GEOM_POINT)) { // Point String quadkey = QuadKeyUtils.geoPointToQuadKey(((Point) geom).getX(), ((Point) geom).getY(), zoomLevel); JSONObject newJSONObject = setGeometry(geom, jsonObject); ((Map) newJSONObject.get("properties")).put("quadkey", quadkey); Tuple newQuadKey = tupleFactory.newTuple(2); newQuadKey.set(0, quadkey); newQuadKey.set(1, newJSONObject.toString()); returnKeys.add(newQuadKey); } else { // Polygon or MultiPolygon // getEnvelope() returns a Polygon whose points are (minx, miny), (maxx, miny), (maxx, maxy), (minx, maxy), (minx, miny). Polygon boundingBox = (Polygon) geom.getEnvelope(); int startZoom = 1; Coordinate[] boxTileCoords = QuadKeyUtils.latLngToTileCoords(boundingBox.getCoordinates(), startZoom); // Increase startZoom as much as possible until either the max zoom is reached, or the bounding box no longer fits within a single tile. while ((startZoom < zoomLevel) && (((int) boxTileCoords[0].x == (int) boxTileCoords[2].x) || ((int) boxTileCoords[0].y == (int) boxTileCoords[2].y))) { startZoom += 1; boxTileCoords = QuadKeyUtils.latLngToTileCoords(boundingBox.getCoordinates(), startZoom); } Coordinate[] boxCoordinates = boundingBox.getCoordinates(); // These are going to be tile coordinates, not lat/long coordinates. Coordinate[] boxTileCoordinates = QuadKeyUtils.latLngToTileCoords(boxCoordinates, startZoom); double maxX = boxTileCoordinates[0].x; double minX = boxTileCoordinates[0].x; double maxY = boxTileCoordinates[0].y; double minY = boxTileCoordinates[0].y; for (Coordinate c : boxTileCoordinates) { if (c.x > maxX) maxX = c.x; if (c.y > maxY) maxY = c.y; if (c.x < minX) minX = c.x; if (c.y < minY) minY = c.y; } for (int tileX = (int) minX; tileX <= (int) maxX; tileX++) { for (int tileY = (int) minY; tileY <= (int) maxY; tileY++) { String quadkey = QuadKeyUtils.tileXYToQuadKey(tileX, tileY, startZoom); // Recursively search for tiles that contain portions of the provided geometry for (Tuple t : searchTile(quadkey, geom, jsonObject, zoomLevel)) { returnKeys.add(t); } } } } } catch (TopologyException e) { System.out.println(e.getMessage()); throw e; } return returnKeys; }
From source file:control.ParametrizacionServlets.InsertarUnidadesMedida.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//from ww w . j av a2s.co m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JSONObject respError = new JSONObject(); try { //Obtenemos los datos enviados. String descripcion = request.getParameter("descripcion"); //Creamos el manager para registrar la informacion UnidadesMedida manager = new UnidadesMedida(); respError = manager.insertar(descripcion); //Armamos la respuesta JSON y la enviamos response.setContentType("application/json"); response.getWriter().write(respError.toString()); } catch (Exception ex) { //Armamos la respuesta JSON y la enviamos response.setContentType("application/json"); respError.put("error", 0); response.getWriter().write(respError.toString()); } }
From source file:fr.itldev.koya.services.impl.KoyaContentServiceImpl.java
@Override public InputStream getZipInputStream(User user, List<SecuredItem> securedItems) throws AlfrescoServiceException { HttpURLConnection con;/*from w w w .j ava 2 s . c o m*/ try { String urlDownload = getAlfrescoServerUrl() + DOWNLOAD_ZIP_WS_URI + user.getTicketAlfresco(); Map<String, Serializable> params = new HashMap<>(); ArrayList<String> selected = new ArrayList<>(); params.put("nodeRefs", selected); for (SecuredItem item : securedItems) { selected.add(item.getNodeRef()); } JSONObject postParams = new JSONObject(params); con = (HttpURLConnection) new URL(urlDownload).openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); con.setDoInput(true); con.setRequestProperty("Content-Type", "application/json"); con.getOutputStream().write(postParams.toString().getBytes()); return con.getInputStream(); } catch (IOException e) { throw new AlfrescoServiceException(e.getMessage(), e); } }
From source file:HostController.java
@RequestMapping("/hosts") public @ResponseBody Host host( @RequestParam(value = "authentication", required = false, defaultValue = "") String authentication) throws FileNotFoundException, UnsupportedEncodingException, IOException { Properties props = new Properties(); FileInputStream fis = new FileInputStream("properties.xml"); //loading properites from properties file props.loadFromXML(fis);//from w w w . j ava2 s.co m 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 HttpClient client = new HttpClient(); PutMethod putMethod = new PutMethod(ZABBIX_API_URL); // content-type is controlled in api_jsonrpc.php, so set it like this putMethod.setRequestHeader("Content-Type", "application/json-rpc"); // create json object for apiinfo.version JSONParser parser = new JSONParser(); JSONObject jsonObj = new JSONObject(); JSONArray list = new JSONArray(); jsonObj.put("jsonrpc", "2.0"); jsonObj.put("method", "host.get"); JSONObject params = new JSONObject(); params.put("output", "extend"); 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 String loginResponse = ""; 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"); for (int i = 0; i < array.size(); i++) { JSONObject tobj = (JSONObject) array.get(i); JSONObject objret = new JSONObject(); objret.put("hostid", tobj.get("hostid")); objret.put("hostName", tobj.get("host")); list.add(objret); } return new Host(list); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException pe) { pe.printStackTrace(); } return new Host( "Error: please provide the appropriate input parameters of the metric you are looking for its corresponding monitoring data:"); }
From source file:control.ProcesoVertimientosServlets.SeleccionarVisitas.java
private void getContVisitasPendientes(HttpServletRequest request, HttpServletResponse response) { JSONObject jsonObject = new JSONObject(); try {/*from w ww. ja v a 2 s.c o m*/ String codigoProceso = request.getParameter("codigoProceso"); Visitas manager = new Visitas(); jsonObject = manager.getContVisitasPendientes(codigoProceso); //Armamos la respuesta JSON y la enviamos response.setContentType("application/json"); response.getWriter().write(jsonObject.toString()); } catch (Exception e) { } }
From source file:control.AutenticacionServlets.InsertarPermisos.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/* w w w .jav a 2 s . c o m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JSONObject jsonObject = new JSONObject(); response.setContentType("application/json"); try { int codigo_rol = Integer.parseInt(request.getParameter("rol")); int codigo_pantalla = Integer.parseInt(request.getParameter("pantalla")); String valor = request.getParameter("valor"); PermisosAcceso manager = new PermisosAcceso(); jsonObject = manager.insertarPermisos(codigo_rol, codigo_pantalla, valor); response.getWriter().write(jsonObject.toString()); } catch (Exception ex) { jsonObject.put("error", 0); jsonObject.put("exception", ex.toString()); response.getWriter().write(jsonObject.toString()); } }