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

The following examples show how to use javax.json.stream.JsonGenerator#writeEnd() . 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: 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 2
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 3
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 4
Source File: JSONDomainFacade.java    From jcypher with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example 5
Source File: CadfCredential.java    From FHIR with Apache License 2.0 6 votes vote down vote up
public static void generate(CadfCredential obj, JsonGenerator generator)
        throws IOException {
    if (obj.getAuthority() != null) {
        generator.write("authority", obj.getAuthority());
    }

    if (obj.getToken() != null) {
        generator.write("token", obj.getToken());
    }

    if (obj.getType() != null) {
        generator.write("type", obj.getType());
    }

    //Annotations
    if (obj.getAssertions() != null) {
        generator.writeStartArray("assertions");
        for (CadfMapItem item : obj.getAssertions()) {
            CadfMapItem.Writer.generate(item, generator);
        }
        generator.writeEnd();
    }
}
 
Example 6
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 7
Source File: JSONDBFacade.java    From jcypher with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example 8
Source File: JSONWriter.java    From jcypher with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 9
Source File: MagazineSerializer.java    From Java-EE-8-Sampler with MIT License 5 votes vote down vote up
@Override
public void serialize(Magazine magazine, JsonGenerator generator, SerializationContext ctx) {

    if (magazine != null) {
        generator.writeStartObject();
        ctx.serialize("name", magazine.getAuthor(), generator);
        generator.writeEnd();
    } else {
        ctx.serialize(null, generator);
    }

}
 
Example 10
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 11
Source File: CadfMeasurement.java    From FHIR with Apache License 2.0 5 votes vote down vote up
public static void generate(CadfMeasurement obj, JsonGenerator generator)
        throws IOException {
    if (obj == null) {
        return;
    }
    generator.writeStartObject();

    if (obj.getResult() != null) {
        Object tmpObj = obj.getResult();
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ObjectOutputStream objStream = new ObjectOutputStream(baos);) {
            objStream.writeObject(tmpObj);
            generator.write("result",
                    java.util.Base64.getEncoder().encodeToString(baos.toByteArray()));
        }
    }

    if (obj.getMetricId() != null) {
        generator.write("metricId", obj.getMetricId());
    }

    if (obj.getMetric() != null) {
        generator.writeStartObject("metric");
        CadfMetric.Writer.generate(obj.getMetric(), generator);
        generator.writeEnd();
    }

    if (obj.getCalculatedBy() != null) {
        generator.writeStartObject("calculatedBy");
        CadfResource.Writer.generate(obj.getCalculatedBy(), generator);
        generator.writeEnd();
    }

    if (obj.getCalculatedById() != null) {
        generator.write("calculatedById", obj.getCalculatedById());
    }

    generator.writeEnd();
}
 
Example 12
Source File: CountriesMessage.java    From ipst with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void toJson(JsonGenerator generator) {
    generator.writeStartArray("countries");
    for (Country country : countries) {
        generator.writeStartObject();
        generator.write("id", country.name());
        generator.write("label", country.name() + ", " + country.getName());
        generator.writeEnd();
    }
    generator.writeEnd();
}
 
Example 13
Source File: CadfReporterStep.java    From FHIR with Apache License 2.0 5 votes vote down vote up
public static void generate(CadfReporterStep obj, JsonGenerator generator)
        throws IOException {
    // If the CADF reporter step is null, then simply skip it.
    if (obj == null) {
        return;
    }
    generator.writeStartObject();

    if (obj.getReporter() != null) {
        generator.writeStartObject("reporter");
        CadfResource.Writer.generate(obj.getReporter(), generator);
        generator.writeEnd();
    }

    if (obj.getReporterId() != null) {
        generator.write("reporterId", obj.getReporterId());
    }

    if (obj.getReporterTime() != null) {
        generator.write("reporterTime", formatterFullTimestamp.format(obj.getReporterTime()));
    }

    if (obj.getRole() != null) {
        generator.write("role", obj.getRole().toString());
    }

    //Attachments
    if (obj.getAttachments() != null) {
        generator.writeStartArray("attachments");
        for (CadfAttachment item : obj.getAttachments()) {
            CadfAttachment.Writer.generate(item, generator);
        }
        generator.writeEnd();
    }
    generator.writeEnd();
}
 
Example 14
Source File: InstanceBodyWriterTools.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
private static void writeAttributes(List<InstanceAttributeDTO> attributes, JsonGenerator jg) {
    jg.writeStartArray("attributes");
    for (InstanceAttributeDTO a : attributes) {
        jg.writeStartObject();
        jg.write("name", a.getName());
        jg.write("type", a.getType().toString());
        jg.write("value", a.getValue());
        jg.writeEnd();
    }
    jg.writeEnd();
}
 
Example 15
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 16
Source File: Data.java    From NOVA-Core with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static void writeData(JsonGenerator writer, Data data, String key) {
	boolean isCollection;
	if (data.containsKey("isCollection") && Boolean.TRUE.equals(data.get("isCollection"))) {
		isCollection = true;
		if (key == null)
			writer.writeStartArray();
		else
			writer.writeStartArray(key);
	} else {
		isCollection = false;
		if (key == null)
			writer.writeStartObject();
		else
			writer.writeStartObject(key);
	}

	if (!isCollection)
		data.forEach((k, v) -> {
			if (v instanceof Data) {
				writeData(writer, (Data) v, k);
			} else if (v instanceof Number) {
				if (v instanceof Byte) {
					writer.write(k, (Byte) v);
				} else if (v instanceof Short) {
					writer.write(k, (Short) v);
				} else if (v instanceof Integer) {
					writer.write(k, (Integer) v);
				} else if (v instanceof Long) {
					writer.write(k, (Long) v);
				} else if (v instanceof Float) {
					writer.write(k, (Float) v);
				} else if (v instanceof Double) {
					writer.write(k, (Double) v);
				} else if (v instanceof BigInteger) {
					writer.write(k, (BigInteger) v);
				} else if (v instanceof BigDecimal) {
					writer.write(k, (BigDecimal) v);
				}
			} else {
				if (v instanceof Boolean) {
					writer.write(k, (Boolean) v);
				} else if (v instanceof Character) {
					writer.write(k, (Character) v);
				} else if (v instanceof String) {
					writer.write(k, (String) v);
				} else if (v instanceof JsonValue) {
					writer.write(k, (JsonValue) v);
				}
			}
		});
	else
		LongStream.range(0, data.size()).mapToObj(l -> data.get(Long.toUnsignedString(l))).forEachOrdered(v -> {
			if (v instanceof Data) {
				writeData(writer, (Data) v, null);
			} else if (v instanceof Number) {
				if (v instanceof Byte) {
					writer.write((Byte) v);
				} else if (v instanceof Short) {
					writer.write((Short) v);
				} else if (v instanceof Integer) {
					writer.write((Integer) v);
				} else if (v instanceof Long) {
					writer.write((Long) v);
				} else if (v instanceof Float) {
					writer.write((Float) v);
				} else if (v instanceof Double) {
					writer.write((Double) v);
				} else if (v instanceof BigInteger) {
					writer.write((BigInteger) v);
				} else if (v instanceof BigDecimal) {
					writer.write((BigDecimal) v);
				}
			} else {
				if (v instanceof Boolean) {
					writer.write((Boolean) v);
				} else if (v instanceof Character) {
					writer.write((Character) v);
				} else if (v instanceof String) {
					writer.write((String) v);
				} else if (v instanceof JsonValue) {
					writer.write((JsonValue) v);
				}
			}
		});

	writer.writeEnd();
}
 
Example 17
Source File: ModelWithSerializerAndDeserializerOnField.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Override
public void serialize(Inner obj, JsonGenerator gen, SerializationContext ctx) {
    gen.writeStartObject();
    gen.write("someValue", "unchangeable");
    gen.writeEnd();
}
 
Example 18
Source File: HalLinkJsonbSerializer.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Override
public void serialize(HalLink value, JsonGenerator generator, SerializationContext context) {
    generator.writeStartObject();
    generator.write("href", value.getHref());
    generator.writeEnd();
}
 
Example 19
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 20
Source File: JobParameter.java    From FHIR with Apache License 2.0 4 votes vote down vote up
/**
 * @param generator
 * @param parameter     job parameter details.
 * @param withSensitive indicates sensitive information should or should not be included.
 * @throws IOException
 */
public static void generate(JsonGenerator generator, JobParameter parameter, boolean withSensitive)
        throws IOException {
    if (withSensitive) {
        if (parameter.getCosApiKey() != null) {
            generator.write("cos.api.key", parameter.getCosApiKey());
        }
    }

    if (withSensitive) {
        if (parameter.getCosBucketName() != null) {
            generator.write("cos.bucket.name", parameter.getCosBucketName());
        }
    }

    if (parameter.getCosCredentialIbm() != null) {
        generator.write("cos.credential.ibm", parameter.getCosCredentialIbm());
    }

    if (parameter.getCosOperationBucketNameOo() != null) {
        generator.write("cos.operationoutcomes.bucket.name", parameter.getCosOperationBucketNameOo());
    }

    if (withSensitive) {
        if (parameter.getCosEndpointUrl() != null) {
            generator.write("cos.endpointurl", parameter.getCosEndpointUrl());
        }
    }
    if (parameter.getCosLocation() != null) {
        generator.write("cos.location", parameter.getCosLocation());
    }

    if (withSensitive) {
        if (parameter.getCosSrvInstId() != null) {
            generator.write("cos.srvinst.id", parameter.getCosSrvInstId());
        }
    }

    if (parameter.getFhirResourceType() != null) {
        generator.write("fhir.resourcetype", parameter.getFhirResourceType());
    }

    if (parameter.getFhirSearchFromDate() != null) {
        generator.write("fhir.search.fromdate", parameter.getFhirSearchFromDate());
    }

    if (parameter.getFhirTenant() != null) {
        generator.write("fhir.tenant", parameter.getFhirTenant());
    }

    if (parameter.getFhirPatientGroupId() != null) {
        generator.write("fhir.search.patientgroupid", parameter.getFhirPatientGroupId());
    }

    if (withSensitive) {
        if (parameter.getCosBucketPathPrefix() != null) {
            generator.write("cos.bucket.pathprefix", parameter.getCosBucketPathPrefix());
        }
    }

    if (parameter.getFhirDataStoreId() != null) {
        generator.write("fhir.datastoreid", parameter.getFhirDataStoreId());
    }

    if (parameter.getFhirTypeFilters() != null) {
        generator.write("fhir.typeFilters", parameter.getFhirTypeFilters());
    }

    if (parameter.getInputs() != null) {
        generator.write("fhir.dataSourcesInfo", writeToBase64(parameter.getInputs()));
    }

    String type = BulkDataConstants.DataSourceStorageType.HTTPS.value();
    if (parameter.getStorageDetails() != null) {
        type = parameter.getStorageDetails().getType();
    }
    generator.write("import.fhir.storagetype", type);

    generator.writeEnd();
}