Java Code Examples for javax.json.Json#createGenerator()

The following examples show how to use javax.json.Json#createGenerator() . 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: FrontHandler.java    From gluon-samples with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@RequestMapping(value = "whiteboard", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE + "; " + CHARSET)
public String whiteboard() {
    try (StringWriter stringWriter = new StringWriter(); JsonGenerator jsonGenerator = Json.createGenerator(stringWriter)) {
        jsonGenerator.writeStartArray();
        service.listItems().stream()
                .map(item -> Json.createObjectBuilder()
                        .add("id", item.getId())
                        .add("title", item.getTitle())
                        .add("creationDate", item.getCreationDate())
                        .build())
                .forEach(jsonGenerator::write);
        jsonGenerator.writeEnd();
        jsonGenerator.close();
        return stringWriter.toString();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return "[]";
}
 
Example 2
Source File: FrontHandler.java    From gluon-samples with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@RequestMapping(value = "whiteboard", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE + "; " + CHARSET)
public String whiteboard() {
    try (StringWriter stringWriter = new StringWriter(); JsonGenerator jsonGenerator = Json.createGenerator(stringWriter)) {
        jsonGenerator.writeStartArray();
        service.listItems().stream()
                .map(item -> Json.createObjectBuilder()
                        .add("id", item.getId())
                        .add("title", item.getTitle())
                        .add("creationDate", item.getCreationDate())
                        .build())
                .forEach(jsonGenerator::write);
        jsonGenerator.writeEnd();
        jsonGenerator.close();
        return stringWriter.toString();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return "[]";
}
 
Example 3
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 4
Source File: CloudLinkService.java    From gluon-samples with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Async
public void addItem(Item item) {
    StringWriter writer = new StringWriter();
    try (JsonGenerator generator = Json.createGenerator(writer)) {
        generator.writeStartObject()
                .write("title", item.getTitle())
                .write("creationDate", item.getCreationDate())
                .writeEnd();
    }
    String payload = writer.toString();

    System.out.println("Creating Item: " + item.getId() + " with payload " + payload);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON_UTF8);

    HttpEntity<String> entity = new HttpEntity<>(payload, headers);

    OAuthRestTemplate restTemplate = new OAuthRestTemplate(resourceDetails);
    String response = restTemplate.postForObject(CLOUDLINK_ENDPOINT + "/list/items/add/" + item.getId(),
            entity, String.class);
    System.out.println("CloudLink Response: " + response);
}
 
Example 5
Source File: JsonpTest.java    From ee8-sandbox with Apache License 2.0 6 votes vote down vote up
@Test
public void testJsonGenerator() {
    JsonGenerator gen = Json.createGenerator(System.out);
    gen.writeStartArray()
            .writeStartObject()
            .write("name", "Duke")
            .write("birthData", "1995-5-23")
            .writeStartArray("phoneNumbers")
            .writeStartObject()
            .write("type", "home")
            .write("number", "123 456 789")
            .writeEnd()
            .writeEnd()
            .writeEnd()
            .writeEnd()
            .flush();

}
 
Example 6
Source File: NovaMinecraftPreloader.java    From NOVA-Core with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Dynamically generates a sound JSON file based on a resource pack's file structure.
 *
 * If it's a folder, then load it as a sound collection.
 * A sound collection falls under the same resource name. When called to play, it will pick a random sound from the collection to play it.
 *
 * If it's just a sound file, then load the sound file
 *
 * @param pack The resource pack to generate the sound JSON for.
 * @return The generated sound JSON.
 */
public static String generateSoundJSON(AbstractResourcePack pack) {
	StringWriter sw = new StringWriter();
	try (JsonGenerator json = Json.createGenerator(sw);) {
		json.writeStartObject();
		if (pack instanceof FileResourcePack) {
			//For zip resource packs
			try {
				generateSoundJSON((FileResourcePack) pack, json);
			} catch (Exception e) {
				Error error = new ExceptionInInitializerError("Error generating fake sound JSON file.");
				error.addSuppressed(e);
				throw error;
			}
		} else if (pack instanceof FolderResourcePack) {
			//For folder resource packs
			generateSoundJSON((FolderResourcePack) pack, json);
		}
		json.writeEnd().flush();
		return sw.toString();
	}
}
 
Example 7
Source File: RealtimeCargoTrackingService.java    From pragmatic-microservices-lab with MIT License 6 votes vote down vote up
public void onCargoInspected(@Observes @CargoInspected Cargo cargo) {
    Writer writer = new StringWriter();

    try (JsonGenerator generator = Json.createGenerator(writer)) {
        generator
                .writeStartObject()
                .write("trackingId", cargo.getTrackingId().getIdString())
                .write("origin", cargo.getOrigin().getName())
                .write("destination", cargo.getRouteSpecification().getDestination().getName())
                .write("lastKnownLocation", cargo.getDelivery().getLastKnownLocation().getName())
                .write("transportStatus", cargo.getDelivery().getTransportStatus().toString())
                .writeEnd();
    }

    String jsonValue = writer.toString();

    for (Session session : sessions) {
        try {
            session.getBasicRemote().sendText(jsonValue);
        } catch (IOException ex) {
            logger.log(Level.WARNING, "Unable to publish WebSocket message", ex);
        }
    }

}
 
Example 8
Source File: MDICOM.java    From aws-big-data-blog with Apache License 2.0 6 votes vote down vote up
public static String dicomJsonContent(File dicomFile) {
  String dicomJsonString = "";

  try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
      DicomInputStream dis = new DicomInputStream(dicomFile)) {
    IncludeBulkData includeBulkData = IncludeBulkData.URI;
    dis.setIncludeBulkData(includeBulkData);

    JsonGenerator jsonGen = Json.createGenerator(baos);
    JSONWriter jsonWriter = new JSONWriter(jsonGen);
    dis.setDicomInputHandler(jsonWriter);
    dis.readDataset(-1, -1);
    jsonGen.flush();
    dicomJsonString = new String(baos.toByteArray(), "UTF-8");
  } catch (Exception e) {
    System.out.println("error processing dicom: " + e.getMessage());
  }

  return dicomJsonString;
}
 
Example 9
Source File: NovaMinecraftPreloader.java    From NOVA-Core with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Dynamically generates a sound JSON file based on a resource pack's file structure.
 *
 * If it's a folder, then load it as a sound collection.
 * A sound collection falls under the same resource name. When called to play, it will pick a random sound from the collection to play it.
 *
 * If it's just a sound file, then load the sound file
 *
 * @param pack The resource pack to generate the sound JSON for.
 * @return The generated sound JSON.
 */
public static String generateSoundJSON(AbstractResourcePack pack) {
	StringWriter sw = new StringWriter();
	try (JsonGenerator json = Json.createGenerator(sw);) {
		json.writeStartObject();
		if (pack instanceof FileResourcePack) {
			//For zip resource packs
			try {
				generateSoundJSON((FileResourcePack) pack, json);
			} catch (Exception e) {
				Error error = new ExceptionInInitializerError("Error generating fake sound JSON file.");
				error.addSuppressed(e);
				throw error;
			}
		} else if (pack instanceof FolderResourcePack) {
			//For folder resource packs
			generateSoundJSON((FolderResourcePack) pack, json);
		}
		json.writeEnd().flush();
		return sw.toString();
	}
}
 
Example 10
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 11
Source File: Message.java    From ipst with Mozilla Public License 2.0 5 votes vote down vote up
public static <U extends Message<?>> String toJson(Iterable<U> messages) {
    StringWriter writer = new StringWriter();
    try (JsonGenerator generator = Json.createGenerator(writer)) {
        generator.writeStartArray();
        for (U message : messages) {
            generator.writeStartObject();
            message.toJson(generator);
            generator.writeEnd();
        }
        generator.writeEnd();
    }
    return writer.toString();
}
 
Example 12
Source File: NovaMinecraftPreloader.java    From NOVA-Core with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static String generatePackMcmeta() {
	StringWriter sw = new StringWriter();
	try (JsonGenerator json = Json.createGenerator(sw);) {
		json.writeStartObject()                                      //	{
		        .writeStartObject("pack")                            //		"pack": {
		            .write("description", "NOVA mod resource pack")  //			"description": "NOVA mod resource pack",
		            .write("pack_format", 3)                         //			"pack_format": 3 // Required by 1.11+
		        .writeEnd()                                          //		}
		    .writeEnd()                                              //	}
		.flush();

		return sw.toString();
	}
}
 
Example 13
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 14
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 15
Source File: Message.java    From ipst with Mozilla Public License 2.0 5 votes vote down vote up
public static <U extends Message> String toJson(Iterable<U> messages) {
    StringWriter writer = new StringWriter();
    try (JsonGenerator generator = Json.createGenerator(writer)) {
        generator.writeStartArray();
        for (U message : messages) {
            generator.writeStartObject();
            message.toJson(generator);
            generator.writeEnd();
        }
        generator.writeEnd();
    }
    writer.flush();
    return writer.toString();
}
 
Example 16
Source File: Message.java    From ipst with Mozilla Public License 2.0 5 votes vote down vote up
public String toJson() {
    StringWriter writer = new StringWriter();
    try (JsonGenerator generator = Json.createGenerator(writer)) {
        generator.writeStartObject().write("type", getType()).writeStartObject("body");
        toJson(generator);
        generator.writeEnd().writeEnd();
    }
    return writer.toString();
}
 
Example 17
Source File: JSONWriter.java    From jcypher with Apache License 2.0 4 votes vote down vote up
public static void toJSON(List<JcQuery> queries, WriterContext context) {
	List<Statement> statements = new ArrayList<Statement>(queries.size());
	PreparedQueries prepQs = new PreparedQueries();
	context.preparedQuery = prepQs;
	Format cf = context.cypherFormat;
	context.cypherFormat = Format.NONE;
	boolean useTxEndpoint = ContextAccess.useTransationalEndpoint(context);
	// needed for multiple statements
	ContextAccess.setUseTransactionalEndpoint(true, context);
	boolean extract = QueryParam.isExtractParams(context);
	for (JcQuery query : queries) {
		PreparedQuery prepQ = new PreparedQuery();
		prepQs.add(prepQ);
		PQContext pqContext = prepQ.getContext();
		pqContext.cypherFormat = cf;
		pqContext.extractParams = query.isExtractParams();
		pqContext.useTransationalEndpoint = ContextAccess.useTransationalEndpoint(context);
		pqContext.resultDataContents = ContextAccess.getResultDataContents(context);
		
		WriterContext ctxt = ContextAccess.cloneContext(context);
		ctxt.preparedQuery = prepQs; // needed to mark if there are dynamic parameters
		QueryParam.setExtractParams(query.isExtractParams(), ctxt);
		CypherWriter.toCypherExpression(query, ctxt);
		String cypher = ctxt.buffer.toString();
		prepQ.setCypher(cypher);
		pqContext.queryParams = QueryParamSet.getQueryParams(ctxt);
		reInitContext(ctxt);
		statements.add(new Statement(ctxt, cypher));
	}
	context.cypherFormat = cf;
	
	StringWriter sw = new StringWriter();
	JsonGenerator generator;
	if (context.cypherFormat != Format.NONE) {
		JsonGeneratorFactory gf = getPrettyGeneratorFactory();
		generator = gf.createGenerator(sw);
	} else
		generator = Json.createGenerator(sw);
	
	generator.writeStartObject();
	Statement[] statementsArray = statements.toArray(new Statement[statements.size()]);
	writeStatements(statementsArray, generator);
	generator.writeEnd();

	generator.flush();
	context.buffer.append(sw.getBuffer());
	
	// reset to original
	QueryParam.setExtractParams(extract, context);
	ContextAccess.setUseTransactionalEndpoint(useTxEndpoint, context);
	prepQs.setJson(context.buffer.toString());
}
 
Example 18
Source File: JSONWriter.java    From jcypher with Apache License 2.0 4 votes vote down vote up
public static String toJSON(PreparedQueries preparedQueries) {
	if (preparedQueries.hasdSLParams()) { // parameters part of json must be recreated
		WriterContext context = new WriterContext();
		List<PreparedQuery> prepQs = preparedQueries.getPreparedQueries();
		if (prepQs.isEmpty())
			return new String();
		PreparedQuery prepQ = prepQs.get(0);
		PQContext pqContext = prepQ.getContext();
		List<Statement> statements = new ArrayList<Statement>(prepQs.size());
		Format cf = pqContext.cypherFormat;
		pqContext.fillContext(context);
		context.cypherFormat = Format.NONE;
		// needed for multiple statements
		ContextAccess.setUseTransactionalEndpoint(true, context);
		for (PreparedQuery pq : prepQs) {
			WriterContext ctxt = new WriterContext();
			PQContext pqCtxt = pq.getContext();
			pqCtxt.fillContext(ctxt);
			
			String cypher = pq.getCypher();
			statements.add(new Statement(ctxt, cypher));
		}
		context.cypherFormat = cf;
		
		StringWriter sw = new StringWriter();
		JsonGenerator generator;
		if (context.cypherFormat != Format.NONE) {
			JsonGeneratorFactory gf = getPrettyGeneratorFactory();
			generator = gf.createGenerator(sw);
		} else
			generator = Json.createGenerator(sw);
		
		generator.writeStartObject();
		Statement[] statementsArray = statements.toArray(new Statement[statements.size()]);
		writeStatements(statementsArray, generator);
		generator.writeEnd();

		generator.flush();
		context.buffer.append(sw.getBuffer());
		preparedQueries.setJson(context.buffer.toString());
		return preparedQueries.getJson();
	} else
		return preparedQueries.getJson();
}
 
Example 19
Source File: PingJSONP.java    From sample.daytrader7 with Apache License 2.0 4 votes vote down vote up
/**
 * this is the main method of the servlet that will service all get
 * requests.
 *
 * @param request
 *            HttpServletRequest
 * @param responce
 *            HttpServletResponce
 **/
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    try {
        res.setContentType("text/html");

        ServletOutputStream out = res.getOutputStream();
        
        hitCount++;
        
        // JSON generate
        StringWriter sw = new StringWriter();
        JsonGenerator generator = Json.createGenerator(sw);
         
        generator.writeStartObject();
        generator.write("initTime",initTime);
        generator.write("hitCount", hitCount);
        generator.writeEnd();
        generator.flush();
        
        String generatedJSON =  sw.toString();
        StringBuffer parsedJSON = new StringBuffer(); 
        
        // JSON parse
        JsonParser parser = Json.createParser(new StringReader(generatedJSON));
        while (parser.hasNext()) {
           JsonParser.Event event = parser.next();
           switch(event) {
              case START_ARRAY:
              case END_ARRAY:
              case START_OBJECT:
              case END_OBJECT:
              case VALUE_FALSE:
              case VALUE_NULL:
              case VALUE_TRUE:
                 break;
              case KEY_NAME:
                  parsedJSON.append(parser.getString() + ":");
                 break;
              case VALUE_STRING:
              case VALUE_NUMBER:
                  parsedJSON.append(parser.getString() + " ");
                 break;
           }
        }
        
        out.println("<html><head><title>Ping JSONP</title></head>"
                + "<body><HR><BR><FONT size=\"+2\" color=\"#000066\">Ping JSONP</FONT><BR>Generated JSON: " + generatedJSON + "<br>Parsed JSON: " + parsedJSON + "</body></html>");
    } catch (Exception e) {
        Log.error(e, "PingJSONP.doGet(...): general exception caught");
        res.sendError(500, e.toString());

    }
}
 
Example 20
Source File: StowrsSingleFile.java    From weasis-dicom-tools with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void uploadEncapsulatedDocument(Attributes metadata, File bulkDataFile, String mimeType, String sopClassUID)
    throws Exception {
    HttpURLConnection httpPost = buildConnection();

    setEncapsulatedDocumentAttributes(bulkDataFile.toPath(), metadata, mimeType);
    if (metadata.getValue(Tag.EncapsulatedDocument) == null) {
        metadata.setValue(Tag.EncapsulatedDocument, VR.OB, new BulkData(null, "bulk", false));
    }
    metadata.setValue(Tag.SOPClassUID, VR.UI, sopClassUID);
    ensureUID(metadata, Tag.StudyInstanceUID);
    ensureUID(metadata, Tag.SeriesInstanceUID);
    ensureUID(metadata, Tag.SOPInstanceUID);

    try (ByteArrayOutputStream bOut = new ByteArrayOutputStream();
                    DataOutputStream out = new DataOutputStream(httpPost.getOutputStream())) {
        if (getContentType() == Multipart.ContentType.JSON)
            try (JsonGenerator gen = Json.createGenerator(bOut)) {
                new JSONWriter(gen).write(metadata);
            }
        else {
            SAXTransformer.getSAXWriter(new StreamResult(bOut)).write(metadata);
        }

        writeContentMarkers(out);

        out.write(bOut.toByteArray());

        // Segment and headers for a part
        out.write(Multipart.Separator.BOUNDARY.getType());
        out.writeBytes(MULTIPART_BOUNDARY);
        byte[] fsep = Multipart.Separator.FIELD.getType();
        out.write(fsep);
        out.writeBytes("Content-Type: "); //$NON-NLS-1$
        out.writeBytes(mimeType);
        out.write(fsep);
        out.writeBytes("Content-Location: "); //$NON-NLS-1$
        out.writeBytes(getContentLocation(metadata));
        out.write(Multipart.Separator.HEADER.getType());

        Files.copy(bulkDataFile.toPath(), out);

        writeEndMarkers(httpPost, out, metadata.getString(Tag.SOPInstanceUID));
    } finally {
        removeConnection(httpPost);
    }
}