List of usage examples for com.google.gson JsonObject toString
@Override
public String toString()
From source file:cd.go.contrib.elasticagents.dockerswarm.elasticagent.reports.StatusReportGenerationErrorHandler.java
License:Apache License
public static GoPluginApiResponse handle(PluginStatusReportViewBuilder builder, Exception e) { try {//from w ww .ja v a 2s. co m LOG.error(format("Error while generating status report: {0}", e.getMessage()), e); final Template template = builder.getTemplate("error.template.ftlh"); final String errorView = builder.build(template, new StatusReportGenerationError(e)); final JsonObject responseJSON = new JsonObject(); responseJSON.addProperty("view", errorView); return DefaultGoPluginApiResponse.success(responseJSON.toString()); } catch (Exception ex) { LOG.error(format("Failed to generate error report: {0}", e.getMessage()), e); return DefaultGoPluginApiResponse.error(format("Failed to generate error report: {0}.", e.toString())); } }
From source file:cf.adriantodt.David.modules.db.I18nModule.java
License:LGPL
public static String generateJsonDump() { System.out.println();//from w ww . jav a2 s. c o m JsonObject json = new JsonObject(); JsonObject parentsJson = new JsonObject(); JsonObject localizations = new JsonObject(); parents.forEach(parentsJson::addProperty); locales.forEach((k, v) -> { JsonObject localization = new JsonObject(); v.forEach(localization::addProperty); localizations.add(k, localization); }); json.add("parents", parentsJson); json.add("localizations", localizations); return json.toString(); }
From source file:ch.ethz.coss.nervous.pulse.sql.SqlRequestWorker.java
License:Open Source License
@Override public void run() { try {/*from w ww . j a v a 2 s. co m*/ JsonObject feature = null; JsonArray features = null; JsonObject featureCollection = null; try { /***** SQL get ********/ // Fetch data PreparedStatement datastmt = sqlse.getSensorValuesFetchStatement(connection, ptmRequest.readingType, ptmRequest.startTime, ptmRequest.endTime); ResultSet rs = datastmt.executeQuery(); featureCollection = new JsonObject(); features = new JsonArray(); // System.out.println("SQL query result size = // "+rs.getFetchSize()); long currentTimeMillis = System.currentTimeMillis(); while (rs.next()) { long volatility = rs.getLong("Volatility"); long recordTime = rs.getLong("RecordTime"); // System.out.println("Volatility = " + volatility); // System.out.println("currentTimeMillis = " + currentTimeMillis); // System.out.println("left time = " + (currentTimeMillis - (recordTime + (volatility * 1000)))); if (volatility != -1) if (volatility == 0 || currentTimeMillis > (recordTime + (volatility * 1000))) { // System.out.println("Continue"); continue; } String lat = rs.getString("lat"); String lon = rs.getString("lon"); feature = new JsonObject(); feature.addProperty("type", "Feature"); JsonObject point = new JsonObject(); point.addProperty("type", "Point"); JsonArray coord = new JsonArray(); coord.add(new JsonPrimitive(lat)); coord.add(new JsonPrimitive(lon)); point.add("coordinates", coord); feature.add("geometry", point); JsonObject properties = new JsonObject(); properties.addProperty("volatility", volatility); if (ptmRequest.readingType == 0) { String luxVal = rs.getString("Light"); // System.out.println("Reading instance of light"); properties.addProperty("readingType", "" + 0); properties.addProperty("level", luxVal); } else if (ptmRequest.readingType == 1) { String soundVal = rs.getString("Decibel"); properties.addProperty("readingType", "" + 1); properties.addProperty("level", soundVal); } else if (ptmRequest.readingType == 2) { String message = rs.getString("Message"); message = message.trim(); properties.addProperty("readingType", "" + 2); if (message.length() <= 0) { message = "***Empty Message***"; continue; } properties.addProperty("message", message); } else { // System.out.println("Reading instance not known"); } feature.add("properties", properties); features.add(feature); // if((features.getAsJsonArray()).size() >= 60000){ // featureCollection.add("features", features); // pSocketServer.sendToSocket(ptmRequest.webSocket, // ptmRequest.requestID, featureCollection.toString(), // false); // featureCollection = new JsonObject(); // featureCollection = new JsonObject(); // features = new JsonArray(); // try { // Thread.sleep(10); // } catch (Exception e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // break; // } } featureCollection.add("features", features); // System.out.println("Feature collection + // "+featureCollection.toString()); pSocketServer.sendToSocket(ptmRequest.webSocket, ptmRequest.requestID, featureCollection.toString(), true); /*************/ } catch (JsonParseException e) { System.out.println("can't save json object: " + e.toString()); } } catch (Exception e) { e.printStackTrace(); Log.getInstance().append(Log.FLAG_WARNING, "Generic error"); } finally { cleanup(); } }
From source file:ch.ethz.coss.nervous.pulse.sql.SqlUploadWorker.java
License:Open Source License
@SuppressWarnings("deprecation") @Override// w w w. ja va2 s . com public void run() { // InputStream is; DataInputStream in = null; try { in = new DataInputStream(socket.getInputStream()); boolean connected = true; while (connected) { connected &= !socket.isClosed(); Visual reading = null; JsonObject featureCollection = new JsonObject(); JsonArray features = new JsonArray(); JsonObject feature = null; try { // String json = in.readUTF(); // StringBuffer json = new StringBuffer(); // String tmp; String json = null; try { // while ((tmp = in.read()) != null) { // json.append(tmp); // } ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte buffer[] = new byte[1024]; for (int s; (s = in.read(buffer)) != -1;) { baos.write(buffer, 0, s); } byte result[] = baos.toByteArray(); json = new String(result); // use inputLine.toString(); here it would have whole // source in.close(); } catch (MalformedURLException me) { System.out.println("MalformedURLException: " + me); } catch (IOException ioe) { System.out.println("IOException: " + ioe); } System.out.println("JSON STRING = " + json); System.out.println("JSON Length = " + json.length()); if (json.length() <= 0) continue; reading = new JSONDeserializer<Visual>().deserialize(json, Visual.class); feature = new JsonObject(); feature.addProperty("type", "Feature"); // JsonArray featureList = new JsonArray(); // iterate through your list // for (ListElement obj : list) { // {"geometry": {"type": "Point", "coordinates": // [-94.149, 36.33]} JsonObject point = new JsonObject(); point.addProperty("type", "Point"); // construct a JSONArray from a string; can also use an // array or list JsonArray coord = new JsonArray(); if (reading == null || reading.location == null) continue; else if (reading.location.latnLong[0] == 0 && reading.location.latnLong[1] == 0) continue; coord.add(new JsonPrimitive(new String("" + reading.location.latnLong[0]))); coord.add(new JsonPrimitive(new String("" + reading.location.latnLong[1]))); point.add("coordinates", coord); feature.add("geometry", point); JsonObject properties = new JsonObject(); if (reading.type == 0) { // System.out.println("Reading instance of light"); properties.addProperty("readingType", "" + 0); properties.addProperty("level", "" + ((LightReading) reading).lightVal); } else if (reading.type == 1) { properties.addProperty("readingType", "" + 1); properties.addProperty("level", "" + ((NoiseReading) reading).soundVal); } else if (reading.type == 2) { properties.addProperty("readingType", "" + 2); properties.addProperty("message", "" + ((TextVisual) reading).textMsg); } else { // System.out.println("Reading instance not known"); } properties.addProperty("recordTime", reading.timestamp); properties.addProperty("volatility", reading.volatility); feature.add("properties", properties); features.add(feature); featureCollection.add("features", features); if (reading.volatility != 0) { /***** SQL insert ********/ // Insert data System.out.println("before uploading SQL - reading uuid = " + reading.uuid); System.out.println("Reading volatility = " + reading.volatility); PreparedStatement datastmt = sqlse.getSensorInsertStatement(connection, reading.type); if (datastmt != null) { // System.out.println("datastmt - " + // datastmt.toString()); List<Integer> types = sqlse.getArgumentExpectation((long) reading.type); datastmt.setString(1, reading.uuid); if (reading.type == 0) { datastmt.setLong(2, reading.timestamp); datastmt.setLong(3, reading.volatility); datastmt.setDouble(4, ((LightReading) reading).lightVal); datastmt.setDouble(5, reading.location.latnLong[0]); datastmt.setDouble(6, reading.location.latnLong[1]); } else if (reading.type == 1) { datastmt.setLong(2, reading.timestamp); datastmt.setLong(3, reading.volatility); datastmt.setDouble(4, ((NoiseReading) reading).soundVal); datastmt.setDouble(5, reading.location.latnLong[0]); datastmt.setDouble(6, reading.location.latnLong[1]); } else if (reading.type == 2) { datastmt.setLong(2, reading.timestamp); datastmt.setLong(3, reading.volatility); datastmt.setString(4, ((TextVisual) reading).textMsg); datastmt.setDouble(5, reading.location.latnLong[0]); datastmt.setDouble(6, reading.location.latnLong[1]); } // System.out.println("datastmt after populating - " // + datastmt.toString()); datastmt.addBatch(); datastmt.executeBatch(); datastmt.close(); } /*************/ } } catch (JsonParseException e) { System.out.println("can't save json object: " + e.toString()); } // output the result // System.out.println("featureCollection=" + // featureCollection.toString()); String message = featureCollection.toString(); pSocketServer.sendToAll(message); } } catch (EOFException e) { e.printStackTrace(); Log.getInstance().append(Log.FLAG_WARNING, "EOFException occurred, but ignored it for now."); } catch (IOException e) { e.printStackTrace(); Log.getInstance().append(Log.FLAG_WARNING, "Opening data stream from socket failed"); } catch (Exception e) { e.printStackTrace(); Log.getInstance().append(Log.FLAG_WARNING, "Generic error"); } finally { cleanup(); try { in.close(); in = null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); ; } } }
From source file:ch.ethz.coss.nervous.pulse.WriteJSON.java
License:Open Source License
public static void sendGeoJSON(Socket socket, Object o) { try {//from w w w.j a v a 2 s.c o m Scanner in = new Scanner(socket.getInputStream()); while (!in.nextLine().isEmpty()) ; PrintWriter out = new PrintWriter(socket.getOutputStream()); Visual reading = (Visual) o; JsonObject feature = new JsonObject(); try { feature.addProperty("type", "Feature"); // JsonArray featureList = new JsonArray(); // iterate through your list // for (ListElement obj : list) { // {"geometry": {"type": "Point", "coordinates": [-94.149, // 36.33]} JsonObject point = new JsonObject(); point.addProperty("type", "Point"); // construct a JSONArray from a string; can also use an array or // list JsonArray coord = new JsonArray(); coord.add(new JsonPrimitive(reading.location.latnLong[0])); coord.add(new JsonPrimitive(reading.location.latnLong[1])); point.add("coordinates", coord); feature.add("geometry", point); JsonObject properties = new JsonObject(); if (reading.type == 0) { // System.out.println("Reading instance of light"); properties.addProperty("readingType", "" + 0); properties.addProperty("lightLevel", "" + ((LightReading) reading).lightVal); } else if (reading.type == 1) { properties.addProperty("readingType", "" + 1); properties.addProperty("noiseLevel", "" + ((NoiseReading) reading).soundVal); } else if (reading.type == 2) { properties.addProperty("readingType", "" + 2); properties.addProperty("message", "" + ((TextVisual) reading).textMsg); } else { // System.out.println("Reading instance not known"); } feature.add("properties", properties); // } } catch (JsonParseException e) { // System.out.println("can't save json object: " + // e.toString()); } // output the result // System.out.println("featureCollection=" + feature.toString()); String message = feature.toString(); out.println("HTTP/1.0 200 OK"); out.println("Content-Type: text/json"); out.printf("Content-Length: %d%n", message.length()); out.println("Access-Control-Allow-Origin: *"); out.println(); out.println(message); out.flush(); socket.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:ch.usz.c3pro.c3_pro_android_framework.dataqueue.EncryptedDataQueue.java
License:Open Source License
/** * Decrypts a FHIR resource contained in a json object received from a C3-PRO server. *//*ww w. j av a 2s . co m*/ public IBaseResource decryptResource(JsonObject jsonObject) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException { if (jsonObject.has("symmetric_key") && jsonObject.has("message")) { String keyString = jsonObject.get("symmetric_key").getAsString(); String objectString = jsonObject.get("message").getAsString(); if (!Strings.isNullOrEmpty(keyString) && !Strings.isNullOrEmpty(objectString)) { byte[] keyBytes = Base64.decode(keyString, Base64.DEFAULT); byte[] objectBytes = Base64.decode(objectString, Base64.DEFAULT); SecretKey key = rsaUtility.unwrapKey(keyBytes); byte[] resourceBytes = aesUtility.deCryptData(objectBytes, key); String resourceString = new String(resourceBytes); return Pyro.getFhirContext().newJsonParser().parseResource(resourceString); } } Log.e(Logging.logTag, "The jsonObject could not be decrypted, fields are invalid: " + jsonObject.toString()); return null; }
From source file:client.commands.TwitchAPICommands.java
License:Apache License
@Override public void run() { if (!this.isAllowed()) return;/*from w ww.j a va 2 s.co m*/ if (this.m.getMessage().startsWith("!game")) { String[] arr = this.m.getMessage().split(" ", 2); if (arr.length > 1) { JsonObject innerbody = new JsonObject(); innerbody.addProperty("game", this.m.getMessage().split(" ", 2)[1]); JsonObject obj = new JsonObject(); obj.add("channel", innerbody); System.out.println(obj.toString()); TwitchAPI api = new TwitchAPI(s.getClientid(), s.getOauth()); api.PUT("https://api.twitch.tv/kraken/channels/" + this.m.getChannel(), obj.toString()); } else { TwitchAPI api = new TwitchAPI(s.getClientid(), s.getOauth()); this.mq.offer(new MessageOut(this.m.getChannel().toLowerCase(), api.GET("https://api.twitch.tv/kraken/channels/" + this.m.getChannel()).get("game") .toString())); } } }
From source file:client.utils.CommandsSettings.java
License:Apache License
private void writeDefault() throws IOException { this.fo.mkdir(); FileWriter set = new FileWriter(this.fi); JsonParser parser = new JsonParser(); String defaultLocalization = "{\n" + " \"Commands\": {\n" + " \"points\": \"!points\",\n" + " \"creator\": \"!creator\",\n" + " \"banme\": \"!banme\",\n" + " \"timeoutenemy\": \"!timeoutenemy\",\n" + " \"baconspam\": \"!baconspam\",\n" + " \"game\": \"!game\",\n" + " \"title\": \"!title\"\n" + " },\n" + " \"Points\": {\n" + " \"command_add\" : \"add\",\n" + " \"command_remove\" : \"remove\",\n" + " \"command_get\" : \"get\",\n" + " \"command_addall\" : \"addall\",\n" + " \"available\" : \"Available commands are: !points <add|remove|get|addall>\",\n" + " \"Get\" : {\n" + " \"permission_level\" : \"user\",\n" + " \"message\" : \"%s has %s points!\"\n" + " },\n" + " \"Add\" : {\n" + " \"permission_level\" : \"broadcaster\",\n" + " \"message\" : \"Points successfully added!\"\n" + " },\n" + " \"Remove\" : {\n" + " \"permission_level\" : \"broadcaster\",\n" + " \"message\" : \"Points successfully removed!\"\n" + " },\n" + " \"AddAll\" : {\n" + " \"permission_level\" : \"broadcaster\"\n" + " },\n" + " \"error\" : \"Something went wrong!\"\n" + " },\n" + " \"Creator\": {\n" + " \"permission_level\" : \"creator\",\n" + " \"message\" : \"My creator and owner is Hoffs!\"\n" + " },\n" + " \"TimeoutEnemy\": {\n" + " \"permission_level\" : \"user\",\n" + " \"initiator\" : \"%s 360 Sacrifice had to be made.\",\n" + " \"enemy\" : \"%s 90 You have an enemy.\"\n" + " }\n" + "}"; JsonObject defaultSettings = parser.parse(defaultLocalization).getAsJsonObject(); set.write(defaultSettings.toString()); set.flush();/*from w ww . j a v a 2s .c om*/ set.close(); System.out.println("Please set up your settings first"); System.exit(0); }
From source file:client.utils.Settings.java
License:Apache License
private void writeDefault() throws IOException { this.fo.mkdir(); FileWriter set = new FileWriter(this.fi); JsonParser parser = new JsonParser(); JsonObject defaultSettings = parser.parse( "{\"username\":\"\",\"token\":\"oauth:\", \"clientid\":\"\", \"oauth\":\"\", \"point_increment\":\"10\", \"point_interval\":\"15\", \"channels\":[]}") .getAsJsonObject();//ww w .ja v a 2 s. c o m set.write(defaultSettings.toString()); set.flush(); set.close(); System.out.println("Please set up your settings first"); System.exit(0); }
From source file:clientcommunicator.Server.Cookie.java
private JsonObject getUserJsonObject(JsonElement element, boolean setNew) throws MalformedCookieException { JsonObject jobject = element.getAsJsonObject(); if (!jobject.has("playerID")) { throw new MalformedCookieException(); }/*w ww .j a v a2 s. c o m*/ JsonObject resultingCookie = new JsonObject(); resultingCookie.add("name", jobject.get("name")); resultingCookie.add("password", jobject.get("password")); resultingCookie.add("playerID", jobject.get("playerID")); if (setNew) { try { String realCookie = resultingCookie.toString(); realCookie = java.net.URLEncoder.encode(realCookie, "UTF-8"); this.userInformationString = realCookie; } catch (UnsupportedEncodingException ex) { Logger.getLogger(Cookie.class.getName()).log(Level.SEVERE, null, ex); } } return jobject; }