Search in sources :

Example 1 with JsonGenerator

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());
    }
}
Also used : DistributionQueueEntry(org.apache.sling.distribution.queue.DistributionQueueEntry) LinkedList(java.util.LinkedList) DistributionQueueItem(org.apache.sling.distribution.queue.DistributionQueueItem) StringWriter(java.io.StringWriter) FileOutputStream(java.io.FileOutputStream) JsonGenerator(javax.json.stream.JsonGenerator) File(java.io.File) Map(java.util.Map)

Example 2 with JsonGenerator

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);
    }
}
Also used : Resource(org.apache.sling.api.resource.Resource) ResourceTraversor(org.apache.sling.servlets.get.impl.util.ResourceTraversor) JsonGenerator(javax.json.stream.JsonGenerator) JsonRenderer(org.apache.sling.servlets.get.impl.util.JsonRenderer) ResourceNotFoundException(org.apache.sling.api.resource.ResourceNotFoundException) SlingException(org.apache.sling.api.SlingException) IOException(java.io.IOException) ResourceNotFoundException(org.apache.sling.api.resource.ResourceNotFoundException)

Example 3 with JsonGenerator

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();
    }
}
Also used : JsonException(javax.json.JsonException) JsonGenerator(javax.json.stream.JsonGenerator) HashMap(java.util.HashMap) Map(java.util.Map) PrintWriter(java.io.PrintWriter) JsonWriter(javax.json.JsonWriter) Writer(java.io.Writer)

Example 4 with JsonGenerator

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();
}
Also used : JsonIo(org.sbolstandard.core.io.json.JsonIo) HashMap(java.util.HashMap) JsonGenerator(javax.json.stream.JsonGenerator)

Example 5 with JsonGenerator

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);
}
Also used : StringWriter(java.io.StringWriter) JsonGenerator(javax.json.stream.JsonGenerator) JsonGeneratorFactory(javax.json.stream.JsonGeneratorFactory) Test(org.junit.Test)

Aggregations

JsonGenerator (javax.json.stream.JsonGenerator)21 StringWriter (java.io.StringWriter)9 HashMap (java.util.HashMap)6 JsonGeneratorFactory (javax.json.stream.JsonGeneratorFactory)6 Test (org.junit.Test)4 IOException (java.io.IOException)3 PrintWriter (java.io.PrintWriter)3 File (java.io.File)2 FileWriter (java.io.FileWriter)2 Map (java.util.Map)2 ServletOutputStream (javax.servlet.ServletOutputStream)2 AuthOpException (digilib.auth.AuthOpException)1 DigilibServletRequest (digilib.conf.DigilibServletRequest)1 ImageOpException (digilib.image.ImageOpException)1 DocuDirectory (digilib.io.DocuDirectory)1 FileOpException (digilib.io.FileOpException)1 ImageInput (digilib.io.ImageInput)1 ImageSet (digilib.io.ImageSet)1 ImageSize (digilib.util.ImageSize)1 FileOutputStream (java.io.FileOutputStream)1