use of javax.json.stream.JsonGenerator in project sling by apache.
the class SimpleDistributionQueueCheckpoint method run.
@Override
public void run() {
String fileName = queue.getName() + "-checkpoint";
File checkpointFile = new File(checkpointDirectory, fileName + "-new");
log.debug("started checkpointing");
try {
if (checkpointFile.exists()) {
assert checkpointFile.delete();
}
assert checkpointFile.createNewFile();
Collection<String> lines = new LinkedList<String>();
FileOutputStream fileOutputStream = new FileOutputStream(checkpointFile);
for (DistributionQueueEntry queueEntry : queue.getItems(0, -1)) {
DistributionQueueItem item = queueEntry.getItem();
String packageId = item.getPackageId();
StringWriter w = new StringWriter();
JsonGenerator jsonWriter = Json.createGenerator(w);
jsonWriter.writeStartObject();
for (Map.Entry<String, Object> entry : item.entrySet()) {
Object value = entry.getValue();
boolean isArray = value instanceof String[];
if (isArray) {
jsonWriter.writeStartArray(entry.getKey());
for (String s : ((String[]) value)) {
jsonWriter.write(s);
}
jsonWriter.writeEnd();
} else {
jsonWriter.write(entry.getKey(), (String) value);
}
}
jsonWriter.writeEnd();
jsonWriter.close();
lines.add(packageId + " " + w.toString());
}
log.debug("parsed {} items", lines.size());
IOUtils.writeLines(lines, Charset.defaultCharset().name(), fileOutputStream, Charset.defaultCharset());
fileOutputStream.flush();
fileOutputStream.close();
boolean success = checkpointFile.renameTo(new File(checkpointDirectory, fileName));
log.debug("checkpoint succeeded: {}", success);
} catch (Exception e) {
log.error("failed checkpointing for queue {}", queue.getName());
}
}
use of javax.json.stream.JsonGenerator in project sling by apache.
the class JsonRendererServlet method doGet.
@Override
protected void doGet(SlingHttpServletRequest req, SlingHttpServletResponse resp) throws IOException {
// Access and check our data
final Resource r = req.getResource();
if (ResourceUtil.isNonExistingResource(r)) {
throw new ResourceNotFoundException("No data to render.");
}
int maxRecursionLevels = 0;
try {
maxRecursionLevels = getMaxRecursionLevel(req);
} catch (IllegalArgumentException iae) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, iae.getMessage());
return;
}
resp.setContentType(req.getResponseContentType());
resp.setCharacterEncoding("UTF-8");
// We check the tree to see if the nr of nodes isn't bigger than the allowed nr.
boolean allowDump = true;
int allowedLevel = 0;
final boolean tidy = isTidy(req);
final boolean harray = hasSelector(req, HARRAY);
ResourceTraversor traversor = null;
try {
traversor = new ResourceTraversor(maxRecursionLevels, maximumResults, r);
allowedLevel = traversor.collectResources();
if (allowedLevel != -1) {
allowDump = false;
}
} catch (final Exception e) {
reportException(e);
}
try {
// Dump the resource if we can
if (allowDump) {
if (tidy || harray) {
final JsonRenderer.Options opt = renderer.options().withIndent(tidy ? INDENT_SPACES : 0).withArraysForChildren(harray);
resp.getWriter().write(renderer.prettyPrint(traversor.getJSONObject(), opt));
} else {
// If no rendering options, use the plain toString() method, for
// backwards compatibility. Output might be slightly different
// with prettyPrint and no options
Json.createGenerator(resp.getWriter()).write(traversor.getJSONObject()).close();
}
} else {
// We are not allowed to do the dump.
// Send a 300
String tidyUrl = (tidy) ? "tidy." : "";
resp.setStatus(HttpServletResponse.SC_MULTIPLE_CHOICES);
JsonGenerator writer = Json.createGenerator(resp.getWriter());
writer.writeStartArray();
while (allowedLevel >= 0) {
writer.write(r.getResourceMetadata().getResolutionPath() + "." + tidyUrl + allowedLevel + ".json");
allowedLevel--;
}
writer.writeEnd();
writer.close();
}
} catch (Exception je) {
reportException(je);
}
}
use of javax.json.stream.JsonGenerator in project sling by apache.
the class SlingInfoServlet method renderJson.
private void renderJson(final SlingHttpServletResponse response, final Map<String, String> data) throws IOException {
// render data in JSON format
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
final Writer out = response.getWriter();
final JsonGenerator w = Json.createGenerator(out);
try {
w.writeStartObject();
for (final Map.Entry<String, String> e : data.entrySet()) {
w.write(e.getKey(), e.getValue());
}
w.writeEnd();
} catch (JsonException jse) {
out.write(jse.toString());
out.flush();
} finally {
w.flush();
}
}
use of javax.json.stream.JsonGenerator in project libSBOLj by SynBioDex.
the class SBOLWriter method writeJSON.
private static void writeJSON(Writer stream, DocumentRoot<QName> document) throws CoreIoException {
HashMap<String, Object> config = new HashMap<>();
config.put(JsonGenerator.PRETTY_PRINTING, true);
JsonGenerator writer = Json.createGeneratorFactory(config).createGenerator(stream);
JsonIo jsonIo = new JsonIo();
jsonIo.createIoWriter(writer).write(StringifyQName.qname2string.mapDR(document));
writer.flush();
writer.close();
}
use of javax.json.stream.JsonGenerator in project javaee7-samples by javaee-samples.
the class StreamingGeneratorTest method testNestedStructure.
@Test
public void testNestedStructure() throws JSONException {
JsonGeneratorFactory factory = Json.createGeneratorFactory(null);
StringWriter w = new StringWriter();
JsonGenerator gen = factory.createGenerator(w);
gen.writeStartObject().write("title", "The Matrix").write("year", 1999).writeStartArray("cast").write("Keanu Reaves").write("Laurence Fishburne").write("Carrie-Anne Moss").writeEnd().writeEnd();
gen.flush();
JSONAssert.assertEquals("{\"title\":\"The Matrix\",\"year\":1999,\"cast\":[\"Keanu Reaves\",\"Laurence Fishburne\",\"Carrie-Anne Moss\"]}", w.toString(), JSONCompareMode.STRICT);
}
Aggregations