List of usage examples for org.json JSONWriter JSONWriter
public JSONWriter(Writer w)
From source file:charitypledge.Pledge.java
public void JsonWrite(String[] args) { String[] values = args;// w ww.j a v a 2 s .co m JSONObject obj = new JSONObject(); JSONArray objArray = new JSONArray(); try { if (args == null || values.length == 0) { throw new Exception("Noting to write to file"); } else { String title = ""; String value = ""; for (int i = (values.length - 1); i >= 0; i--) { if ((i % 2) == 0) { title = values[i]; obj.put(title, value); } else { value = values[i]; } } objArray.put(obj); } try { try { InputStream foo = new FileInputStream(JSONFile); JSONTokener t = new JSONTokener(foo); JSONObject json = new JSONObject(t); foo.close(); FileWriter file = new FileWriter(JSONFile); json.append("contributors", obj); file.write(json.toString(5)); file.close(); tableRefresh(); } catch (FileNotFoundException e) { JSONWriter jsonWriter; try { jsonWriter = new JSONWriter(new FileWriter(JSONFile)); jsonWriter.object(); jsonWriter.key("contributors"); jsonWriter.array(); jsonWriter.endArray(); jsonWriter.endObject(); InputStream foo = new FileInputStream(JSONFile); JSONTokener t = new JSONTokener(foo); JSONObject json = new JSONObject(t); foo.close(); FileWriter file = new FileWriter(JSONFile); json.append("contributors", obj); file.write(json.toString(5)); file.close(); tableRefresh(); } catch (IOException f) { e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { int pic = JOptionPane.ERROR_MESSAGE; JOptionPane.showMessageDialog(null, e, "", pic); } }
From source file:com.google.enterprise.connector.db.diffing.JsonDocument.java
public String toJson() { // JSON does not support custom serialization, so we have to find // the InputStreamFactory for the content and serialize it // ourselves. This could be cleaner if we supported toString on the // InputStreamFactory implementations, but that would mean less // control over when the LOB was materialized in memory. try {//from w ww . j ava2 s.c o m StringWriter buffer = new StringWriter(); JSONWriter writer = new JSONWriter(buffer); writer.object(); for (String name : JSONObject.getNames(jsonObject)) { writer.key(name).value(toJson(name, jsonObject.get(name))); } writer.endObject(); return buffer.toString(); } catch (IOException e) { throw new SnapshotRepositoryRuntimeException("Error serializing document " + objectId, e); } catch (JSONException e) { throw new SnapshotRepositoryRuntimeException("Error serializing document " + objectId, e); } }
From source file:org.sc.probro.servlets.SkeletonServlet.java
public static void raiseInternalError(HttpServletResponse response, Throwable t) throws IOException { StringWriter stringer = new StringWriter(); JSONWriter writer = new JSONWriter(stringer); int errorCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; int httpStatusCode = errorCode; try {//ww w . j av a 2s.c o m String msg = t.getMessage(); writer.object().key("error_code").value(errorCode).key("error_name") .value(BrokerException.ERROR_NAMES.get(errorCode)).key("error_description").value(msg) .endObject(); String errorMessage = stringer.toString(); Log.warn(t); Log.warn(errorMessage); response.sendError(httpStatusCode, errorMessage); } catch (JSONException e) { Log.warn(e); Log.warn(t); response.sendError(httpStatusCode, t.getMessage()); } }
From source file:org.sc.probro.servlets.SkeletonServlet.java
public static void raiseException(HttpServletResponse response, int httpStatusCode, int errorCode, String msg) throws IOException { StringWriter stringer = new StringWriter(); JSONWriter writer = new JSONWriter(stringer); try {// w w w . jav a2s .co m writer.object().key("error_code").value(errorCode).key("error_name").value("").key("error_description") .value(msg).endObject(); String errorMessage = stringer.toString(); Log.warn(errorMessage); response.sendError(httpStatusCode, errorMessage); } catch (JSONException e) { Log.warn(e); Log.warn(msg); response.sendError(httpStatusCode, msg); } }
From source file:uk.org.rivernile.edinburghbustracker.server.livedata.LiveBusStopData.java
/** * Get all of the bus stop information available in this object and output * it in JSON format to the supplied Writer stream. * * @param out The stream to write the JSON text to. *///ww w . j a v a 2 s. c o m public void writeJSONToStream(final Writer out) { if (out == null) throw new IllegalArgumentException("The Writer object" + " cannot be null."); JSONWriter jw = new JSONWriter(out); try { jw.object().key("stopCode").value(thisStopCode).key("stopName").value(thisStopName).key("services") .array(); for (BusService s : busServices) { jw.object().key("serviceName").value(s.getServiceName()).key("route").value(s.getRoute()) .key("buses").array(); for (LiveBus b : s.buses) { jw.object().key("destination").value(b.getDestination()).key("arrivalTime") .value(b.getArrivalTime()).key("accessible").value(b.getAccessible()).endObject(); } jw.endArray().endObject(); } jw.endArray().endObject(); } catch (JSONException e) { System.err.println("A JSON exception has occurred. The exception " + "reported was:"); System.err.println(e.toString()); } }
From source file:com.comcast.cqs.persistence.CQSMessagePartitionedCassandraPersistence.java
private String getMessageJSON(CQSMessage message) throws JSONException { Writer writer = new StringWriter(); JSONWriter jw = new JSONWriter(writer); jw = jw.object();/*w w w . j a v a 2 s. co m*/ jw.key("MessageId").value(message.getMessageId()); jw.key("MD5OfBody").value(message.getMD5OfBody()); jw.key("Body").value(message.getBody()); if (message.getAttributes() == null) { message.setAttributes(new HashMap<String, String>()); } if (!message.getAttributes().containsKey(CQSConstants.SENT_TIMESTAMP)) { message.getAttributes().put(CQSConstants.SENT_TIMESTAMP, "" + System.currentTimeMillis()); } if (!message.getAttributes().containsKey(CQSConstants.APPROXIMATE_RECEIVE_COUNT)) { message.getAttributes().put(CQSConstants.APPROXIMATE_RECEIVE_COUNT, "0"); } if (message.getAttributes() != null) { for (String key : message.getAttributes().keySet()) { String value = message.getAttributes().get(key); if (value == null || value.isEmpty()) { value = ""; } jw.key(key).value(value); } } if (message.getMessageAttributes() != null && message.getMessageAttributes().size() > 0) { jw.key("MD5OfMessageAttributes").value(message.getMD5OfMessageAttributes()); jw.key("MessageAttributes"); jw.object(); for (String key : message.getMessageAttributes().keySet()) { jw.key(key); jw.object(); CQSMessageAttribute messageAttribute = message.getMessageAttributes().get(key); if (messageAttribute.getStringValue() != null) { jw.key("StringValue").value(messageAttribute.getStringValue()); } else if (messageAttribute.getBinaryValue() != null) { jw.key("BinaryValue").value(messageAttribute.getBinaryValue()); } jw.key("DataType").value(messageAttribute.getDataType()); jw.endObject(); } jw.endObject(); } jw.endObject(); return writer.toString(); }
From source file:org.qi4j.entitystore.sql.SQLEntityStoreMixin.java
protected void writeEntityState(DefaultEntityState state, Writer writer, String version) throws EntityStoreException { try {/*w w w. j a v a 2 s .c om*/ JSONWriter json = new JSONWriter(writer); JSONWriter properties = json.object().key("identity").value(state.identity().identity()) .key("application_version").value(application.version()).key("type") .value(state.entityDescriptor().entityType().type().name()).key("version").value(version) .key("modified").value(state.lastModified()).key("properties").object(); EntityType entityType = state.entityDescriptor().entityType(); for (PropertyType propertyType : entityType.properties()) { Object value = state.properties().get(propertyType.qualifiedName()); json.key(propertyType.qualifiedName().name()); if (value == null) { json.value(null); } else { propertyType.type().toJSON(value, json); } } JSONWriter associations = properties.endObject().key("associations").object(); for (Map.Entry<QualifiedName, EntityReference> stateNameEntityReferenceEntry : state.associations() .entrySet()) { EntityReference value = stateNameEntityReferenceEntry.getValue(); associations.key(stateNameEntityReferenceEntry.getKey().name()) .value(value != null ? value.identity() : null); } JSONWriter manyAssociations = associations.endObject().key("manyassociations").object(); for (Map.Entry<QualifiedName, List<EntityReference>> stateNameListEntry : state.manyAssociations() .entrySet()) { JSONWriter assocs = manyAssociations.key(stateNameListEntry.getKey().name()).array(); for (EntityReference entityReference : stateNameListEntry.getValue()) { assocs.value(entityReference.identity()); } assocs.endArray(); } JSONWriter namedAssociations = associations.endObject().key("namedassociations").object(); for (Map.Entry<QualifiedName, Map<String, EntityReference>> stateNameListEntry : state .namedAssociations().entrySet()) { JSONWriter assocs = namedAssociations.key(stateNameListEntry.getKey().name()).object(); Map<String, EntityReference> value = stateNameListEntry.getValue(); for (Map.Entry<String, EntityReference> entry : value.entrySet()) { assocs.key(entry.getKey()).value(entry.getValue()); } assocs.endObject(); } manyAssociations.endObject().endObject(); } catch (JSONException e) { throw new EntityStoreException("Could not store EntityState", e); } }
From source file:org.mapfish.print.servlet.MapPrinterServlet.java
/** * Create the PDF and returns to the client (in JSON) the URL to get the PDF. *///from ww w .j a v a 2s.com protected void createPDF(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String basePath) throws ServletException { TempFile tempFile = null; try { purgeOldTemporaryFiles(); String spec = getSpecFromPostBody(httpServletRequest); tempFile = doCreatePDFFile(spec, httpServletRequest); if (tempFile == null) { error(httpServletResponse, "Missing 'spec' parameter", 500); return; } } catch (Throwable e) { deleteFile(tempFile); error(httpServletResponse, e); return; } final String id = generateId(tempFile); httpServletResponse.setContentType("application/json; charset=utf-8"); PrintWriter writer = null; try { writer = httpServletResponse.getWriter(); JSONWriter json = new JSONWriter(writer); json.object(); { json.key("getURL").value(basePath + "/" + id + TEMP_FILE_SUFFIX); } json.endObject(); } catch (JSONException e) { deleteFile(tempFile); throw new ServletException(e); } catch (IOException e) { deleteFile(tempFile); throw new ServletException(e); } finally { if (writer != null) { writer.close(); } } addTempFile(tempFile, id); }
From source file:org.mapfish.print.servlet.MapPrinterServlet.java
/** * To get (in JSON) the information about the available formats and CO. *///from w ww .j a va 2 s . c om protected void getInfo(HttpServletRequest req, HttpServletResponse resp, String basePath) throws ServletException, IOException { app = req.getParameter("app"); //System.out.println("app = "+app); MapPrinter printer = getMapPrinter(app); resp.setContentType("application/json; charset=utf-8"); final PrintWriter writer = resp.getWriter(); try { final String var = req.getParameter("var"); if (var != null) { writer.print(var + "="); } JSONWriter json = new JSONWriter(writer); try { json.object(); { printer.printClientConfig(json); json.key("printURL").value(basePath + PRINT_URL); json.key("createURL").value(basePath + CREATE_URL); if (app != null) { json.key("app").value(app); } } json.endObject(); } catch (JSONException e) { throw new ServletException(e); } if (var != null) { writer.print(";"); } } finally { writer.close(); } }
From source file:de.dekarlab.moneybuilder.model.parser.JsonBookSaver.java
/** * Save book to file.//from w w w . j av a2 s . co m * * @param file * @param book * @throws Exception */ public static void saveBook(BookFile bookFile) throws Exception { FileWriter writer = null; JSONWriter jsonWriter = null; try { Book book = bookFile.getBook(); writer = new FileWriter(bookFile.getFilePath()); jsonWriter = new JSONWriter(writer); jsonWriter.object().key("book"); jsonWriter.object(); jsonWriter.key("name").value(book.getName()); jsonWriter.key("currPeriodId").value(book.getCurrPeriodId()); savePeriodBudget(book.getPeriodBudget(), jsonWriter); savePeriodValue(book.getPeriodValue(), jsonWriter); jsonWriter.key("assets"); saveAccount(book.getAssetList(), jsonWriter); jsonWriter.key("liability"); saveAccount(book.getLiabilityList(), jsonWriter); jsonWriter.key("income"); saveAccount(book.getIncomeList(), jsonWriter); jsonWriter.key("expenses"); saveAccount(book.getExpenseList(), jsonWriter); jsonWriter.key("periodList"); savePeriodList(book.getPeriodList(), jsonWriter); jsonWriter.endObject(); jsonWriter.endObject(); } finally { if (writer != null) { writer.flush(); writer.close(); } } }