/** * Returns a name and a value after the OK * @return just OK */ public static String build(String name, String value) { if (name == null) { throw new NullPointerException("name is null"); } if (value == null) { throw new NullPointerException("value is null"); } JsonGeneratorFactory jf = JsonUtil.getJsonGeneratorFactory(JsonUtil.DEFAULT_PRETTY_PRINTING); StringWriter sw = new StringWriter(); JsonGenerator gen = jf.createGenerator(sw); gen.writeStartObject() .write("status", "OK") .write(name, value) .writeEnd(); gen.close(); return sw.toString(); }
/** * Build a Json with name and values rom the passed map * @param namesAndValues the map of (name, value) to add to the JsonGenerator * @return */ public static String build(Map<String, String> namesAndValues) { if (namesAndValues == null) { throw new NullPointerException("namesAndValues is null"); } JsonGeneratorFactory jf = JsonUtil.getJsonGeneratorFactory(JsonUtil.DEFAULT_PRETTY_PRINTING); StringWriter sw = new StringWriter(); JsonGenerator gen = jf.createGenerator(sw); gen.writeStartObject() .write("status", "OK") ; for (Map.Entry<String, String> entry : namesAndValues.entrySet()) { // trace(entry.getKey() + "/" + entry.getValue()); gen.write(entry.getKey(), entry.getValue()); } gen.writeEnd(); gen.close(); return sw.toString(); }
/** * Builds a security error message in JSON format for Statements * @param sqlOrder * @param errorMessage * @param doPrettyPrinting * @return */ public static String statementNotAllowedBuild(String sqlOrder, String errorMessage, boolean doPrettyPrinting) { try { JsonGeneratorFactory jf = JsonUtil .getJsonGeneratorFactory(doPrettyPrinting); ByteArrayOutputStream out = new ByteArrayOutputStream(); JsonGenerator gen = jf.createGenerator(out); gen.writeStartObject(); gen.write(Tag.PRODUCT_SECURITY, errorMessage); gen.write("SQL order", sqlOrder); gen.writeEnd(); gen.close(); return out.toString("UTF-8"); } catch (Exception e) { String returnString = Tag.PRODUCT_SECURITY + " " + errorMessage + " " + sqlOrder; return returnString; } }
@Test public void testArray() throws JSONException { JsonGeneratorFactory factory = Json.createGeneratorFactory(null); StringWriter w = new StringWriter(); JsonGenerator gen = factory.createGenerator(w); gen .writeStartArray() .writeStartObject() .write("apple", "red") .writeEnd() .writeStartObject() .write("banana", "yellow") .writeEnd() .writeEnd(); gen.flush(); JSONAssert.assertEquals("[{\"apple\":\"red\"},{\"banana\":\"yellow\"}]", w.toString(), JSONCompareMode.STRICT); }
@Test public void testNestedStructure() throws JSONException { JsonGeneratorFactory factory = Json.createGeneratorFactory(null); StringWriter w = new StringWriter(); JsonGenerator gen = factory.createGenerator(w); gen .writeStartObject() .write("title", "The Matrix") .write("year", 1999) .writeStartArray("cast") .write("Keanu Reaves") .write("Laurence Fishburne") .write("Carrie-Anne Moss") .writeEnd() .writeEnd(); gen.flush(); JSONAssert.assertEquals("{\"title\":\"The Matrix\",\"year\":1999,\"cast\":[\"Keanu Reaves\",\"Laurence Fishburne\",\"Carrie-Anne Moss\"]}", w.toString(), JSONCompareMode.STRICT); }
public String toJSONString(){ Map<String, Object> properties = new HashMap<String, Object>(1); properties.put(JsonGenerator.PRETTY_PRINTING, true); JsonGeneratorFactory jgf = Json.createGeneratorFactory(properties); Writer sw = new StringWriter(); JsonGenerator jg = jgf.createGenerator(sw); jg = jg.writeStartObject() // { .writeStartObject("project") // "project":{ .write("name", name) // "name":name, .write("description", description) // "description":description, .write("createdOn", formatter.format(createdOn)) // "createdOn":createdOn, .write("lastModifiedOn", formatter.format(lastModifiedOn)) // "lastModifiedOn":lastModifiedOn .writeStartArray("tables"); // "tables":[ for(String s : tableNames){ jg = jg.writeStartObject() // { .write("name",s) // "name":name .writeEnd(); // } } jg.writeEnd() // ] .writeEnd() // } .writeEnd() // } .close(); return sw.toString(); }
/** * Answer a JSON representation of a recorded query * @param query * @return */ public String toJSON(RecordedQuery query) { StringWriter sw = new StringWriter(); JsonGenerator generator; if (this.prettyFormat != Format.NONE) { JsonGeneratorFactory gf = JSONWriter.getPrettyGeneratorFactory(); generator = gf.createGenerator(sw); } else generator = Json.createGenerator(sw); generator.writeStartObject(); writeQuery(query, generator); generator.writeEnd(); generator.flush(); return sw.toString(); }
/** * Answer a JSON representation of the available domains in the database * @return */ public String getDomains() { StringWriter sw = new StringWriter(); JsonGenerator generator; if (this.prettyFormat != Format.NONE) { JsonGeneratorFactory gf = JSONWriter.getPrettyGeneratorFactory(); generator = gf.createGenerator(sw); } else generator = Json.createGenerator(sw); generator.writeStartArray(); List<String> doms = DomainInformation.availableDomains(dbAccess); for (String dom : doms) { generator.write(dom); } generator.writeEnd(); generator.flush(); return sw.toString(); }
/** * Answer a JSON representation of the domain model * @return */ public String getDomainModel() { DomainModel model = ((IIntDomainAccess)this.domainAccess).getInternalDomainAccess().getDomainModel(); StringWriter sw = new StringWriter(); JsonGenerator generator; if (this.prettyFormat != Format.NONE) { JsonGeneratorFactory gf = JSONWriter.getPrettyGeneratorFactory(); generator = gf.createGenerator(sw); } else generator = Json.createGenerator(sw); generator.writeStartObject(); generator.write("domainName", model.getDomainName()); writeModel(model, generator); generator.writeEnd(); generator.flush(); return sw.toString(); }
/** * Answer a JSON object containing the domain name * @return */ public String getDomainName() { DomainModel model = ((IIntDomainAccess)this.domainAccess).getInternalDomainAccess().getDomainModel(); StringWriter sw = new StringWriter(); JsonGenerator generator; if (this.prettyFormat != Format.NONE) { JsonGeneratorFactory gf = JSONWriter.getPrettyGeneratorFactory(); generator = gf.createGenerator(sw); } else generator = Json.createGenerator(sw); generator.writeStartObject(); generator.write("domainName", model.getDomainName()); generator.writeEnd(); generator.flush(); return sw.toString(); }
/** * Returns just OK * @return just OK */ public static String build() { JsonGeneratorFactory jf = JsonUtil.getJsonGeneratorFactory(JsonUtil.DEFAULT_PRETTY_PRINTING); StringWriter sw = new StringWriter(); JsonGenerator gen = jf.createGenerator(sw); gen.writeStartObject() .write("status", "OK") .writeEnd(); gen.close(); return sw.toString(); }
/** * JsonGeneratorFactory getter with pretty printing on/off * @param prettyPrintingif true, JSON will be pretty printed * @return */ public static JsonGeneratorFactory getJsonGeneratorFactory(boolean prettyPrinting) { Map<String, Object> properties = new HashMap<>(1); if (prettyPrinting) { // Putting any value sets the pretty printing to true... So test must be done properties.put(JsonGenerator.PRETTY_PRINTING, prettyPrinting); } JsonGeneratorFactory jf = Json.createGeneratorFactory(properties); return jf; }
/** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { StringWriter writer = new StringWriter(); JsonGeneratorFactory jf = JsonUtil.getJsonGeneratorFactory(true); JsonGenerator gen = jf.createGenerator(writer); gen.writeStartObject() .write("firstName", "Duke") .write("lastName", "Java") .write("age", 18) .write("streetAddress", "100 Internet Dr") .write("city", "JavaTown") .write("state", "JA") .write("postalCode", "12345") .writeStartArray("phoneNumbers") .writeStartObject() .write("type", "mobile") .write("number", "111-111-1111") .writeEnd() .writeStartObject() .write("type", "home") .write("number", "222-222-2222") .writeEnd() .writeEnd() .writeEnd(); gen.close(); System.out.println(writer.toString()); }
/** * Builds the error message * @return the error message */ public String build() { JsonGeneratorFactory jf = JsonUtil.getJsonGeneratorFactory(JsonUtil.DEFAULT_PRETTY_PRINTING); StringWriter sw = new StringWriter(); JsonGenerator gen = jf.createGenerator(sw); gen.writeStartObject() .write("status", "FAIL") .write("error_type", errorType); if (errorMessage != null) { gen.write("error_message", errorMessage); } else { gen.write("error_message", JsonValue.NULL); } if (stackTrace != null) { gen.write("stack_trace", stackTrace); System.err.println(stackTrace); } gen.write("http_status", httpStatus); gen.writeEnd(); gen.close(); String doc = sw.toString(); if (LOG_JSON_ERROR) { System.err.println(doc); } return doc; }
public static void writeJsonStreamToString(){ StringWriter stringWriter = new StringWriter(); JsonGeneratorFactory jsonGeneratorFactory = Json.createGeneratorFactory(Collections.singletonMap(JsonGenerator.PRETTY_PRINTING, true)); JsonGenerator generator = jsonGeneratorFactory.createGenerator(stringWriter); generator.writeStartObject() .write("title","JSON-Processing With Java EE") .writeStartArray("chapters") .write("Introduction") .write("1. JSON and Java") .write("2. JSON-Processing API features") .write("3. The Java EE JSON Object model") .write("4. The Java EE JSON Streaming model") .write("Conclusion") .writeEnd() .write("released",JsonValue.TRUE) .write("length",90) .writeStartObject("sourceCode") .write("repositoryName", "JSON-Processing-with-Java-EE") .write("url","github.com/readlearncode") .writeEnd() .writeStartArray("complementaryCourse") .writeStartObject() .write("title", "RESTful Service with JAX-RS 2.0") .write("length", 120) .writeEnd() .writeStartObject() .write("title", "Java Enterprise Edition Introduction") .write("length", 130) .writeEnd() .writeEnd() .write("notes", JsonValue.NULL) .writeEnd(); generator.close(); System.out.print(stringWriter.toString()); }
private void testEncoding (byte[] value) { JsonProvider provider = new CookJsonProvider (); HashMap<String, Object> config = new HashMap<String, Object> (); config.put (CookJsonProvider.BINARY_FORMAT, CookJsonProvider.BINARY_FORMAT_HEX); JsonGeneratorFactory f = provider.createGeneratorFactory (config); StringWriter sw = new StringWriter (); CookJsonGenerator g = (CookJsonGenerator) f.createGenerator (sw); g.writeStartArray (); g.write (value); g.writeEnd (); g.close (); String expected = "[\"" + Hex.encodeHexString (value) + "\"]"; Assert.assertEquals (expected, sw.toString ()); sw = new StringWriter (); g = (CookJsonGenerator) f.createGenerator (sw); g.writeStartObject (); g.write ("test", value); g.writeEnd (); g.close (); expected = "{\"test\":\"" + Hex.encodeHexString (value) + "\"}"; Assert.assertEquals (expected, sw.toString ()); }
private void testEncoding (byte[] value) { JsonProvider provider = new CookJsonProvider (); HashMap<String, Object> config = new HashMap<String, Object> (); config.put (CookJsonProvider.BINARY_FORMAT, CookJsonProvider.BINARY_FORMAT_BASE64); JsonGeneratorFactory f = provider.createGeneratorFactory (config); StringWriter sw = new StringWriter (); CookJsonGenerator g = (CookJsonGenerator) f.createGenerator (sw); g.writeStartArray (); g.write (value); g.writeEnd (); g.close (); String expected = "[\"" + Base64.encodeBase64String (value) + "\"]"; Assert.assertEquals (expected, sw.toString ()); sw = new StringWriter (); g = (CookJsonGenerator) f.createGenerator (sw); g.writeStartObject (); g.write ("test", value); g.writeEnd (); g.close (); expected = "{\"test\":\"" + Base64.encodeBase64String (value) + "\"}"; Assert.assertEquals (expected, sw.toString ()); }
public void write(Model model, String path) throws IOException { String filename = path + "/json" + System.currentTimeMillis() + ".txt"; FileWriter writer = new FileWriter(filename, false); Collections.singletonMap(JsonGenerator.PRETTY_PRINTING, true); JsonGeneratorFactory jf = Json.createGeneratorFactory(Collections.singletonMap(JsonGenerator.PRETTY_PRINTING, true)); JsonGenerator gen = jf.createGenerator(writer); gen.writeStartObject(); // write scenario name gen.write("scenario", model.getScenario().getName()); // write streets gen.writeStartArray("streets"); model.getDesignEntities().stream().filter(e -> e instanceof Street).map(e -> (Street)e).forEach(e -> writeStreet(gen, e)); gen.writeEnd(); // write open space gen.writeStartArray("openspace"); model.getDesignEntities().stream().filter(e -> e instanceof OpenSpaceBlock).map(e -> (OpenSpaceBlock)e).forEach(e -> writeOpenSpace(gen, e)); gen.writeEnd(); // write lots & buildings gen.writeStartArray("buildings"); model.getDesignEntities().stream().filter(e -> e instanceof BuildingBlock).map(e -> (BuildingBlock)e).forEach(e -> e.getBuildings().forEach(b -> writeBuilding(gen, b))); gen.writeEnd(); // write existing buildings gen.writeStartArray("existing_blocks"); model.getDesignEntities().stream().filter(e -> e instanceof Block).map(e -> (Block)e).filter(e -> e.getBlockType() == BlockType.LEAVE_AS_IS).forEach(e -> writeExistingBlock(gen, e)); gen.writeEnd(); // done gen.writeEnd(); gen.close(); }
/** * Always return a JSON Writer. * * @return The JSON writer to use. * * @throws UnsupportedOperationException if it could not be loaded. */ private static synchronized JsonGeneratorFactory factory() { JsonGeneratorFactory f = factory; if (f == null) { factory = f = loadFactory(); } return f; }
/** * Always return a JSON Writer. * * @return The JSON writer to use. * * @throws UnsupportedOperationException if no provider could be found. */ private static synchronized JsonGeneratorFactory loadFactory() { try { // This method does not return null, it throws a JsonException instead JsonProvider provider = JsonProvider.provider(); LOGGER.debug("JSON Provider found using {}", provider.getClass().getName()); // XXX: We could supply configuration for the factory return provider.createGeneratorFactory(Collections.emptyMap()); } catch (JsonException ex) { LOGGER.warn("JSON Provider not found: {}", ex.getMessage()); throw new UnsupportedOperationException("Unable to find suitable provider"); } }
private JsonGenerator createJsonGenerator(Writer theWriter) { Map<String, Object> properties = new HashMap<String, Object>(1); if (myPrettyPrint) { properties.put(JsonGenerator.PRETTY_PRINTING, myPrettyPrint); } JsonGeneratorFactory jgf = Json.createGeneratorFactory(properties); JsonGenerator eventWriter = jgf.createGenerator(theWriter); return eventWriter; }
Mapper(final JsonReaderFactory readerFactory, final JsonGeneratorFactory generatorFactory, MapperConfig config, final Collection<Closeable> closeables) { this.readerFactory = readerFactory; this.generatorFactory = generatorFactory; this.config = config; this.mappings = new Mappings(config); this.readerHandler = ReaderHandler.create(readerFactory); this.closeables = closeables; this.charset = config.getEncoding(); }
@Test public void testEmptyObject() throws JSONException { JsonGeneratorFactory factory = Json.createGeneratorFactory(null); StringWriter w = new StringWriter(); JsonGenerator gen = factory.createGenerator(w); gen.writeStartObject().writeEnd(); gen.flush(); JSONAssert.assertEquals("{}", w.toString(), JSONCompareMode.STRICT); }
@Test public void testSimpleObject() throws JSONException { JsonGeneratorFactory factory = Json.createGeneratorFactory(null); StringWriter w = new StringWriter(); JsonGenerator gen = factory.createGenerator(w); gen .writeStartObject() .write("apple", "red") .write("banana", "yellow") .writeEnd(); gen.flush(); JSONAssert.assertEquals("{\"apple\" : \"red\", \"banana\" : \"yellow\" }", w.toString(), JSONCompareMode.STRICT); }
public static String getTableJSON(Table table){ Map<String, Object> properties = new HashMap<String, Object>(1); properties.put(JsonGenerator.PRETTY_PRINTING, true); JsonGeneratorFactory jgf = Json.createGeneratorFactory(properties); Writer sw = new StringWriter(); JsonGenerator jg = jgf.createGenerator(sw); Attribute idAttribute = table.getIdAttribute(); jg = jg.writeStartObject() // { .writeStartObject(TABLE) // "table":{ .write(NAME, table.getName()) // "name":name, .write(DESCRIPTION, table.getDescription()); // "description":description, if(null != idAttribute){ jg = jg.writeStartObject(ID_ATTRIB) // "idAttrib": { .write(NAME,table.getIdAttribute().getName()) // "name":name, .write(TYPE,table.getIdAttribute().getType().name())// "type":type .writeEnd(); // } } jg = jg.write(PROJECT_NAME, table.getProjectName()) // "projectName":projectName, .writeStartArray(ATTRIBUTES); // "attributes": [ for(Attribute attribute : table.getAttributes()){ jg = jg.writeStartObject() // { .write(NAME, attribute.getName()) // "name":name, .write(TYPE, attribute.getType().name()) // "type":type .writeEnd(); // }, } jg.writeEnd() // ] .writeEnd() // } .writeEnd() // } .close(); return sw.toString(); }
public String toJSONString(){ Map<String, Object> properties = new HashMap<String, Object>(1); properties.put(JsonGenerator.PRETTY_PRINTING, true); JsonGeneratorFactory jgf = Json.createGeneratorFactory(properties); Writer sw = new StringWriter(); JsonGenerator jg = jgf.createGenerator(sw); jg = jg.writeStartObject() // { .writeStartObject("table") // "table":{ .write("name", name) // "name":name, .write("idAttrib", idAttrib.getName()) // "idAttrib":idAttrib, .write("projectName", projectName) // "projectName":projectName, .writeStartArray("attributes"); // "attributes": [ for(Attribute attribute : attributes){ jg = jg.writeStartObject() // { .write("name", attribute.getName()) // "name":name, .write("type", attribute.getType().name()) // "type":type .writeEnd(); // }, } jg.writeEnd() // ], .write("size", items.size()) // "size":size .writeEnd() // } .writeEnd() // } .close(); return sw.toString(); }
public static String toJSON(PreparedQuery preparedQuery) { if (preparedQuery.hasdSLParams()) { // parameters part of json must be recreated WriterContext context = new WriterContext(); PQContext pqContext = preparedQuery.getContext(); QueryParam.setExtractParams(pqContext.extractParams, context); context.cypherFormat = pqContext.cypherFormat; String cypher = preparedQuery.getCypher(); StringWriter sw = new StringWriter(); JsonGenerator generator; if (context.cypherFormat != Format.NONE) { JsonGeneratorFactory gf = getPrettyGeneratorFactory(); generator = gf.createGenerator(sw); } else generator = Json.createGenerator(sw); ContextAccess.setUseTransactionalEndpoint(pqContext.useTransationalEndpoint, context); ContextAccess.setResultDataContents(context, pqContext.resultDataContents); context.queryParams = pqContext.queryParams; generator.writeStartObject(); if (pqContext.useTransationalEndpoint) writeStatements(new Statement[] {new Statement(context, cypher)}, generator); else writeQuery("query", cypher, context, generator); generator.writeEnd(); generator.flush(); context.buffer.append(sw.getBuffer()); return context.buffer.toString(); } else return preparedQuery.getJson(); }
public static JsonGeneratorFactory getPrettyGeneratorFactory() { if (prettyGeneratorFactory == null) { HashMap<String, Object> prettyConfigMap = new HashMap<String, Object>(); prettyConfigMap.put(JsonGenerator.PRETTY_PRINTING, Boolean.TRUE); prettyGeneratorFactory = Json.createGeneratorFactory(prettyConfigMap); } return prettyGeneratorFactory; }
private JsonGenerator newJsonGenerator(Options options) throws IOException { JsonGeneratorFactory jgf = Json.createGeneratorFactory( options.isCompactFormat() ? null : singletonMap(JsonGenerator.PRETTY_PRINTING, true)); OutputStream output = options.getOutput() != null ? new BufferedOutputStream(new FileOutputStream(options.getOutput(), false)) : System.out; return jgf.createGenerator(output); }
public static JsonGeneratorFactory createGeneratorFactory() { return getProvider().createGeneratorFactory(); }
public static JsonGeneratorFactory createGeneratorFactory(JsonConfiguration config) { return getProvider().createGeneratorFactory(config); }
public abstract JsonGeneratorFactory createGeneratorFactory(JsonConfiguration config);
public void write(AnnoSentence sent) throws IOException { Map<String, Object> properties = new HashMap<>(1); //properties.put(JsonGenerator.PRETTY_PRINTING, false); JsonGeneratorFactory gf = Json.createGeneratorFactory(properties); g = gf.createGenerator(writer); g.writeStartObject(); appendIfNotNull("words", sent.getWords(), false); appendIfNotNull("prefixes", sent.getPrefixes()); appendIfNotNull("lemmas", sent.getLemmas()); appendIfNotNull("posTags", sent.getPosTags()); appendIfNotNull("cposTags", sent.getCposTags()); appendIfNotNull("strictPosTags", sent.getStrictPosTags()); appendIfNotNull("clusters", sent.getClusters()); appendIfNotNull("feats", sent.getFeats()); appendIfNotNull("chunks", sent.getChunks()); appendIfNotNull("neTags", sent.getNeTags()); appendIfNotNull("parents", sent.getParents()); appendIfNotNull("deprels", sent.getDeprels()); appendIfNotNull("naryTree", sent.getNaryTree() == null ? null : sent.getNaryTree().getAsOneLineString()); appendIfNotNull("namedEntities", sent.getNamedEntities() == null ? null : nesToJson(sent.getNamedEntities()).toString()); appendIfNotNull("nePairs", nePairsToJson(sent.getNePairs()).toString()); appendIfNotNull("relLabels", sent.getRelLabels()); // Not included: //appendIfNotNull("embedIds", sent.getEmbedIds()); //appendIfNotNull("depEdgeMask", sent.getDepEdgeMask()); //appendIfNotNull("srlGraph", sent.getSrlGraph()); //appendIfNotNull("knownPreds", sent.getKnownPreds()); //if (sent.getNamedEntities() != null) { // appendIfNotNull("namedEntities-InContext", sent.getNamedEntities().toString(sent.getWords())); //} //appendIfNotNull("relations", sent.getRelations()); //if (sent.getRelations() != null) { // appendIfNotNull("relations-InContext", sent.getRelations().toString(sent.getWords())); //} g.writeEnd(); forceNewline(); forceNewline(); g.flush(); count++; }
@Override public JsonGeneratorFactory createGeneratorFactory (Map<String, ?> config) { return new JsonGeneratorFactoryImpl (config, getHandler (config)); }
@Override public JsonGeneratorFactory generatorFactory() { return generatorFactory; }
public static JsonGeneratorFactory createGeneratorFactory(Map<String, ?> config) { return provider.createGeneratorFactory(config); }
public void setGeneratorFactory(final JsonGeneratorFactory generatorFactory) { builder.setGeneratorFactory(generatorFactory); }
@Override public JsonGeneratorFactory createGeneratorFactory(final Map<String, ?> stringMap) { return DELEGATE.createGeneratorFactory(stringMap); }