List of usage examples for com.google.gson JsonArray JsonArray
public JsonArray()
From source file:ch.eitchnet.csvrestendpoint.marshaller.CsvDataToHeaderJsonMarshaller.java
License:Apache License
@Override public JsonObject marshall(CSVParser csvParser) { JsonObject root = new JsonObject(); root.addProperty("msg", "-"); JsonArray data = new JsonArray(); Set<Entry<String, Integer>> header = csvParser.getHeaderMap().entrySet(); for (Entry<String, Integer> entry : header) { data.add(new JsonPrimitive(entry.getKey())); }/*from ww w. jav a 2 s.c o m*/ root.add("data", data); return root; }
From source file:ch.eitchnet.csvrestendpoint.marshaller.CsvDataToJsonMarshaller.java
License:Apache License
@Override public JsonObject marshall(CSVParser csvParser) { // validate any references to column names Map<String, Integer> headerMap = csvParser.getHeaderMap(); validate(headerMap);//from ww w . java2 s . c o m // filter List<CSVRecord> allRecords = new ArrayList<>(); long dataSetSize = 0; for (CSVRecord record : csvParser) { dataSetSize++; if (isSelected(headerMap, record)) allRecords.add(record); } // sort if (StringHelper.isNotEmpty(sortBy)) { Integer columnIndex = headerMap.get(sortBy); if (this.ascending) allRecords.sort((r1, r2) -> r1.get(columnIndex).compareTo(r2.get(columnIndex))); else allRecords.sort((r1, r2) -> r2.get(columnIndex).compareTo(r1.get(columnIndex))); } // paging Paging<CSVRecord> paging = Paging.asPage(allRecords, this.pageSize, this.page); // get page List<CSVRecord> page = paging.getPage(); // build JSON response JsonObject root = new JsonObject(); root.addProperty("msg", "-"); root.addProperty("draw", this.draw); root.addProperty("dataSetSize", dataSetSize); root.addProperty("nrOfElements", paging.getNrOfElements()); if (StringHelper.isNotEmpty(sortBy)) root.addProperty("sortBy", this.sortBy); root.addProperty("ascending", this.ascending); root.addProperty("nrOfPages", paging.getNrOfPages()); root.addProperty("pageSize", paging.getPageSize()); root.addProperty("page", paging.getPageToReturn()); // prune any unwanted columns if (!this.returnFields.isEmpty()) { headerMap.keySet().retainAll(this.returnFields); } // add items JsonArray data = new JsonArray(); for (CSVRecord record : page) { JsonObject element = new JsonObject(); for (Entry<String, Integer> entry : headerMap.entrySet()) { String column = entry.getKey(); String value = record.get(entry.getValue()); element.addProperty(column, value); } data.add(element); } root.add("data", data); return root; }
From source file:ch.eitchnet.csvrestendpoint.marshaller.CsvNamesToJsonMarshaller.java
License:Apache License
public JsonObject marshall(List<String> names) { JsonObject root = new JsonObject(); root.addProperty("msg", "-"); JsonArray data = new JsonArray(); for (String name : names) { data.add(new JsonPrimitive(name)); }/* w w w.ja va2 s . com*/ root.add("data", data); return root; }
From source file:ch.epfl.leb.sass.models.Microscope.java
License:Open Source License
/** * Returns information about the sample fluorophores. * /*w w w.j a v a 2s . c om*/ * @return A JsonObject containing information about the fluorophores. */ public JsonElement toJsonFluorescence() { JsonArray jsonArray = new JsonArray(); for (Fluorophore f : fluorophores) { jsonArray.add(f.toJson()); } return jsonArray; }
From source file:ch.epfl.leb.sass.server.RemoteSimulationServiceHandler.java
License:Open Source License
/** * Returns messages about changes in the simulation state as a JSON string. * /*from w w w. j av a 2 s.c o m*/ * Unlike {@link #toJsonState(int id) toJsonState()}, which returns * information about the *current* state of just the fluorophores, this * method returns the messages from individual simulation components that * contain information about changes in their state that have occurred since * the last time this method was called. * * @param id The simulation ID. * @return A JSON string containing the messages that were recorded. * @throws UnknownSimulationIdException */ @Override public String toJsonMessages(int id) throws UnknownSimulationIdException { Simulator sim = manager.getSimulator(id); if (sim == null) { throw new UnknownSimulationIdException(); } List<Message> messages = sim.getMessages(); JsonArray json = new JsonArray(); for (Message msg : messages) { json.add(msg.toJson()); } try { Gson gson = new Gson(); String jsonString = gson.toJson(json); return jsonString; } catch (Exception ex) { String err = "Unable to convert JSON object to string."; LOGGER.log(Level.SEVERE, err); ex.printStackTrace(); return null; } }
From source file:ch.epfl.leb.sass.simulator.internal.DefaultSimulator.java
License:Open Source License
/** * Returns messages about changes in the simulation state as a JSON object. * /*from w w w.jav a 2 s . c o m*/ * Unlike {@link #toJsonState() toJsonState()}, which returns * information about the *current* state of the simulation, this method * returns the messages from individual simulation components that contain * information about changes in their state that have occurred since the * last time this method was called. * * @return A JSON object containing the simulation messages. */ @Override public JsonElement toJsonMessages() { JsonArray json = new JsonArray(); for (Message msg : this.getMessages()) { json.add(msg.toJson().getAsJsonObject()); } Gson gson = new Gson(); return gson.fromJson(json, JsonArray.class); }
From source file:ch.ethz.coss.nervous.pulse.sql.SqlRequestWorker.java
License:Open Source License
@Override public void run() { try {//w ww . j av a 2s .com 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 ww . j ava2 s .co m*/ 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 ww w . j a va 2s .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.gaps.slasher.views.main.MainController.java
License:Open Source License
/** * To save the state of the software, the tab, the servers and the databases. *//*from w w w. j av a 2 s. c om*/ public void saveState() { try { os = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("save.json"))); Gson jsonEngine = new GsonBuilder().setPrettyPrinting().create(); JsonArray mainArray = new JsonArray(); for (Server s : servers) { JsonObject server = new JsonObject(); server.addProperty("serverDescription", s.getDescription()); server.addProperty("serverDriver", s.getDiverName()); server.addProperty("serverHost", s.getHost()); server.addProperty("serverPort", s.getPort()); JsonArray databases = new JsonArray(); for (Database db : s.getDatabases()) { JsonObject database = new JsonObject(); database.addProperty("databaseDescritpion", db.getDescritpion()); database.addProperty("databaseName", db.getName()); database.addProperty("databaseUsername", db.getUsername()); JsonArray tabsJson = new JsonArray(); tabs.forEach(editorTab -> { if (editorTab.getDatabase() == db) { JsonObject tabJson = new JsonObject(); tabJson.addProperty("tabName", "name"); tabJson.addProperty("moduleName", editorTab.getModuleName()); tabJson.addProperty("content", editorTab.getEditorController().getContent()); tabsJson.add(tabJson); } }); database.add("tabs", tabsJson); databases.add(database); } server.add("databases", databases); mainArray.add(server); } os.write(jsonEngine.toJson(mainArray)); os.flush(); } catch (IOException e) { addToUserCommunication(e.getMessage()); } }