Java Code Examples for com.google.gson.stream.JsonWriter#flush()
The following examples show how to use
com.google.gson.stream.JsonWriter#flush() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MetaKeys.java From packagedrone with Eclipse Public License 1.0 | 6 votes |
public static void writeJson ( final Map<MetaKey, String> properties, final Writer output ) throws IOException { @SuppressWarnings ( "resource" ) final JsonWriter writer = new JsonWriter ( output ); writer.beginObject (); for ( final Map.Entry<MetaKey, String> entry : properties.entrySet () ) { writer.name ( entry.getKey ().toString () ); if ( entry.getValue () != null ) { writer.value ( entry.getValue () ); } } writer.endObject (); writer.flush (); }
Example 2
Source File: JsonCodec.java From denominator with Apache License 2.0 | 6 votes |
<T> MockResponse toJsonArray(Iterator<T> elements) { elements.hasNext(); // defensive to make certain error cases eager. StringWriter out = new StringWriter(); // MWS cannot do streaming responses. try { JsonWriter writer = new JsonWriter(out); writer.setIndent(" "); writer.beginArray(); while (elements.hasNext()) { Object next = elements.next(); json.toJson(next, next.getClass(), writer); } writer.endArray(); writer.flush(); } catch (IOException e) { throw new RuntimeException(e); } return new MockResponse().setResponseCode(200) .addHeader("Content-Type", "application/json") .setBody(out.toString() + "\n"); // curl nice }
Example 3
Source File: MapedSql.java From sumk with Apache License 2.0 | 6 votes |
public String toJson(JsonWriterVisitor visitor) throws Exception { StringWriter stringWriter = new StringWriter(); JsonWriter writer = new JsonWriter(stringWriter); writer.setSerializeNulls(true); writer.beginObject(); writer.name("sql").value(sql); writer.name("hash").value(sql.hashCode()); String params = DBGson.toJson(paramters); params = LogKits.shorterSubfix(params, DBSettings.maxSqlParamLength()); writer.name("paramters").value(params); if (visitor != null) { visitor.visit(writer); } writer.endObject(); writer.flush(); writer.close(); return stringWriter.toString(); }
Example 4
Source File: KeyProvider.java From big-c with Apache License 2.0 | 5 votes |
/** * Serialize the metadata to a set of bytes. * @return the serialized bytes * @throws IOException */ protected byte[] serialize() throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); JsonWriter writer = new JsonWriter( new OutputStreamWriter(buffer, Charsets.UTF_8)); try { writer.beginObject(); if (cipher != null) { writer.name(CIPHER_FIELD).value(cipher); } if (bitLength != 0) { writer.name(BIT_LENGTH_FIELD).value(bitLength); } if (created != null) { writer.name(CREATED_FIELD).value(created.getTime()); } if (description != null) { writer.name(DESCRIPTION_FIELD).value(description); } if (attributes != null && attributes.size() > 0) { writer.name(ATTRIBUTES_FIELD).beginObject(); for (Map.Entry<String, String> attribute : attributes.entrySet()) { writer.name(attribute.getKey()).value(attribute.getValue()); } writer.endObject(); } writer.name(VERSIONS_FIELD).value(versions); writer.endObject(); writer.flush(); } finally { writer.close(); } return buffer.toByteArray(); }
Example 5
Source File: EmployeeGsonWriter.java From journaldev with MIT License | 5 votes |
public static void main(String[] args) throws IOException { Employee emp = EmployeeGsonExample.createEmployee(); //writing on console, we can initialize with FileOutputStream to write to file OutputStreamWriter out = new OutputStreamWriter(System.out); JsonWriter writer = new JsonWriter(out); //set indentation for pretty print writer.setIndent("\t"); //start writing writer.beginObject(); //{ writer.name("id").value(emp.getId()); // "id": 123 writer.name("name").value(emp.getName()); // "name": "David" writer.name("permanent").value(emp.isPermanent()); // "permanent": false writer.name("address").beginObject(); // "address": { writer.name("street").value(emp.getAddress().getStreet()); // "street": "BTM 1st Stage" writer.name("city").value(emp.getAddress().getCity()); // "city": "Bangalore" writer.name("zipcode").value(emp.getAddress().getZipcode()); // "zipcode": 560100 writer.endObject(); // } writer.name("phoneNumbers").beginArray(); // "phoneNumbers": [ for(long num : emp.getPhoneNumbers()) writer.value(num); //123456,987654 writer.endArray(); // ] writer.name("role").value(emp.getRole()); // "role": "Manager" writer.name("cities").beginArray(); // "cities": [ for(String c : emp.getCities()) writer.value(c); //"Los Angeles","New York" writer.endArray(); // ] writer.name("properties").beginObject(); //"properties": { Set<String> keySet = emp.getProperties().keySet(); for(String key : keySet) writer.name("key").value(emp.getProperties().get(key));//"age": "28 years","salary": "1000 Rs" writer.endObject(); // } writer.endObject(); // } writer.flush(); //close writer writer.close(); }
Example 6
Source File: SpeechTimestampTypeAdapter.java From java-sdk with Apache License 2.0 | 5 votes |
@Override public void write(JsonWriter writer, SpeechTimestamp speechTimestamp) throws IOException { writer.beginArray(); writer.value(speechTimestamp.getWord()); writer.value(speechTimestamp.getStartTime()); writer.value(speechTimestamp.getEndTime()); writer.endArray(); writer.flush(); }
Example 7
Source File: SpeechWordConfidenceTypeAdapter.java From java-sdk with Apache License 2.0 | 5 votes |
@Override public void write(JsonWriter writer, SpeechWordConfidence speechWordConfidence) throws IOException { writer.beginArray(); writer.value(speechWordConfidence.getWord()); writer.value(speechWordConfidence.getConfidence()); writer.endArray(); writer.flush(); }
Example 8
Source File: WordTimingTypeAdapter.java From java-sdk with Apache License 2.0 | 5 votes |
@Override public void write(JsonWriter out, WordTiming wordTiming) throws IOException { out.beginArray(); out.value(wordTiming.getWord()); out.value(wordTiming.getStartTime()); out.value(wordTiming.getEndTime()); out.endArray(); out.flush(); }
Example 9
Source File: MarkTimingTypeAdapter.java From java-sdk with Apache License 2.0 | 5 votes |
@Override public void write(JsonWriter out, MarkTiming markTiming) throws IOException { out.beginArray(); out.value(markTiming.getMark()); out.value(markTiming.getTime()); out.endArray(); out.flush(); }
Example 10
Source File: KeyProvider.java From hadoop with Apache License 2.0 | 5 votes |
/** * Serialize the metadata to a set of bytes. * @return the serialized bytes * @throws IOException */ protected byte[] serialize() throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); JsonWriter writer = new JsonWriter( new OutputStreamWriter(buffer, Charsets.UTF_8)); try { writer.beginObject(); if (cipher != null) { writer.name(CIPHER_FIELD).value(cipher); } if (bitLength != 0) { writer.name(BIT_LENGTH_FIELD).value(bitLength); } if (created != null) { writer.name(CREATED_FIELD).value(created.getTime()); } if (description != null) { writer.name(DESCRIPTION_FIELD).value(description); } if (attributes != null && attributes.size() > 0) { writer.name(ATTRIBUTES_FIELD).beginObject(); for (Map.Entry<String, String> attribute : attributes.entrySet()) { writer.name(attribute.getKey()).value(attribute.getValue()); } writer.endObject(); } writer.name(VERSIONS_FIELD).value(versions); writer.endObject(); writer.flush(); } finally { writer.close(); } return buffer.toByteArray(); }
Example 11
Source File: NodeLayoutStore.java From olca-app with Mozilla Public License 2.0 | 5 votes |
private static void writeAsJson(List<NodeLayoutInfo> layoutInfo, File file) throws IOException { JsonWriter w = new JsonWriter(new FileWriter(file)); w.beginObject(); w.name("nodes"); w.beginArray(); for (NodeLayoutInfo layout : layoutInfo) writeAsJson(layout, w); w.endArray(); w.endObject(); w.flush(); w.close(); }
Example 12
Source File: JsonOutputFormat.java From buildnumber-maven-plugin with MIT License | 5 votes |
@Override public void write( Properties props, OutputStream out ) throws IOException { Gson gson = new Gson(); JsonWriter jsonWriter = gson.newJsonWriter( new OutputStreamWriter( out, "UTF-8" ) ); jsonWriter.beginObject(); for ( Object key : props.keySet() ) { jsonWriter.name( (String) key ); jsonWriter.value( props.getProperty( (String) key ) ); } jsonWriter.endObject(); jsonWriter.flush(); }
Example 13
Source File: StructuredJsonExamplesMessageBodyReaderTest.java From vw-webservice with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void throwAwayTest() throws IOException { StructuredExample.ExampleBuilder exampleBuilder = new StructuredExample.ExampleBuilder(); StructuredExample.Namespace.NamespaceBuilder namespaceBuilder = new StructuredExample.Namespace.NamespaceBuilder(); exampleBuilder.setLabel("34"); exampleBuilder.setTag("someTag"); namespaceBuilder.setName("one"); namespaceBuilder.addFeature("a", 12.34f); namespaceBuilder.addFeature("b", 45.1f); StructuredExample.Namespace firstNamespace = namespaceBuilder.build(); namespaceBuilder.clear(); namespaceBuilder.setName("two"); namespaceBuilder.setScalingFactor(34.3f); namespaceBuilder.addFeature("bah", 0.038293f); namespaceBuilder.addFeature("another", 3.4000f); namespaceBuilder.addFeature("andThis", 2.0f); StructuredExample.Namespace secondNamespace = namespaceBuilder.build(); exampleBuilder.addNamespace(firstNamespace); exampleBuilder.addNamespace(secondNamespace); StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); JsonTestUtils.writeExample(jsonWriter, exampleBuilder.build()); jsonWriter.flush(); jsonWriter.close(); LOGGER.debug("The JSON is: {}", stringWriter.toString()); }
Example 14
Source File: GsonRequestConverter.java From jus with Apache License 2.0 | 5 votes |
@Override public NetworkRequest convert(T value) throws IOException { Buffer buffer = new Buffer(); Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8); JsonWriter jsonWriter = gson.newJsonWriter(writer); try { adapter.write(jsonWriter, value); jsonWriter.flush(); } catch (IOException e) { throw new AssertionError(e); // Writing to Buffer does no I/O. } return new NetworkRequest.Builder().setContentType(MEDIA_TYPE).setBody(buffer.readByteArray()) .build(); }
Example 15
Source File: WorkerProcessProtocolZero.java From buck with Apache License 2.0 | 5 votes |
private static void sendHandshake(JsonWriter writer, int messageId) throws IOException { writer.beginArray(); writer.beginObject(); writer.name("id").value(messageId); writer.name("type").value(TYPE_HANDSHAKE); writer.name("protocol_version").value(PROTOCOL_VERSION); writer.name("capabilities").beginArray().endArray(); writer.endObject(); writer.flush(); }
Example 16
Source File: Keystore.java From hedera-sdk-java with Apache License 2.0 | 4 votes |
public void export(OutputStream outputStream, String passphrase) throws IOException { final JsonWriter writer = new JsonWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8)); gson.toJson(exportJson(passphrase), writer); writer.flush(); }
Example 17
Source File: JsonStreamingResponse.java From swellrt with Apache License 2.0 | 4 votes |
@Override public final void write(OutputStream output) throws IOException, WebApplicationException { JsonWriter jw = new JsonWriter(new PrintWriter(output)); write(jw); jw.flush(); }
Example 18
Source File: InterpreterSetting.java From zeppelin with Apache License 2.0 | 4 votes |
public static String toJson(InterpreterSetting intpSetting) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); try { // id jsonWriter.beginObject(); jsonWriter.name("id"); jsonWriter.value(intpSetting.getId()); // name jsonWriter.name("name"); jsonWriter.value(intpSetting.getName()); // group jsonWriter.name("group"); jsonWriter.value(intpSetting.getGroup()); // dependencies jsonWriter.name("dependencies"); String jsonDep = gson.toJson(intpSetting.getDependencies(), new TypeToken<List<Dependency>>() { }.getType()); jsonWriter.value(jsonDep); // properties jsonWriter.name("properties"); String jsonProps = gson.toJson(intpSetting.getProperties(), new TypeToken<Map<String, InterpreterProperty>>() { }.getType()); jsonWriter.value(jsonProps); // interpreterOption jsonWriter.name("interpreterOption"); String jsonOption = gson.toJson(intpSetting.getOption(), new TypeToken<InterpreterOption>() { }.getType()); jsonWriter.value(jsonOption); // interpreterGroup jsonWriter.name("interpreterGroup"); String jsonIntpInfos = gson.toJson(intpSetting.getInterpreterInfos(), new TypeToken<List<InterpreterInfo>>() { }.getType()); jsonWriter.value(jsonIntpInfos); jsonWriter.endObject(); jsonWriter.flush(); } catch (IOException e) { LOGGER.error(e.getMessage(), e); } return stringWriter.getBuffer().toString(); }
Example 19
Source File: BufferGeometry.java From BlueMap with MIT License | 4 votes |
public String toJson() { try { StringWriter sw = new StringWriter(); Gson gson = new GsonBuilder().create(); JsonWriter json = gson.newJsonWriter(sw); json.beginObject(); // main-object // set special values json.name("type").value("BufferGeometry"); json.name("uuid").value(UUID.randomUUID().toString().toUpperCase()); json.name("data").beginObject(); // data json.name("attributes").beginObject(); // attributes for (Entry<String, BufferAttribute> entry : attributes.entrySet()) { json.name(entry.getKey()); entry.getValue().writeJson(json); } json.endObject(); // attributes json.name("groups").beginArray(); // groups // write groups into json for (MaterialGroup g : groups) { json.beginObject(); json.name("materialIndex").value(g.getMaterialIndex()); json.name("start").value(g.getStart()); json.name("count").value(g.getCount()); json.endObject(); } json.endArray(); // groups json.endObject(); // data json.endObject(); // main-object // save and return json.flush(); return sw.toString(); } catch (IOException e) { // since we are using a StringWriter there should never be an IO exception // thrown throw new RuntimeException(e); } }
Example 20
Source File: StructuredJsonExamplesMessageBodyReaderTest.java From vw-webservice with BSD 3-Clause "New" or "Revised" License | 2 votes |
@Test public void readFromTest() throws IOException, InterruptedException, TimeoutException, ExecutionException { final CountDownLatch readThreadIsReadyLatch = new CountDownLatch(1); final Exchanger<Example> exampleExchanger = new Exchanger<Example>(); final PipedInputStream pipedInputStream = new PipedInputStream(); //the reading thread will read from this stream final PipedOutputStream pipedOutputStream = new PipedOutputStream(pipedInputStream); //the submission thread will write to this stream ExecutorService executorService = Executors.newCachedThreadPool(); //------- //this is the thread that will read the structured examples and compare //them to what was submitted by the submitting thread. Future<Integer> readingThreadFuture = executorService.submit(new Callable<Integer>() { @Override public Integer call() throws Exception { readThreadIsReadyLatch.countDown(); //signal to the writing thread that this thread is ready. Iterable<Example> readStructuredExamples = toTest.readFrom(ExamplesIterable.class, null, null, null, null, pipedInputStream); int numExamplesRead = 0; LOGGER.trace("Starting to read examples..."); for (Example readExample : readStructuredExamples) { //LOGGER.trace("Read example: {}", readExample.getVWStringRepresentation()); exampleExchanger.exchange(readExample); numExamplesRead++; } return Integer.valueOf(numExamplesRead); } }); readThreadIsReadyLatch.await(); LOGGER.trace("Writing examples..."); StructuredExample lastComputedExample = null; OutputStreamWriter outputStreamWriter = new OutputStreamWriter(pipedOutputStream, Charsets.UTF_8); JsonWriter jsonWriter = new JsonWriter(outputStreamWriter); jsonWriter.beginArray(); Iterable<StructuredExample> structuredExamplesIterable = TestUtils.getStructuredExamplesFromNerTrain(); for (StructuredExample example : structuredExamplesIterable) { if (lastComputedExample != null) { Assert.assertEquals(lastComputedExample.getVWStringRepresentation(), exampleExchanger.exchange(null, 2000, TimeUnit.MILLISECONDS).getVWStringRepresentation()); } if (example != StructuredExample.EMPTY_EXAMPLE) JsonTestUtils.writeExample(jsonWriter, example); else { jsonWriter.beginObject(); jsonWriter.endObject(); } jsonWriter.flush(); lastComputedExample = example; }//end for jsonWriter.endArray(); jsonWriter.flush(); jsonWriter.close(); LOGGER.trace("Verifying final example..."); //don't forget to verify the very last example! Assert.assertEquals(lastComputedExample.getVWStringRepresentation(), exampleExchanger.exchange(null, 2000, TimeUnit.MILLISECONDS).getVWStringRepresentation()); Assert.assertEquals(272274, readingThreadFuture.get().intValue()); //assert that no exceptions where thrown. }