List of usage examples for org.json.simple JSONObject toString
@Override
public String toString()
From source file:com.ibm.storlet.common.StorletObjectOutputStream.java
@SuppressWarnings("unchecked") public void setMetadata(Map<String, String> md) throws StorletException { JSONObject jobj = new JSONObject(); Iterator<Map.Entry<String, String>> it = md.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> pairs = (Map.Entry<String, String>) it.next(); jobj.put((String) pairs.getKey(), (String) pairs.getValue()); it.remove();/*from w ww .j av a 2 s . co m*/ } try { MetadataStream_.write(jobj.toString().getBytes()); MetadataStream_.close(); } catch (IOException e) { throw new StorletException("Failed to set metadata " + e.toString()); } }
From source file:gwap.rest.User.java
@POST @Consumes(MediaType.APPLICATION_JSON)/*from ww w .j a v a 2s . c o m*/ @Produces(MediaType.APPLICATION_JSON) @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) @Transactional @Path("/{id:[A-Za-z0-9][A-Za-z0-9]*}") public Response createUser(@PathParam("id") String deviceId, String payloadString) { Query query = entityManager.createNamedQuery("person.byDeviceId"); query.setParameter("deviceId", deviceId); if (query.getResultList().size() > 0) { log.info("createUser(#0): Person does already exist, not creating again", deviceId); return Response.status(Response.Status.NOT_FOUND).build(); } Person person = new Person(); person.setUsername(""); person.setDeviceId(deviceId); person.setExternalUsername("Neuling"); person.setLastLogin(new Date()); entityManager.persist(person); entityManager.flush(); JSONObject userObject = getUserStatistics(deviceId, person); log.info("createUser(#0): Person #1 created successfully.", deviceId, person); return Response.ok(userObject.toString(), MediaType.APPLICATION_JSON).build(); }
From source file:com.opensoc.enrichment.adapters.geo.GeoMysqlAdapterTest.java
/** * Test method for {@link com.opensoc.enrichment.adapters.geo.GeoMysqlAdapter#enrich(java.lang.String)}. *///w w w . jav a 2 s.com public void testEnrich() { if (skipTests(this.getMode())) { return;//skip tests } else { try { JSONObject json = geoMySqlAdapter.enrich("72.163.4.161"); //assert Geo Response is not null System.out.println("json =" + json); assertNotNull(json); assertEquals(true, super.validateJsonData(super.getSchemaJsonString(), json.toString())); //assert LocId is not null assertNotNull(json.get("locID")); //assert right LocId is being returned assertEquals("4522", json.get("locID")); } catch (Exception e) { e.printStackTrace(); fail("Json validation Failed"); } } }
From source file:cn.vlabs.umt.ui.servlet.LoginTokenServlet.java
private void writeToResponse(HttpServletResponse response, Token randomToken) throws IOException { // all for ie response.setContentType("text/html"); PrintWriter writer = response.getWriter(); JSONObject obj = new JSONObject(); obj.put("token", randomToken.getRandom() + "-" + randomToken.getId()); obj.put("createTime", randomToken.getCreateTime().getTime()); obj.put("expireTime", String.valueOf(randomToken.getExpireTime())); writer.write(obj.toString()); }
From source file:gov.nih.nci.caintegrator.application.lists.ajax.CommonListFunctions.java
public static String getListAsList(ListType ty) { JSONObject res = new JSONObject(); res.put("listType", ty.toString()); String results = ""; HttpSession session = ExecutionContext.get().getSession(false); UserListBeanHelper helper = new UserListBeanHelper(session); List patientLists = helper.getLists(ty); if (!patientLists.isEmpty()) { for (int i = 0; i < patientLists.size(); i++) { UserList list = (UserList) patientLists.get(i); ListManager uploadManager = (ListManager) ListManager.getInstance(); Map paramMap = uploadManager.getParams(list); String commas = StringUtils.join(list.getList().toArray(), ","); String sty = list.getListOrigin() != null && !list.getListOrigin().equals(ListOrigin.Default) ? "color:#A90101" : "color:#000"; results += ("<li id='" + paramMap.get("listName") + "' title='" + commas + "' style='" + sty + "'>" + paramMap.get("listName") + "</li>"); }/*from ww w. jav a 2 s .c o m*/ } else { results = ""; } res.put("LIs", results); return res.toString(); }
From source file:hoot.services.controllers.ingest.BasemapResource.java
@GET @Path("/delete") @Produces(MediaType.TEXT_PLAIN)//w w w. j a v a 2 s . c om public Response deleteBasemap(@QueryParam("NAME") final String bmName) { try { _deleteBaseMap(bmName); } catch (Exception ex) { ResourceErrorHandler.handleError("Error deleting base map: " + bmName + " Error: " + ex.getMessage(), Status.INTERNAL_SERVER_ERROR, log); } JSONObject resp = new JSONObject(); resp.put("name", bmName); return Response.ok(resp.toString(), MediaType.TEXT_PLAIN).build(); }
From source file:control.ParametrizacionServlets.InsertarPrmfisicoquimicos.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from ww 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 { try { //Obtenemos los datos enviados. String descripcion = request.getParameter("descripcion"); int unidades = Integer.parseInt(request.getParameter("unidades")); int tipoParametro = Integer.parseInt(request.getParameter("tipoParametro")); int salida; JSONObject jsonObject = new JSONObject(); //Creamos el manager para registrar la informacion ParamFisicoquimicos manager = new ParamFisicoquimicos(); salida = manager.insertar(descripcion, tipoParametro, unidades); jsonObject.put("error", salida); response.setContentType("application/json"); response.getWriter().write(jsonObject.toString()); } catch (Exception ex) { //Logger.getLogger(InsertarActEconomica.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:itinno.example.ExampleSocialMediaJavaLoggerBolt.java
/** * Execute received Tuple. In this case the bolt will parse received tuple and log the message to the log file. * //from w w w . j a v a2 s .c o m * @param input standard Storm tuple input object (passed within Storm topology itself, not be a user) */ @Override public void execute(Tuple input) { try { // Retrieve hash map tuple object from Tuple input at index 0, index 1 will be message delivery tag (not used here) Map<Object, Object> inputMap = (HashMap<Object, Object>) input.getValue(0); // Get JSON object from the HashMap from the Collections.singletonList JSONObject jsonObject = (JSONObject) Collections.singletonList(inputMap.get("message")).get(0); // Since all the input will be utf-8 encoded using AMQP Storm Schema, simple get the json string message value String strMessage = jsonObject.toString(); // Finally log UTF-8 JSON message to disk to verify its all OK logger.info("JSON received = " + jsonObject.toString()); // Emit a received message this.collector.emit(new Values(strMessage)); // Acknowledge the collector that we actually received the input this.collector.ack(input); } catch (Exception e) { e.printStackTrace(); try { throw new Exception("Failed to parse tuple input. Details: " + e.getMessage()); } catch (Exception e1) { e1.printStackTrace(); } } }
From source file:XBMCmote.java
/** * * @param title title of notification/*w ww . ja va2 s .c o m*/ * @param message body of notification * @param image icon to be displayed with notification * @return command sent */ @Command public String notify(String title, String message, String image) { JSONObject request = XBMC.guiNotify; LinkedHashMap params = new LinkedHashMap(); params.put("title", title); params.put("message", message); params.put("image", image); request.put("params", params); String response = XBMC.sendCommand(request); return String.format("%s\n%s", request.toString(), response); }
From source file:de.codebucket.licenseservice.util.UpdateTask.java
public void check() { new Thread(new Runnable() { public void run() { try { URL url = new URL(UpdateTask.this.url); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); JSONObject response = (JSONObject) parser .parse(new InputStreamReader(connection.getInputStream())); String content = response.toString(); Update update = new Gson().fromJson(content, Update.class); updateSucess(update);//from w ww . j a v a 2s.com } catch (Exception ex) { updateSucess(null); } } }).start(); }