List of usage examples for org.json JSONStringer JSONStringer
public JSONStringer()
From source file:org.sc.probro.servlets.UserListServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {/*from w w w .j av a 2 s. co m*/ UserCredentials creds = new UserCredentials(); String contentType = getContentType(request); String content = null; Broker broker = getBroker(); String ontologyID = null; User[] users = broker.listUsers(creds, ontologyID); if (contentType.equals(CONTENT_TYPE_JSON)) { JSONStringer stringer = new JSONStringer(); try { stringer.object(); stringer.key("vals"); BrokerData.stringJSONArray(stringer, users); stringer.endObject(); } catch (JSONException e) { throw new BrokerException(e); } content = stringer.toString(); } else if (contentType.equals(CONTENT_TYPE_HTML)) { StringWriter stringer = new StringWriter(); PrintWriter writer = new PrintWriter(stringer); User t = new User(); writer.println("<table>"); writer.println(t.writeHTMLRowHeader()); for (User user : users) { writer.println(user.writeHTMLObject(true)); } writer.println("</table>"); content = stringer.toString(); } response.setStatus(HttpServletResponse.SC_OK); response.setContentType(contentType); response.getWriter().println(content); } catch (BrokerException e) { handleException(response, e); } }
From source file:fr.mby.opa.picsimpl.service.BasicPictureFactory.java
protected void loadMetadata(final Picture picture, final BufferedInputStream stream) throws IOException { try {/*from www. jav a2 s . c o m*/ stream.reset(); final Metadata metadata = ImageMetadataReader.readMetadata(stream, false); // Process all metadatas final JSONStringer jsonStringer = new JSONStringer(); // Start main object jsonStringer.object(); final Iterator<Directory> dirIt = metadata.getDirectories().iterator(); while (dirIt.hasNext()) { final Directory dir = dirIt.next(); // Start Directory jsonStringer.key(dir.getName()).object(); final Collection<Tag> dirTags = dir.getTags(); for (final Tag tag : dirTags) { final int tagType = tag.getTagType(); final String tagName = tag.getTagName(); final String tagDesc = tag.getDescription(); // Add Tag jsonStringer.key(tagName + "[" + tagType + "]").value(tagDesc); } // End Directory jsonStringer.endObject(); } // End main object jsonStringer.endObject(); final String jsonMetadata = jsonStringer.toString(); picture.setJsonMetadata(jsonMetadata); // Process specific metadata // Times final Timestamp originalTime = this.findOriginalTime(metadata); picture.setOriginalTime(originalTime); picture.setCreationTime(new Timestamp(System.currentTimeMillis())); } catch (final ImageProcessingException e) { // Unable to process metadata BasicPictureFactory.LOG.warn("Unable to read metadata !", e); } catch (final JSONException e) { // Technical problem BasicPictureFactory.LOG.warn("Problem while converting Metadata to JSON !", e); throw new RuntimeException("Problem while converting Metadata to JSON !", e); } }
From source file:org.sc.probro.servlets.OntologyListServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {/*from w w w . j a va2 s . co m*/ UserCredentials creds = new UserCredentials(); String contentType = getContentType(request); String content = null; Broker broker = getBroker(); Ontology[] onts = broker.listOntologies(creds); if (contentType.equals(CONTENT_TYPE_JSON)) { JSONStringer stringer = new JSONStringer(); try { stringer.object(); stringer.key("vals"); BrokerData.stringJSONArray(stringer, onts); stringer.endObject(); } catch (JSONException e) { throw new BrokerException(e); } content = stringer.toString(); } else if (contentType.equals(CONTENT_TYPE_HTML)) { StringWriter stringer = new StringWriter(); PrintWriter writer = new PrintWriter(stringer); Ontology t = new Ontology(); writer.println("<table>"); writer.println(t.writeHTMLRowHeader()); for (Ontology ont : onts) { writer.println(ont.writeHTMLObject(true)); } writer.println("</table>"); content = stringer.toString(); } response.setStatus(HttpServletResponse.SC_OK); response.setContentType(contentType); response.getWriter().println(content); } catch (BrokerException e) { handleException(response, e); } }
From source file:com.agrn.senqm.network.Message.java
@Override public String toString() { JSONStringer stringer = new JSONStringer(); Set<String> keyValues = values.keySet(); try {// w w w .ja v a2 s . co m stringer.object().key("content").value(content.toString()); for (String key : keyValues) { if (!key.equals("content")) stringer.key(key).value(values.get(key)); } return stringer.endObject().toString(); } catch (JSONException e) { return "{'content': '".concat(content.toString()).concat("'}"); } }
From source file:de.ailis.midi4js.MessageReceiver.java
/** * @see javax.sound.midi.Receiver#send(javax.sound.midi.MidiMessage, long) *//*from w w w . j a va 2 s .com*/ @Override public void send(final MidiMessage message, final long timeStamp) { try { final JSONStringer json = new JSONStringer(); json.object(); json.key("status").value(message.getStatus()); json.key("message"); json.array(); final byte[] data = message.getMessage(); final int max = Math.min(data.length, message.getLength()); for (int i = 0; i < max; i++) json.value(data[i] & 0xff); json.endArray(); if (message instanceof ShortMessage) processShortMessage((ShortMessage) message, json); else if (message instanceof MetaMessage) processMetaMessage((MetaMessage) message, json); else if (message instanceof SysexMessage) processSysexMessage((SysexMessage) message, json); json.endObject(); this.applet.execJSMethod("messageReceived", System.identityHashCode(this), json.toString(), timeStamp); } catch (final JSONException e) { throw new RuntimeException(e.toString(), e); } }
From source file:com.google.blockly.android.control.BlocklyEvent.java
public String toJsonString() throws JSONException { JSONStringer out = new JSONStringer(); out.object();//from w w w. ja v a 2 s . co m out.key(JSON_TYPE); out.value(getTypeName()); if (!TextUtils.isEmpty(mBlockId)) { out.key(JSON_BLOCK_ID); out.value(mBlockId); } if (!TextUtils.isEmpty(mGroupId)) { out.key(JSON_GROUP_ID); out.value(mGroupId); } writeJsonAttributes(out); // Workspace id is not included to reduce size over network. out.endObject(); return out.toString(); }
From source file:org.jwebsocket.plugins.sharedobjects.SharedObjectsPlugIn.java
@Override public void processToken(PlugInResponse aResponse, WebSocketConnector aConnector, Token aToken) { String lType = aToken.getType(); String lNS = aToken.getNS();//ww w.j ava2 s. c o m String lID = aToken.getString("id"); String lDataType = aToken.getString("datatype"); String lValue = aToken.getString("value"); if (lType != null && (lNS == null || lNS.equals(NS_SHARED_OBJECTS))) { Token lResponse = getServer().createResponse(aToken); // create if (lType.equals("create")) { if (log.isDebugEnabled()) { log.debug("Processing 'create'..."); } if (!isDataTypeValid(lDataType, aConnector, lResponse)) { return; } if (alreadyExists(lID, aConnector, lResponse)) { return; } sharedObjects.put(lID, string2Object(lDataType, lValue)); Token lBCT = new Token(lNS, "event"); lBCT.put("name", "created"); lBCT.put("id", lID); lBCT.put("datatype", lDataType); lBCT.put("value", lValue); getServer().broadcastToken(aConnector, lBCT); // destroy } else if (lType.equals("destroy")) { if (log.isDebugEnabled()) { log.debug("Processing 'destroy'..."); } if (!doesContain(lID, aConnector, lResponse)) { return; } sharedObjects.remove(lID); Token lBCT = new Token(lNS, "event"); lBCT.put("name", "destroyed"); lBCT.put("id", lID); getServer().broadcastToken(aConnector, lBCT); // get } else if (lType.equals("get")) { if (log.isDebugEnabled()) { log.debug("Processing 'get'..."); } if (!doesContain(lID, aConnector, lResponse)) { return; } Object lObj = sharedObjects.get(lID); lResponse.put("id", lID); lResponse.put("result", lObj.toString()); // put } else if (lType.equals("update")) { if (log.isDebugEnabled()) { log.debug("Processing 'update'..."); } if (!isDataTypeValid(lDataType, aConnector, lResponse)) { return; } sharedObjects.put(lID, string2Object(lDataType, lValue)); Token lBCT = new Token(lNS, "event"); lBCT.put("name", "updated"); lBCT.put("id", lID); lBCT.put("datatype", lDataType); lBCT.put("value", lValue); getServer().broadcastToken(aConnector, lBCT); // init } else if (lType.equals("init")) { if (log.isDebugEnabled()) { log.debug("Processing 'init'..."); } Token lBCT = new Token(lNS, "event"); lBCT.put("name", "init"); String lData = null; try { JSONStringer jsonStringer = new JSONStringer(); // start main object jsonStringer.object(); // iterate through all items (fields) of the token Iterator<String> lIterator = sharedObjects.getKeys().iterator(); while (lIterator.hasNext()) { String lKey = lIterator.next(); Object lVal = sharedObjects.get(lKey); if (lVal instanceof Collection) { jsonStringer.key(lKey).array(); for (Object item : (Collection) lVal) { jsonStringer.value(item); } jsonStringer.endArray(); } else { jsonStringer.key(lKey).value(lVal); } } // end main object jsonStringer.endObject(); lData = jsonStringer.toString(); } catch (JSONException ex) { log.error(ex.getClass().getSimpleName() + ": " + ex.getMessage()); } lBCT.put("value", lData); getServer().sendToken(aConnector, lBCT); } else { log.warn("Invalid command " + lType + " received..."); lResponse.put("code", -1); lResponse.put("msg", "invalid type '" + lType + "'"); } getServer().sendToken(aConnector, lResponse); } }
From source file:cc.metapro.openct.utils.ExcelHelper.java
public static String tableToJson(@NonNull String table) throws JSONException { String[] rows = table.split("\n"); String[][] tableContents = new String[rows.length][]; int i = 0;//from ww w.j a v a2 s. c o m for (String row : rows) { String[] cols = row.split("\t"); tableContents[i++] = cols; } String[] headers = null; if (tableContents.length > 0) { headers = tableContents[0]; } if (headers == null) { return ""; } JSONStringer stringer = new JSONStringer(); stringer.array(); for (i = 1; i < tableContents.length; i++) { stringer.object(); for (int j = 0; j < tableContents[i].length && j < headers.length; j++) { stringer.key(headers[j].trim()).value(tableContents[i][j]); } stringer.endObject(); } stringer.endArray(); return stringer.toString(); }
From source file:org.sc.probro.servlets.TextQueryServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {/*w ww. j av a2 s . c o m*/ String searchTerm = getRequiredParam(request, "search", String.class); String contentType = getContentType(request); String[] ontologies = getOptionalParam(request, "ontology_id", String[].class); UserCredentials user = new UserCredentials(); Broker broker = getBroker(); try { SearchResult[] results = broker.query(user, searchTerm, ontologies); response.setStatus(HttpServletResponse.SC_OK); response.setContentType(contentType); if (contentType.equals(CONTENT_TYPE_JSON)) { JSONStringer stringer = new JSONStringer(); stringer.array(); for (SearchResult res : results) { res.stringJSON(stringer); } stringer.endArray(); response.getWriter().println(stringer.toString()); } else if (contentType.equals(CONTENT_TYPE_HTML)) { PrintWriter writer = response.getWriter(); writer.println("<table>"); writer.println("<tr>" + "<th>ID</th>" + "<th>Type</th>" + "<th>Descriptions</th>" + "<th>Accessions</th>" + "</tr>"); for (SearchResult res : results) { writer.println(renderHitAsHTML(res)); } writer.println("</table>"); } else { throw new BadRequestException(String.format("Unsupported content type: %s", contentType)); } } catch (JSONException e) { throw new BrokerException(e); } finally { broker.close(); } } catch (BrokerException e) { handleException(response, e); return; } }
From source file:com.vaynberg.wicket.select2.Settings.java
public CharSequence toJson() { try {/* w w w. ja va 2s . c o m*/ JSONStringer writer = new JSONStringer(); writer.object(); Json.writeObject(writer, "minimumInputLength", minimumInputLength); Json.writeObject(writer, "minimumResultsForSearch", minimumResultsForSearch); Json.writeObject(writer, "maximumSelectionSize", maximumSelectionSize); Json.writeObject(writer, "placeholder", placeholder); Json.writeObject(writer, "allowClear", allowClear); Json.writeObject(writer, "multiple", multiple); Json.writeObject(writer, "closeOnSelect", closeOnSelect); Json.writeFunction(writer, "id", id); Json.writeFunction(writer, "matcher", matcher); Json.writeFunction(writer, "tokenizer", tokenizer); Json.writeFunction(writer, "formatSelection", formatSelection); Json.writeFunction(writer, "formatResult", formatResult); Json.writeFunction(writer, "formatNoMatches", formatNoMatches); Json.writeFunction(writer, "formatInputTooShort", formatInputTooShort); Json.writeFunction(writer, "formatResultCssClass", formatResultCssClass); Json.writeFunction(writer, "formatSelectionTooBig", formatSelectionTooBig); Json.writeFunction(writer, "formatLoadMore", formatLoadMore); Json.writeFunction(writer, "formatSearching", formatSearching); Json.writeFunction(writer, "createSearchChoice", createSearchChoice); Json.writeFunction(writer, "initSelection", initSelection); Json.writeFunction(writer, "query", query); Json.writeObject(writer, "width", width); Json.writeObject(writer, "openOnEnter", openOnEnter); Json.writeObject(writer, "containerCss", containerCss); Json.writeObject(writer, "containerCssClass", containerCssClass); Json.writeObject(writer, "dropdownCss", dropdownCss); Json.writeObject(writer, "dropdownCssClass", dropdownCssClass); Json.writeObject(writer, "separator", separator); Json.writeObject(writer, "tokenSeparators", tokenSeparators); writer.key("ajax"); ajax.toJson(writer); Json.writeFunction(writer, "data", data); Json.writeFunction(writer, "tags", tags); writer.endObject(); return writer.toString(); } catch (JSONException e) { throw new RuntimeException("Could not convert Select2 settings object to Json", e); } }