List of usage examples for com.google.gson JsonElement toString
@Override
public String toString()
From source file:edu.isi.karma.service.json.JsonManager.java
License:Apache License
private static void recursiveParse(JsonElement jse, Element element) { if (jse.isJsonObject()) { JsonObject j = jse.getAsJsonObject(); Set<Entry<String, JsonElement>> set = j.entrySet(); // System.out.println(set.size()); Iterator<Entry<String, JsonElement>> iter = set.iterator(); while (iter.hasNext()) { Entry<String, JsonElement> entry = iter.next(); Element e = new Element(); e.setKey(entry.getKey());//from w ww.jav a 2 s.com // System.out.println("create " + e.getKey()); e.setValue(new ArrayValue()); e.setValueType(ValueType.ARRAY); recursiveParse(entry.getValue(), e); // System.out.println("element " + element.getKey()); e.setParent(element); ((ArrayValue) element.getValue()).getElements().add(e); // System.out.println("e " + e.getKey()); } } else if (jse.isJsonArray()) { JsonArray j = jse.getAsJsonArray(); Iterator<JsonElement> iter = j.iterator(); while (iter.hasNext()) { Element e = new Element(); e.setKey(""); e.setValue(new ArrayValue()); e.setValueType(ValueType.ARRAY); recursiveParse(iter.next(), e); e.setParent(element); ((ArrayValue) element.getValue()).getElements().add(e); } } else if (jse.isJsonPrimitive()) { element.setValueType(ValueType.SINGLE); element.setValue(new SingleValue(jse.toString())); // System.out.println(jse.getAsString()); } }
From source file:edu.ufl.bmi.ontology.DtmJsonProcessor.java
License:Open Source License
private static JsonArray sortForEasyValidation(JsonArray jsonArray) { JsonArray sortedJsonArray = new JsonArray(); List<JsonElement> jsonList = new ArrayList<JsonElement>(); for (int i = 0; i < jsonArray.size(); i++) { jsonList.add(jsonArray.get(i));//w w w. j a v a2 s . c o m } Collections.sort(jsonList, new Comparator<JsonElement>() { /* We'll sort digital objects by title. However, the data formats do not have a title attribute, so if the title does not exist (i.e., either aTitle or bTitle JsonElement is null), then we'll get the name attribute and use it instead. */ public int compare(JsonElement a, JsonElement b) { if (a == null || b == null) { System.err.println(a + "\n\n" + b); } JsonElement aTitle = a.getAsJsonObject().get("content").getAsJsonObject().get("title"); if (aTitle == null) aTitle = a.getAsJsonObject().get("content").getAsJsonObject().get("name"); JsonElement bTitle = b.getAsJsonObject().get("content").getAsJsonObject().get("title"); if (bTitle == null) bTitle = b.getAsJsonObject().get("content").getAsJsonObject().get("name"); if (aTitle == null || bTitle == null) { System.err.println(aTitle + "\t" + bTitle); System.err.println(a + "\n\n" + b); } return aTitle.toString().compareTo(bTitle.toString()); } }); for (int i = 0; i < jsonArray.size(); i++) { sortedJsonArray.add(jsonList.get(i)); } return sortedJsonArray; }
From source file:elsu.database.rowset.EntityDescriptor.java
public EntityDescriptor(String jsonColumns, String jsonRows) throws Exception { Type columnType = new TypeToken<Map<String, ColumnDescriptor>>() { }.getType();/* w ww .ja v a 2 s.c o m*/ this._columns = (Map<String, ColumnDescriptor>) JsonXMLUtils.JSon2Object(jsonColumns, columnType); this._columnsById = setColumnsById(this._columns); this._rows = new ArrayList<RowDescriptor>(); RowDescriptor rd = null; JsonParser parser = new JsonParser(); JsonArray jArray = parser.parse(jsonRows).getAsJsonArray(); for (JsonElement jElement : jArray) { rd = new RowDescriptor(this._columns, this._columnsById, jElement.toString()); this._rows.add(rd); } }
From source file:esiptestbed.mudrod.metadata.pre.ApiHarvester.java
License:Apache License
private void importSingleFileToES(InputStream is) { try {/*from w ww .ja v a 2s . co m*/ String jsonTxt = IOUtils.toString(is); JsonParser parser = new JsonParser(); JsonElement item = parser.parse(jsonTxt); IndexRequest ir = new IndexRequest(props.getProperty("indexName"), props.getProperty("raw_metadataType")).source(item.toString()); es.getBulkProcessor().add(ir); } catch (IOException e) { LOG.error("Error indexing metadata record!", e); } }
From source file:esiptestbed.mudrod.metadata.pre.ApiHarvester.java
License:Apache License
/** * harvestMetadatafromWeb: Harvest metadata from PO.DAAC web service. */// w w w .ja va2 s. c o m private void harvestMetadatafromWeb() { int startIndex = 0; int doc_length = 0; JsonParser parser = new JsonParser(); do { String searchAPI = "https://podaac.jpl.nasa.gov/api/dataset?startIndex=" + Integer.toString(startIndex) + "&entries=10&sortField=Dataset-AllTimePopularity&sortOrder=asc&id=&value=&search="; HttpRequest http = new HttpRequest(); String response = http.getRequest(searchAPI); JsonElement json = parser.parse(response); JsonObject responseObject = json.getAsJsonObject(); JsonArray docs = responseObject.getAsJsonObject("response").getAsJsonArray("docs"); doc_length = docs.size(); File file = new File(props.getProperty(MudrodConstants.RAW_METADATA_PATH)); if (!file.exists()) { if (file.mkdir()) { LOG.info("Directory is created!"); } else { LOG.error("Failed to create directory!"); } } for (int i = 0; i < doc_length; i++) { JsonElement item = docs.get(i); int docId = startIndex + i; File itemfile = new File( props.getProperty(MudrodConstants.RAW_METADATA_PATH) + "/" + docId + ".json"); try (FileWriter fw = new FileWriter(itemfile.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw);) { itemfile.createNewFile(); bw.write(item.toString()); } catch (IOException e) { LOG.error("Error writing metadata to local file!", e); } } startIndex += 10; try { Thread.sleep(100); } catch (InterruptedException e) { LOG.error("Error entering Elasticsearch Mappings!", e); Thread.currentThread().interrupt(); } } while (doc_length != 0); }
From source file:esiptestbed.mudrod.recommendation.pre.ImportMetadata.java
License:Apache License
/** * importToES: Index metadata into elasticsearch from local file directory. * Please make sure metadata have been harvest from web service before * invoking this method./*from w w w.ja va2 s .c o m*/ */ private void importToES() { es.deleteType(props.getProperty("indexName"), props.getProperty("recom_metadataType")); es.createBulkProcessor(); File directory = new File(props.getProperty("raw_metadataPath")); File[] fList = directory.listFiles(); for (File file : fList) { InputStream is; try { is = new FileInputStream(file); try { String jsonTxt = IOUtils.toString(is); JsonParser parser = new JsonParser(); JsonElement item = parser.parse(jsonTxt); IndexRequest ir = new IndexRequest(props.getProperty("indexName"), props.getProperty("recom_metadataType")).source(item.toString()); es.getBulkProcessor().add(ir); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } } es.destroyBulkProcessor(); }
From source file:eu.betaas.service.extendedservice.api.impl.LEZProcessor.java
License:Apache License
public synchronized void managePositionData(JsonObject data) { JsonObject jsonObj;//from w ww. j a va2 s. c o m JsonElement jsonElement; String lat, lon, userId; double latVal, lonVal; mLogger.info("Received position data"); try { JsonObject serviceResult = data.getAsJsonObject(JSON_FIELD_SERVICE_RESULT); if (serviceResult == null) { mLogger.error("Cannot get ServiceResult"); return; } JsonArray dataList = serviceResult.getAsJsonArray(JSON_FIELD_DATALIST); if (dataList == null) { mLogger.error("Cannot get dataList"); return; } // scan all received points for (int i = 0; i < dataList.size(); i++) { jsonObj = dataList.get(i).getAsJsonObject(); if (jsonObj == null) { mLogger.error("Cannot get data element n. " + i); return; } jsonElement = jsonObj.get(JSON_FIELD_USER_ID); if (jsonElement == null) { mLogger.error("Cannot get user ID from element n. " + i); return; } userId = jsonElement.toString(); if (userId == null) { mLogger.error("Got null user ID from element n. " + i); return; } if (userId.startsWith("\"")) userId = userId.substring(1); if (userId.endsWith("\"")) userId = userId.substring(0, userId.length() - 1); if (userId.isEmpty()) { mLogger.error("Got empty user ID from element n. " + i); return; } try { jsonElement = jsonObj.get(JSON_FIELD_LAT); if (jsonElement == null) { mLogger.error("Cannot get lat from element n. " + i); return; } lat = jsonElement.toString(); latVal = Double.parseDouble(lat); jsonElement = jsonObj.get(JSON_FIELD_LON); if (jsonElement == null) { mLogger.error("Cannot get lon from element n. " + i); return; } lon = jsonElement.toString(); lonVal = Double.parseDouble(lon); } catch (Exception efe) { throw new Exception("Invalid numberic conversion on element n." + i + ": " + efe.getMessage()); } processUserPosition(userId, latVal, lonVal); } } catch (Exception e) { mLogger.error("Cannot manage received position data: " + e.getMessage()); e.printStackTrace(); } }
From source file:eu.betaas.service.extendedservice.api.impl.LEZProcessor.java
License:Apache License
public synchronized void manageTrafficData(JsonObject data) { JsonObject jsonObj;//w w w .j a v a2s .c o m JsonElement jsonElement; String carsMinute, lat, lon; double latVal, lonVal; float carsMinuteVal; mLogger.info("Received traffic data"); try { JsonObject serviceResult = data.getAsJsonObject(JSON_FIELD_SERVICE_RESULT); if (serviceResult == null) { mLogger.error("Cannot get ServiceResult"); return; } JsonArray dataList = serviceResult.getAsJsonArray(JSON_FIELD_DATALIST); if (dataList == null) { mLogger.error("Cannot get dataList"); return; } // scan all received elements for (int i = 0; i < dataList.size(); i++) { jsonObj = dataList.get(i).getAsJsonObject(); if (jsonObj == null) { mLogger.error("Cannot get data element n. " + i); return; } try { jsonElement = jsonObj.get(JSON_FIELD_MEASUREMENT); if (jsonElement == null) { mLogger.error("Cannot get measurement from element n. " + i); return; } carsMinute = jsonElement.toString(); if (carsMinute.startsWith("\"")) carsMinute = carsMinute.substring(1); if (carsMinute.endsWith("\"")) carsMinute = carsMinute.substring(0, carsMinute.length() - 1); carsMinuteVal = Float.parseFloat(carsMinute); jsonElement = jsonObj.get(JSON_FIELD_LAT); if (jsonElement == null) { mLogger.error("Cannot get lat from element n. " + i); return; } lat = jsonElement.toString(); latVal = Double.parseDouble(lat); jsonElement = jsonObj.get(JSON_FIELD_LON); if (jsonElement == null) { mLogger.error("Cannot get lon from element n. " + i); return; } lon = jsonElement.toString(); lonVal = Double.parseDouble(lon); } catch (Exception efe) { throw new Exception("Invalid numeric conversion on element n." + i + ": " + efe.getMessage()); } processTrafficIntensity(latVal, lonVal, carsMinuteVal); } } catch (Exception e) { mLogger.error("Cannot manage received traffic data: " + e.getMessage()); } }
From source file:eu.betaas.service.servicemanager.application.RequestManager.java
License:Apache License
/** * @param dataList/*from w w w . j a v a2 s.c o m*/ * @param operator * @return the combined value * @throws Exception if the combination is not possible */ private String combine(JsonArray dataList, JsonElement operator) throws Exception { if ((dataList == null) || (operator == null)) { throw new Exception("null data list / operator"); } int i; JsonObject measure; JsonElement el; String opr = operator.toString(); opr = trim(opr); String value; if (opr == null) throw new Exception("null operator"); if (opr.equalsIgnoreCase("OR")) { //////////////////////////////////// OR ///////////////////////////////// boolean result = false; for (i = 0; i < dataList.size(); i++) { measure = dataList.get(i).getAsJsonObject(); if (measure == null) throw new Exception("One of the measures is null"); el = measure.get("measurement"); if (el == null) throw new Exception("One of the measures is null"); value = el.toString(); value = trim(value); if ((value.equalsIgnoreCase("TRUE")) || (value.equals("1"))) { result = true; break; } else if ((!value.equalsIgnoreCase("FALSE")) && (!value.equals("0"))) { throw new Exception("Unexpected value with operation OR: " + value); } } if (result) return "true"; else return "false"; } else if (opr.equalsIgnoreCase("AND")) { //////////////////////////////////// AND ///////////////////////////////// boolean result = true; for (i = 0; i < dataList.size(); i++) { measure = dataList.get(i).getAsJsonObject(); if (measure == null) throw new Exception("One of the measures is null"); el = measure.get("measurement"); if (el == null) throw new Exception("One of the measures is null"); value = el.toString(); value = trim(value); if ((value.equalsIgnoreCase("FALSE")) || (value.equals("0"))) { result = false; break; } else if ((!value.equalsIgnoreCase("TRUE")) && (!value.equals("1"))) { throw new Exception("Unexpected value with operation OR: " + value); } } if (result) return "true"; else return "false"; } else if (opr.equalsIgnoreCase("AVERAGE")) { //////////////////////////////////// AVERAGE ///////////////////////////////// float result = 0.0f; for (i = 0; i < dataList.size(); i++) { measure = dataList.get(i).getAsJsonObject(); if (measure == null) throw new Exception("One of the measures is null"); el = measure.get("measurement"); if (el == null) throw new Exception("One of the measures is null"); value = el.toString(); value = trim(value); try { result += Float.parseFloat(value); } catch (Exception e) { throw new Exception("Error parsing numeric value for operation AVERAGE: " + value); } } if (i > 0) return Float.toString(result / i); else throw new Exception("Zero values to be averaged"); } else if (opr.equalsIgnoreCase("SUM")) { //////////////////////////////////// SUM ///////////////////////////////// float result = 0.0f; for (i = 0; i < dataList.size(); i++) { measure = dataList.get(i).getAsJsonObject(); if (measure == null) throw new Exception("One of the measures is null"); el = measure.get("measurement"); if (el == null) throw new Exception("One of the measures is null"); value = el.toString(); value = trim(value); try { result += Float.parseFloat(value); } catch (Exception e) { throw new Exception("Error parsing numeric value for operation SUM: " + value); } } return Float.toString(result); } throw new Exception("Requested combination " + opr + " not supported for incoming data"); }
From source file:eu.riscoss.server.AnalysisManager.java
License:Apache License
private String getCustomData(JsonObject o, String id) { if (o == null) return null; o = o.getAsJsonObject();// ww w .j a v a2s . c om if (o == null) return null; JsonElement e = o.get(id); if (e == null) return null; if (e.getAsJsonObject() == null) return null; return e.toString(); }