Java Code Examples for javax.json.stream.JsonGenerator#close()

The following examples show how to use javax.json.stream.JsonGenerator#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: JsonSecurityMessage.java    From aceql-http with GNU Lesser General Public License v2.1 7 votes vote down vote up
/**
    * 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;
}

   }
 
Example 2
Source File: JsonOkReturn.java    From aceql-http with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
    * 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();
   }
 
Example 3
Source File: JsonOkReturn.java    From aceql-http with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
    * Build a Json with name and values from 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()) {

    //System.out.println(entry.getKey() + "/" + entry.getValue());
    gen.write(entry.getKey(), entry.getValue());
}

gen.writeEnd();
gen.close();

return sw.toString();
   }
 
Example 4
Source File: JsonExample.java    From aceql-http with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
    * @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());

   }
 
Example 5
Source File: MavenLicense.java    From sonarqube-licensecheck with Apache License 2.0 6 votes vote down vote up
public static String createString(Collection<MavenLicense> mavenLicenses)
{
    TreeSet<MavenLicense> mavenLicenseSet = new TreeSet<>(mavenLicenses);

    StringWriter jsonString = new StringWriter();
    JsonGenerator generator = Json.createGenerator(jsonString);
    generator.writeStartArray();
    for (MavenLicense mavenLicense : mavenLicenseSet)
    {
        generator.writeStartObject();
        generator.write("regex", mavenLicense.getRegex().pattern());
        generator.write("license", mavenLicense.getLicense());
        generator.writeEnd();
    }
    generator.writeEnd();
    generator.close();

    return jsonString.toString();
}
 
Example 6
Source File: Dependency.java    From sonarqube-licensecheck with Apache License 2.0 6 votes vote down vote up
public static String createString(Collection<Dependency> dependencies)
{
    TreeSet<Dependency> sortedDependencies = new TreeSet<>();
    sortedDependencies.addAll(dependencies);

    StringWriter jsonString = new StringWriter();
    JsonGenerator generator = Json.createGenerator(jsonString);
    generator.writeStartArray();
    for (Dependency dependency : sortedDependencies)
    {
        String license = dependency.getLicense();
        generator.writeStartObject();
        generator.write("name", dependency.getName());
        generator.write("version", dependency.getVersion());
        generator.write("license", license != null ? license : " ");
        generator.writeEnd();
    }
    generator.writeEnd();
    generator.close();
    return jsonString.toString();
}
 
Example 7
Source File: License.java    From sonarqube-licensecheck with Apache License 2.0 6 votes vote down vote up
public static String createString(Collection<License> licenses)
{
    TreeSet<License> licenseSet = new TreeSet<>(licenses);

    StringWriter jsonString = new StringWriter();
    JsonGenerator generator = Json.createGenerator(jsonString);
    generator.writeStartArray();
    for (License license : licenseSet)
    {
        generator.writeStartObject();
        generator.write("name", license.getName());
        generator.write("identifier", license.getIdentifier());
        generator.write("status", license.getStatus());
        generator.writeEnd();
    }
    generator.writeEnd();
    generator.close();

    return jsonString.toString();
}
 
Example 8
Source File: Index.java    From FHIR with Apache License 2.0 6 votes vote down vote up
public void store(Writer writer) {
    if (version < 1) {
        throw new IllegalStateException("index version was not set");
    }
    if (entries.isEmpty()) {
        throw new IllegalStateException("index contains no entries");
    }
    Collections.sort(entries);
    JsonGenerator generator = GENERATOR_FACTORY.createGenerator(writer);
    generator.writeStartObject();
    generator.write("index-version", version);
    generator.writeStartArray("files");
    for (Entry entry : entries) {
        write(generator, entry);
    }
    generator.writeEnd();
    generator.writeEnd();
    generator.flush();
    generator.close();
}
 
Example 9
Source File: ProjectLicense.java    From sonarqube-licensecheck with Apache License 2.0 6 votes vote down vote up
public static String createString(Collection<ProjectLicense> projectLicenses)
{
    TreeSet<ProjectLicense> projectLicenseSet = new TreeSet<>();
    projectLicenseSet.addAll(projectLicenses);

    StringWriter jsonString = new StringWriter();
    JsonGenerator generator = Json.createGenerator(jsonString);
    generator.writeStartArray();
    for (ProjectLicense projectLicense : projectLicenseSet)
    {
        generator.writeStartObject();
        generator.write("projectKey", projectLicense.getProjectKey());
        generator.write("license", projectLicense.getLicense());
        generator.write("status", projectLicense.getStatus());
        generator.writeEnd();
    }
    generator.writeEnd();
    generator.close();

    return jsonString.toString();
}
 
Example 10
Source File: EventJsonbSerializer.java    From scalable-coffee-shop with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(final CoffeeEvent event, final JsonGenerator generator, final SerializationContext ctx) {
    generator.writeStartObject();
    generator.write("class", event.getClass().getCanonicalName());
    ctx.serialize("data", event, generator);
    generator.writeEnd();
    generator.close();
}
 
Example 11
Source File: CoffeeCollectionWriter.java    From maven-framework-project with MIT License 5 votes vote down vote up
@Override
public void writeTo(List<Coffee> coffees, Class<?> type, java.lang.reflect.Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
    StringWriter writer = new StringWriter();
    JsonGenerator generator = Json.createGenerator(writer);
    Map<String, Object> configs;
    configs = new HashMap<String, Object>(1);
    configs.put(JsonGenerator.PRETTY_PRINTING, true);

    generator.writeStartObject().
            writeStartObject("metadata")
            .write("pageCount",coffees.size())
            .write("totalCount",CoffeeService.getSize())
            .writeStartArray("links")
            .writeStartObject().write("self",
            "/orders?page="+(CoffeeService.getNextPage()-1) +"&limit=10");
            generator.writeEnd();
            generator.writeStartObject().write("next","/orders?page="+CoffeeService.getNextPage() +"&limit=10")
    ;
    generator.writeEnd();
    generator.writeEnd();
    generator.writeEnd();
    generator.writeStartArray("coffees");
    for (Coffee coffee : coffees ) {
        generator.writeStartObject()
                .write("Id", coffee.getId())
                .write("Name", coffee.getName())
                .write("Price", coffee.getPrice())
                .write("Type", coffee.getType())
                .write("Size", coffee.getSize()).writeEnd();

    }
    generator.writeEnd();
    generator.writeEnd();
    generator.close();
    entityStream.write(writer.toString().getBytes());


}
 
Example 12
Source File: EmployeeJSONGenerator.java    From journaldev with MIT License 5 votes vote down vote up
public static void main(String[] args) throws IOException {
	OutputStream fos = new FileOutputStream("emp_stream.txt");
	JsonGenerator jsonGenerator = Json.createGenerator(fos);
	/**
	 * We can get JsonGenerator from Factory class also
	 * JsonGeneratorFactory factory = Json.createGeneratorFactory(null);
	 * jsonGenerator = factory.createGenerator(fos);
	 */
	
	Employee emp = EmployeeJSONWriter.createEmployee();
	jsonGenerator.writeStartObject(); // {
	jsonGenerator.write("id", emp.getId()); // "id":123
	jsonGenerator.write("name", emp.getName());
	jsonGenerator.write("role", emp.getRole());
	jsonGenerator.write("permanent", emp.isPermanent());
	
	jsonGenerator.writeStartObject("address") //start of address object
		.write("street", emp.getAddress().getStreet())
		.write("city",emp.getAddress().getCity())
		.write("zipcode",emp.getAddress().getZipcode())
		.writeEnd(); //end of address object
	
	jsonGenerator.writeStartArray("phoneNumbers"); //start of phone num array
	for(long num : emp.getPhoneNumbers()){
		jsonGenerator.write(num);
	}
	jsonGenerator.writeEnd(); // end of phone num array
	jsonGenerator.writeEnd(); // }
	
	jsonGenerator.close();
	
}
 
Example 13
Source File: EventJsonbSerializer.java    From scalable-coffee-shop with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(final CoffeeEvent event, final JsonGenerator generator, final SerializationContext ctx) {
    generator.writeStartObject();
    generator.write("class", event.getClass().getCanonicalName());
    ctx.serialize("data", event, generator);
    generator.writeEnd();
    generator.close();
}
 
Example 14
Source File: EventJsonbSerializer.java    From scalable-coffee-shop with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(final CoffeeEvent event, final JsonGenerator generator, final SerializationContext ctx) {
    generator.writeStartObject();
    generator.write("class", event.getClass().getCanonicalName());
    ctx.serialize("data", event, generator);
    generator.writeEnd();
    generator.close();
}
 
Example 15
Source File: JsonErrorReturn.java    From aceql-http with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
    * 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;
   }
 
Example 16
Source File: JsonOkReturn.java    From aceql-http with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
    * 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();
   }
 
Example 17
Source File: Client.java    From webex-java-sdk with MIT License 4 votes vote down vote up
private void writeJson(Object body, OutputStream ostream) {
    JsonGenerator jsonGenerator = Json.createGenerator(ostream);
    jsonGenerator.writeStartObject();
    for (Field field : body.getClass().getDeclaredFields()) {
        field.setAccessible(true);
        try {
            Object value = field.get(body);
            if (value == null) {
                continue;
            }

            Type type = field.getType();
            if (type == String.class) {
                jsonGenerator.write(field.getName(), (String) value);
            } else if (type == Integer.class) {
                jsonGenerator.write(field.getName(), (Integer) value);
            } else if (type == BigDecimal.class) {
                jsonGenerator.write(field.getName(), (BigDecimal) value);
            } else if (type == Date.class) {
                DateFormat dateFormat = new SimpleDateFormat(ISO8601_FORMAT);
                jsonGenerator.write(field.getName(), dateFormat.format(value));
            } else if (type == URI.class) {
                jsonGenerator.write(field.getName(), value.toString());
            } else if (type == JsonArray.class) {
                jsonGenerator.write(field.getName(), (JsonArray) value);
            } else if (type == Boolean.class) {
                jsonGenerator.write(field.getName(), (Boolean) value);
            } else if (type == String[].class) {
                jsonGenerator.writeStartArray(field.getName());
                for (String st : (String[]) value) {
                    jsonGenerator.write(st);
                }
                jsonGenerator.writeEnd();
            } else if (type == URI[].class) {
                jsonGenerator.writeStartArray(field.getName());
                for (URI uri : (URI[]) value) {
                    jsonGenerator.write(uri.toString());
                }
                jsonGenerator.writeEnd();
            }
        } catch (IllegalAccessException ex) {
            // ignore
        }
    }
    jsonGenerator.writeEnd();
    jsonGenerator.flush();
    jsonGenerator.close();
}
 
Example 18
Source File: AuspiceGenerator.java    From beast-mcmc with GNU Lesser General Public License v2.1 3 votes vote down vote up
private void writeTreeJSON(String filename, RootedTree tree) throws IOException {
    FileWriter writer = new FileWriter(filename);

    HashMap<String, Object> config = new HashMap<>();
    config.put(JsonGenerator.PRETTY_PRINTING, true);

    JsonGeneratorFactory factory = Json.createGeneratorFactory(config);

    JsonGenerator generator = factory.createGenerator(writer);
    currentYValue = 0;

    writeNode(generator, tree, tree.getRootNode());

    generator.close();
}