List of usage examples for org.json.simple JSONObject writeJSONString
public void writeJSONString(Writer out) throws IOException
From source file:org.sglover.alfrescoextensions.common.identity.ServerIdentityImpl.java
private Data createData(File syncFile) throws IOException { String id = UUID.randomUUID().toString(); Data data = new Data(id); JSONObject dataObject = toJSON(data); Writer writer = new FileWriter(syncFile); try {// w ww. j av a 2 s . c om dataObject.writeJSONString(writer); } finally { if (writer != null) { writer.close(); } } return data; }
From source file:org.tridas.io.formats.lipdmetadata.LiPDMetadataFile.java
@SuppressWarnings("unchecked") protected String getJSONFileString() { JSONObject root = new JSONObject(); // ROOT// w w w.java 2s . c o m root.put("@context", "context.jsonld"); root.put("dataSetName", defaults.getStringDefaultValue(DefaultFields.DATA_SET_NAME).getStringValue()); root.put("archiveType", "Tree rings"); root.put("investigators", defaults.getStringDefaultValue(DefaultFields.INVESTIGATORS).getStringValue()); root.put("dataDOI", defaults.getStringDefaultValue(DefaultFields.DATA_DOI).getStringValue()); root.put("version", defaults.getStringDefaultValue(DefaultFields.VERSION).getStringValue()); // FUNDING JSONObject funding = new JSONObject(); funding.put("agency", null); funding.put("grant", null); root.put("funding", funding); // PUB //JSONObject pub = new JSONObject(); //JSONObject author = new JSONObject(); // GEO JSONObject geo = new JSONObject(); geo.put("type", "Feature"); if (defaults.getDoubleDefaultValue(DefaultFields.LONGITUDE).getValue() != null && defaults.getDoubleDefaultValue(DefaultFields.LATITUDE).getValue() != null) { JSONObject geometry = new JSONObject(); geometry.put("type", "Point"); ArrayList<Double> coords = new ArrayList<Double>(); coords.add(defaults.getDoubleDefaultValue(DefaultFields.LONGITUDE).getValue()); coords.add(defaults.getDoubleDefaultValue(DefaultFields.LATITUDE).getValue()); if (defaults.getDoubleDefaultValue(DefaultFields.ELEVATION).getValue() != null) { coords.add(defaults.getDoubleDefaultValue(DefaultFields.ELEVATION).getValue()); } geometry.put("coordinates", coords); geo.put("geometry", geometry); } JSONObject properties = new JSONObject(); properties.put("siteName", defaults.getStringDefaultValue(DefaultFields.SITE_NAME).getStringValue()); geo.put("properties", properties); root.put("geo", geo); //PaleoData JSONObject paleoData = new JSONObject(); paleoData.put("paleoDataTableName", "data"); paleoData.put("filename", "lipd-data.csv"); JSONArray columns = new JSONArray(); JSONObject col1 = new JSONObject(); col1.put("number", 1); col1.put("parameter", "year"); col1.put("parameterType", "measured"); col1.put("description", "calendar year AD"); col1.put("units", " AD"); col1.put("datatype", "csvw:NumericFormat"); columns.add(col1); int col = 1; for (TridasValues valuegroup : values) { col++; String param = TridasUtils.controlledVocToString(valuegroup.getVariable()); String units = TridasUtils.controlledVocToString(valuegroup.getUnit()); JSONObject datacol = new JSONObject(); datacol.put("number", col); datacol.put("parameter", param); datacol.put("parameterType", "measured"); datacol.put("units", units); datacol.put("datatype", "csvw:NumericFormat"); columns.add(datacol); } paleoData.put("columns", columns); root.put("paleoData", paleoData); // Output JSON try { StringWriter swriter = new StringWriter(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonParser jp = new JsonParser(); root.writeJSONString(swriter); JsonElement je = jp.parse(swriter.getBuffer().toString()); return gson.toJson(je); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
From source file:org.tridas.io.formats.tridasjson.TridasJSONFile.java
@SuppressWarnings("unchecked") @Override//from w w w . j ava 2s . c om public String[] saveToString() { if (projects == null) { return null; } boolean gotData = false; StringWriter swriter = new StringWriter(); JSONObject root = new JSONObject(); String labcode = ""; for (TridasProject project : projects) { for (TridasObject object : project.getObjects()) { try { labcode = TridasUtils.getGenericFieldByName(object, "tellervo.objectLabCode").getValue(); } catch (NullPointerException e) { labcode = object.getTitle(); } ArrayList<TridasElement> elementList = TridasUtils.getElementList(object); for (TridasElement element : elementList) { labcode += "-" + element.getTitle(); for (TridasSample sample : element.getSamples()) { labcode += "-" + sample.getTitle(); for (TridasRadius radius : sample.getRadiuses()) { labcode += "-" + radius.getTitle(); for (TridasMeasurementSeries measurementseries : radius.getMeasurementSeries()) { labcode += "-" + measurementseries.getTitle(); for (TridasValues valuesgroup : measurementseries.getValues()) { ArrayList<Integer> data = new ArrayList<Integer>(); for (TridasValue value : valuesgroup.getValues()) { data.add(Integer.parseInt(value.getValue())); } JSONObject output = new JSONObject(); writeProjectToJSON(output, project); writeObjectToJSON(output, object); writeElementToJSON(output, element); writeSampleToJSON(output, sample); writeRadiusToJSON(output, radius); writeSeriesToJSON(output, measurementseries); String variable = ""; if (valuesgroup.isSetVariable()) { if (valuesgroup.getVariable().isSetNormalTridas()) { if (measurementseries.getValues().size() > 1) { labcode += "-" + valuesgroup.getVariable().getNormalTridas().value(); variable = "-" + valuesgroup.getVariable().getNormalTridas().value(); } output.put("series.values.variable", valuesgroup.getVariable().getNormalTridas().value()); } else if (valuesgroup.getVariable().isSetNormal()) { if (measurementseries.getValues().size() > 1) { labcode += "-" + valuesgroup.getVariable().getNormal(); variable = "-" + valuesgroup.getVariable().getNormal(); } output.put("series.values.variable", valuesgroup.getVariable().getNormal()); } else { if (measurementseries.getValues().size() > 1) { labcode += "-" + valuesgroup.getVariable().getValue(); variable = "-" + valuesgroup.getVariable().getValue(); } output.put("series.values.variable", valuesgroup.getVariable().getValue()); } } else { output.put("series.values.variable", "unknown"); } if (valuesgroup.isSetUnit()) { if (valuesgroup.getUnit().isSetNormalTridas()) { output.put("series.values.units", valuesgroup.getUnit().getNormalTridas().value()); } else if (valuesgroup.getUnit().isSetNormal()) { output.put("series.values.units", valuesgroup.getUnit().getNormal().toString()); } else { output.put("series.values.units", valuesgroup.getUnit().getValue().toString()); } } else { output.put("series.units", "unitless"); } output.put("series.values", data); String key = getUniqueChildKey(root, measurementseries.getIdentifier().getValue() + variable, 0); root.put(key, output); gotData = true; } } } } } } // DERIVED SERIES for (TridasDerivedSeries derivedSeries : project.getDerivedSeries()) { labcode += derivedSeries.getTitle(); for (TridasValues valuesgroup : derivedSeries.getValues()) { ArrayList<Integer> data = new ArrayList<Integer>(); for (TridasValue value : valuesgroup.getValues()) { data.add(Integer.parseInt(value.getValue())); } JSONObject output = new JSONObject(); writeProjectToJSON(output, project); writeSeriesToJSON(output, derivedSeries); String variable = ""; if (valuesgroup.isSetVariable()) { if (valuesgroup.getVariable().isSetNormalTridas()) { if (derivedSeries.getValues().size() > 1) { labcode += "-" + valuesgroup.getVariable().getNormalTridas().value(); variable = "-" + valuesgroup.getVariable().getNormalTridas().value(); } output.put("series.values.variable", valuesgroup.getVariable().getNormalTridas().value()); } else if (valuesgroup.getVariable().isSetNormal()) { if (derivedSeries.getValues().size() > 1) { labcode += "-" + valuesgroup.getVariable().getNormal(); variable = "-" + valuesgroup.getVariable().getNormal(); } output.put("series.values.variable", valuesgroup.getVariable().getNormal()); } else { if (derivedSeries.getValues().size() > 1) { labcode += "-" + valuesgroup.getVariable().getValue(); variable = "-" + valuesgroup.getVariable().getValue(); } output.put("series.values.variable", valuesgroup.getVariable().getValue()); } } else { output.put("series.values.variable", "unknown"); } if (valuesgroup.isSetUnit()) { if (valuesgroup.getUnit().isSetNormalTridas()) { output.put("series.values.units", valuesgroup.getUnit().getNormalTridas().value()); } else if (valuesgroup.getUnit().isSetNormal()) { output.put("series.values.units", valuesgroup.getUnit().getNormal().toString()); } else { output.put("series.values.units", valuesgroup.getUnit().getValue().toString()); } } else { output.put("series.units", "unitless"); } output.put("series.values", data); root.put(derivedSeries.getIdentifier().getValue() + variable, output); gotData = true; } } } if (!gotData) { return "{}".split("\n"); } try { Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonParser jp = new JsonParser(); root.writeJSONString(swriter); JsonElement je = jp.parse(swriter.getBuffer().toString()); String prettyJsonString = gson.toJson(je); return prettyJsonString.split("\n"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
From source file:Server.aws.yulei.SQSOperation.java
public static void receiveSQS() { AWSCredentials credentials = null;//from w ww . ja v a 2 s . com try { credentials = new ProfileCredentialsProvider("default").getCredentials(); } catch (Exception e) { throw new AmazonClientException("Cannot load the credentials from the credential profiles file. " + "Please make sure that your credentials file is at the correct " + "location (/Users/daniel/.aws/credentials), and is in valid format.", e); } AmazonSQS sqs = new AmazonSQSClient(credentials); Region usWest2 = Region.getRegion(Regions.US_EAST_1); sqs.setRegion(usWest2); System.out.println("==========================================="); System.out.println("Getting Started with Amazon SQS"); System.out.println("===========================================\n"); try { // Create a queue System.out.println("Creating a new SQS queue called MyQueue.\n"); //CreateQueueRequest createQueueRequest = new CreateQueueRequest("MyQueue"); String myQueueUrl = "https://sqs.us-east-1.amazonaws.com/659322195879/MyQueue"; // List queues System.out.println("Receiving messages from MyQueue.\n"); ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl); List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages(); for (Message message : messages) { String realData = message.getBody(); AlchemyAPI alchemyObj = AlchemyAPI .GetInstanceFromString("a47635756e657c0dac0bc2d282dbde377de01513"); JSONParser parser = new JSONParser(); JSONObject decodeObj = (JSONObject) parser.parse(realData); String content = (String) decodeObj.get("content"); // load text String text = content; // analyze text Document doc = alchemyObj.TextGetTextSentiment(text); String score = "0.00000"; // parse XML result // String sentiment = doc.getElementsByTagName("type").item(0).getTextContent(); // score = doc.getElementsByTagName("score").item(0).getTextContent(); decodeObj.put("score", score); decodeObj.put("sentiment", "Positive"); StringWriter sw = new StringWriter(); decodeObj.writeJSONString(sw); String jsonText = sw.toString(); SNSPushToGCM.push(jsonText); } } catch (Exception e) { Thread.currentThread().interrupt(); } }
From source file:spms.client.ActiveGame.java
public void joinToGame(int g) { //this method sends game data that chosen by client to join it game = games.get(g);//from w ww . j av a 2 s . com try { JSONObject obj = new JSONObject(); obj.put("gameId", game.getGameId()); StringWriter out = new StringWriter(); obj.writeJSONString(out); String jsonText = out.toString(); session.send(SysConst.JOIN_TO_GAME + jsonText); setConnection(); String data = ""; data = session.receive(); if (data.startsWith(SysConst.DOMAIN_FILE)) { data = data.substring(4); data = data.replace(SysConst.ENDL, "\n"); domainfile = data; new File(game.getGameName()).mkdirs(); try { FileOutputStream f = new FileOutputStream(game.getGameName() + "/domain.pddl"); f.write(data.getBytes()); f.close(); } catch (IOException ex) { System.err.println(ex.getMessage()); } //System.out.println(data); } // TODO: write generator file on storage } catch (IOException ex) { Logger.getLogger(CreateGame.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:spms.client.CreateGame.java
public void sendGame() { //Through this method it's called Method send which in class TCPClient and it's send the game data that chosen by client try {// ww w.j av a 2s.c om JSONObject obj = new JSONObject(); obj.put("gameId", game.getGameId()); StringWriter out = new StringWriter(); obj.writeJSONString(out); String jsonText = out.toString(); session.send(SysConst.SEND_CREATED_GAME + jsonText); //setConnection(); String data = ""; data = session.receive(); if (data.startsWith(SysConst.DOMAIN_FILE)) { data = data.substring(4); data = data.replace(SysConst.ENDL, "\n"); domainfile = data; new File(game.getGameName()).mkdirs(); try { FileOutputStream f = new FileOutputStream(game.getGameName() + "/domain.pddl"); f.write(data.getBytes()); f.close(); } catch (IOException ex) { System.err.println(ex.getMessage()); } //System.out.println(data); } // TODO: write generator file on storage } catch (IOException ex) { Logger.getLogger(CreateGame.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:test.DBConnectionTest.java
public static void getJSON() throws IOException { DBConnection conn = DBConnection.getConnection(); String word = "Help"; ArrayList defs = conn.getDefinition(word); Iterator<Definition> it = defs.iterator(); JSONArray defList = new JSONArray(); while (it.hasNext()) { Definition d = (Definition) it.next(); JSONObject obj = new JSONObject(); obj.put("type", d.getType()); obj.put("definition", d.getDefinition()); defList.add(obj);/*from ww w.j a v a 2 s . c o m*/ } JSONObject mainObj = new JSONObject(); mainObj.put(word, defList); StringWriter out = new StringWriter(); mainObj.writeJSONString(out); String jsonText = out.toString(); System.out.print(jsonText); }
From source file:uk.ac.susx.tag.method51.core.organise.subprocess.JVMInstance.java
private void saveMeta(JSONObject meta) throws IOException { meta.writeJSONString(new OutputStreamWriter(new FileOutputStream(file(META_FILENAME)), "UTF-8")); }
From source file:us.mn.state.health.lims.common.provider.query.AllTestsForSampleTypeProvider.java
@Override public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String sampleTypeId = request.getParameter("sampleTypeId"); String jResult;/*from w w w . j a va 2 s . co m*/ JSONObject jsonResult = new JSONObject(); String jString; if (GenericValidator.isBlankOrNull(sampleTypeId)) { jResult = INVALID; jString = "Internal error, please contact Admin and file bug report"; } else { jResult = createJsonGroupedTestNames(sampleTypeId, jsonResult); StringWriter out = new StringWriter(); try { jsonResult.writeJSONString(out); jString = out.toString(); } catch (IOException e) { e.printStackTrace(); jResult = INVALID; jString = "Internal error, please contact Admin and file bug report"; } catch (IllegalStateException e) { e.printStackTrace(); jResult = INVALID; jString = "Internal error, please contact Admin and file bug report"; } } ajaxServlet.sendData(jString, jResult, request, response); }
From source file:us.mn.state.health.lims.common.provider.query.EntityNamesProvider.java
@Override public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("entityId"); String entityName = request.getParameter("entityName"); String jResult;/*from w w w . j a v a 2 s . c om*/ JSONObject jsonResult = new JSONObject(); String jString; if (GenericValidator.isBlankOrNull(id) || GenericValidator.isBlankOrNull(entityName)) { jResult = INVALID; jString = "Internal error, please contact Admin and file bug report"; } else { jResult = createJsonTestNames(id, entityName, jsonResult); StringWriter out = new StringWriter(); try { jsonResult.writeJSONString(out); jString = out.toString(); } catch (IOException e) { e.printStackTrace(); jResult = INVALID; jString = "Internal error, please contact Admin and file bug report"; } catch (IllegalStateException e) { e.printStackTrace(); jResult = INVALID; jString = "Internal error, please contact Admin and file bug report"; } } ajaxServlet.sendData(jString, jResult, request, response); }