Java Code Examples for com.google.gson.stream.JsonWriter#close()

The following examples show how to use com.google.gson.stream.JsonWriter#close() . 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: RLESparseResourceAllocation.java    From big-c with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the JSON string representation of the current resources allocated
 * over time
 * 
 * @return the JSON string representation of the current resources allocated
 *         over time
 */
public String toMemJSONString() {
  StringWriter json = new StringWriter();
  JsonWriter jsonWriter = new JsonWriter(json);
  readLock.lock();
  try {
    jsonWriter.beginObject();
    // jsonWriter.name("timestamp").value("resource");
    for (Map.Entry<Long, Resource> r : cumulativeCapacity.entrySet()) {
      jsonWriter.name(r.getKey().toString()).value(r.getValue().toString());
    }
    jsonWriter.endObject();
    jsonWriter.close();
    return json.toString();
  } catch (IOException e) {
    // This should not happen
    return "";
  } finally {
    readLock.unlock();
  }
}
 
Example 2
Source File: AttributeTest.java    From TomboloDigitalConnector with MIT License 6 votes vote down vote up
@Test
public void testWriteJSON() throws Exception {
    StringWriter writer = new StringWriter();
    JsonWriter jsonWriter = new JsonWriter(writer);
    TestFactory.makeAttribute(TestFactory.DEFAULT_PROVIDER, "timed_label").writeJSON(jsonWriter);

    JSONAssert.assertEquals("{" +
            "  label: 'timed_label'," +
            "  description: 'timed_label_description'," +
            "  provider: {" +
            "    label: 'default_provider_label'," +
            "    name: 'default_provider_name'" +
            "  }" +
            "}", writer.toString(), false);

    jsonWriter.close();
}
 
Example 3
Source File: MapedSql.java    From sumk with Apache License 2.0 6 votes vote down vote up
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: FancyMessage.java    From fanciful with MIT License 6 votes vote down vote up
/**
 * Serialize this fancy message, converting it into syntactically-valid JSON using a {@link JsonWriter}.
 * This JSON should be compatible with vanilla formatter commands such as {@code /tellraw}.
 *
 * @return The JSON string representing this object.
 */
public String toJSONString() {
	if (!dirty && jsonString != null) {
		return jsonString;
	}
	StringWriter string = new StringWriter();
	JsonWriter json = new JsonWriter(string);
	try {
		writeJson(json);
		json.close();
	} catch (IOException e) {
		throw new RuntimeException("invalid message");
	}
	jsonString = string.toString();
	dirty = false;
	return jsonString;
}
 
Example 5
Source File: MCRRestAPIObjectsHelper.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
private static String listDerivateContentAsJson(MCRDerivate derObj, String path, int depth, UriInfo info,
    Application app)
    throws IOException {
    StringWriter sw = new StringWriter();
    MCRPath root = MCRPath.getPath(derObj.getId().toString(), "/");
    root = MCRPath.toMCRPath(root.resolve(path));
    if (depth == -1) {
        depth = Integer.MAX_VALUE;
    }
    if (root != null) {
        JsonWriter writer = new JsonWriter(sw);
        Files.walkFileTree(root, EnumSet.noneOf(FileVisitOption.class), depth,
            new MCRJSONFileVisitor(writer, derObj.getOwnerID(), derObj.getId(), info, app));
        writer.close();
    }
    return sw.toString();
}
 
Example 6
Source File: EmployeeGsonWriter.java    From journaldev with MIT License 5 votes vote down vote up
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 7
Source File: NodeLayoutStore.java    From olca-app with Mozilla Public License 2.0 5 votes vote down vote up
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 8
Source File: FileStore.java    From teammates with GNU General Public License v2.0 5 votes vote down vote up
private static <T> void saveEncryptedJsonToFile(String fileName, T object, Type typeOfObject) throws Exception {
    SecretKeySpec sks = new SecretKeySpec(StringHelper.hexStringToByteArray(Config.ENCRYPTION_KEY), "AES");
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, sks, cipher.getParameters());

    try (OutputStream os = Files.newOutputStream(Paths.get(fileName))) {
        CipherOutputStream out = new CipherOutputStream(os, cipher);
        JsonWriter writer = new JsonWriter(new OutputStreamWriter(out));
        getSerializer().toJson(object, typeOfObject, writer);
        writer.close();
        out.close();
    }
}
 
Example 9
Source File: AccessRule.java    From outbackcdx with Apache License 2.0 5 votes vote down vote up
static void toJSON(Collection<AccessRule> rules, Function<Long,String> policyNames, Writer out) throws IOException {
    JsonWriter json = GSON.newJsonWriter(out);
    json.beginArray();
    for (AccessRule rule : rules) {
        GSON.toJson(rule, AccessRule.class, json);
    }
    json.endArray();
    json.close();
}
 
Example 10
Source File: CustomGsonRequestBodyConverter.java    From AndroidWallet with GNU General Public License v3.0 5 votes vote down vote up
@Override
public RequestBody convert(T value) throws IOException {
    Buffer buffer = new Buffer();
    Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
    JsonWriter jsonWriter = gson.newJsonWriter(writer);
    adapter.write(jsonWriter, value);
    jsonWriter.close();
    return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
}
 
Example 11
Source File: GsonRequestBodyConverter.java    From XDroid-Databinding with MIT License 5 votes vote down vote up
@Override
public RequestBody convert(T value) throws IOException {
    Buffer buffer = new Buffer();
    Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
    JsonWriter jsonWriter = gson.newJsonWriter(writer);
    adapter.write(jsonWriter, value);
    jsonWriter.close();
    return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
}
 
Example 12
Source File: ProviderTest.java    From TomboloDigitalConnector with MIT License 5 votes vote down vote up
@Test
public void testWriteJSON() throws Exception {
    StringWriter writer = new StringWriter();
    JsonWriter jsonWriter = new JsonWriter(writer);
    TestFactory.DEFAULT_PROVIDER.writeJSON(jsonWriter);

    JSONAssert.assertEquals("{" +
            "  label: 'default_provider_label'," +
            "  name: 'default_provider_name'" +
            "}", writer.toString(), false);

    jsonWriter.close();
}
 
Example 13
Source File: GsonPlacesApiJsonParser.java    From android-PlacesAutocompleteTextView with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void writeHistoryJson(final OutputStream os, final List<Place> places) throws JsonWritingException {
    try {
        JsonWriter writer = new JsonWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.setIndent("  ");
        writer.beginArray();
        for (Place place : places) {
            gson.toJson(place, Place.class, writer);
        }
        writer.endArray();
        writer.close();
    } catch (Exception e) {
        throw new JsonWritingException(e);
    }
}
 
Example 14
Source File: GsonRequestBodyConverter.java    From proteus with Apache License 2.0 5 votes vote down vote up
@Override
public RequestBody convert(T value) throws IOException {
  TypeAdapter<T> adapter = getAdapter();
  Buffer buffer = new Buffer();
  Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
  JsonWriter jsonWriter = gson.newJsonWriter(writer);
  jsonWriter.setSerializeNulls(true);
  adapter.write(jsonWriter, value);
  jsonWriter.close();
  return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
}
 
Example 15
Source File: ReportExporter.java    From synthea with Apache License 2.0 5 votes vote down vote up
/**
 * Export the outcomes, access, and cost report. Requires a Generator with a
 * database. If the database is null, this method will return immediately.
 * In order for a database to be present in the generator, the Synthea
 * configuration file (synthea.properties) should have the `generate.database_type`
 * property set to `file` or `in-memory`.
 * This report will be written to the output folder, in a `statistics` folder, in a file
 * named `statistics-{timestamp}.json`.
 * @param generator - Generator with a database.
 */
public static void export(Generator generator) {
  if (generator == null || generator.database == null) {
    return;
  }

  try (Connection connection = generator.database.getConnection()) {
    File outDirectory = Exporter.getOutputFolder("statistics", null);
    String timeStamp = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date());
    Path outFilePath = outDirectory.toPath().resolve("statistics-" + timeStamp + ".json");

    JsonWriter writer = new JsonWriter(new OutputStreamWriter(
        new FileOutputStream(outFilePath.toFile()), charset));
    writer.setIndent("  ");
    writer.beginObject(); // top-level

    reportParameters(writer);
    processOutcomes(connection, writer);
    processAccess(connection, writer);
    processCosts(connection, writer);

    writer.endObject(); // top-level
    writer.close();

  } catch (IOException | SQLException e) {
    e.printStackTrace();
    throw new RuntimeException("error exporting statistics");
  }
}
 
Example 16
Source File: KeyProvider.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * 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 17
Source File: GsonConverterFactory.java    From ProjectX with Apache License 2.0 5 votes vote down vote up
@Override
public RequestBody convert(T value) throws IOException {
    final Buffer buffer = new Buffer();
    final JsonWriter writer =
            mGson.newJsonWriter(new OutputStreamWriter(buffer.outputStream(), UTF_8));
    mGson.toJson(value, mType, writer);
    writer.close();
    return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
}
 
Example 18
Source File: LenientGsonRequestBodyConverter.java    From youqu_master with Apache License 2.0 5 votes vote down vote up
@Override
public RequestBody convert(T value) throws IOException {
    Buffer buffer = new Buffer();
    Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
    JsonWriter jsonWriter = gson.newJsonWriter(writer);
    jsonWriter.setLenient(true);
    adapter.write(jsonWriter, value);
    jsonWriter.close();
    return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
}
 
Example 19
Source File: CsvConverters.java    From DataflowTemplates with Apache License 2.0 4 votes vote down vote up
/**
 * Builds Json string from list of values and headers or values and schema if schema is provided.
 *
 * @param headers optional list of strings which is the header of the Csv file.
 * @param values list of strings which are combined with header or json schema to create Json
 *     string.
 * @param jsonSchemaString
 * @return Json string containing object.
 * @throws IOException thrown if Json object is not able to be written.
 * @throws NumberFormatException thrown if value cannot be parsed into type successfully.
 */
static String buildJsonString(
    @Nullable List<String> headers, List<String> values, @Nullable String jsonSchemaString)
    throws Exception {

  StringWriter stringWriter = new StringWriter();
  JsonWriter writer = new JsonWriter(stringWriter);

  if (jsonSchemaString != null) {
    JsonArray jsonSchema = jsonParser.parse(jsonSchemaString).getAsJsonArray();
    writer.beginObject();

    for (int i = 0; i < jsonSchema.size(); i++) {
      JsonObject jsonObject = jsonSchema.get(i).getAsJsonObject();
      String type = jsonObject.get("type").getAsString().toUpperCase();
      writer.name(jsonObject.get("name").getAsString());

      switch (type) {
        case "LONG":
          writer.value(Long.parseLong(values.get(i)));
          break;

        case "DOUBLE":
          writer.value(Double.parseDouble(values.get(i)));
          break;

        case "INTEGER":
          writer.value(Integer.parseInt(values.get(i)));
          break;

        case "SHORT":
          writer.value(Short.parseShort(values.get(i)));
          break;

        case "BYTE":
          writer.value(Byte.parseByte(values.get(i)));
          break;

        case "FLOAT":
          writer.value(Float.parseFloat(values.get(i)));
          break;

        case "TEXT":
        case "KEYWORD":
        case "STRING":
          writer.value(values.get(i));
          break;

        default:
          LOG.error("Invalid data type, got: " + type);
          throw new RuntimeException("Invalid data type, got: " + type);
      }
    }
    writer.endObject();
    writer.close();
    return stringWriter.toString();

  } else if (headers != null) {

    writer.beginObject();

    for (int i = 0; i < headers.size(); i++) {
      writer.name(headers.get(i));
      writer.value(values.get(i));
    }

    writer.endObject();
    writer.close();
    return stringWriter.toString();

  } else {
    LOG.error("No headers or schema specified");
    throw new RuntimeException("No headers or schema specified");
  }
}
 
Example 20
Source File: CatalogueExportRunner.java    From TomboloDigitalConnector with MIT License 3 votes vote down vote up
public static void main(String[] args) throws Exception {
    runner.validateArguments(args);

    JsonWriter writer = new JsonWriter(runner.getOutputWriter(args[0]));
    List<Class<? extends Importer>> importers = runner.getImporterClasses();

    writer.beginArray();

    for (Class<? extends Importer> i : importers) {

        if (!i.getCanonicalName().equals("uk.org.tombolo.importer.generalcsv.GeneralCSVImporter")
                && !i.getCanonicalName().equals("uk.org.tombolo.importer.PythonImporter")) {
            Importer importer = runner.getImporter(i);

            List<String> datasources = runner.getDatasourceIds(importer);

            for (String d : datasources) {
                Datasource datasource = runner.getDatasource(d, importer);

                if (null != datasource.getDatasourceSpec()) datasource.writeJSON(writer);
            }
        }
    }

    writer.endArray();
    writer.close();

}