Example usage for com.fasterxml.jackson.core JsonFactory createGenerator

List of usage examples for com.fasterxml.jackson.core JsonFactory createGenerator

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonFactory createGenerator.

Prototype

public JsonGenerator createGenerator(Writer out) throws IOException 

Source Link

Document

Method for constructing JSON generator for writing JSON content using specified Writer.

Usage

From source file:com.cinnober.msgcodec.json.JsonCodec.java

/**
 * Write the group to the stream, but without adding the '$type' field.
 * To decode the JSON the receiver must know what group type to expect.
 *
 * @param group the group to encode./*  ww w  . j a  v  a  2 s.c  o m*/
 * @param out the stream to write to, not null.
 * @throws IOException if the underlying byte sink throws an exception.
 * @throws IllegalArgumentException if the group is not correct or complete, e.g. a required field is missing.
 * Partial data may have been written to the stream.
 */
public void encodeStatic(Object group, OutputStream out) throws IOException {
    if (group == null) {
        out.write(NULL_BYTES);
    } else {
        JsonFactory f = new JsonFactory();
        JsonGenerator g = f.createGenerator(out);
        StaticGroupHandler groupHandler = lookupGroupByValue(group);
        if (groupHandler == null) {
            throw new IllegalArgumentException("Cannot encode group (unknown type)");
        }
        groupHandler.writeValue(group, g, false);
        g.flush();
    }
}

From source file:com.cinnober.msgcodec.json.JsonCodec.java

/**
 * Write the group to the byte sink, but without adding the '$type' field.
 * To decode the JSON the receiver must know what group type to expect.
 *
 * @param group the group to encode./*from   ww  w .  j  a  v  a2s .c o m*/
 * @param out the byte sink to write to, not null.
 * @throws IOException if the underlying byte sink throws an exception.
 * @throws IllegalArgumentException if the group is not correct or complete, e.g. a required field is missing.
 * Partial data may have been written to the byte sink.
 */
public void encodeStatic(Object group, ByteSink out) throws IOException {
    if (group == null) {
        out.write(NULL_BYTES);
    } else {
        JsonFactory f = new JsonFactory();
        JsonGenerator g = f.createGenerator(new ByteSinkOutputStream(out));
        StaticGroupHandler groupHandler = lookupGroupByValue(group);
        if (groupHandler == null) {
            throw new IllegalArgumentException("Cannot encode group (unknown type)");
        }
        groupHandler.writeValue(group, g, false);
        g.flush();
    }
}

From source file:org.graylog.plugins.beats.BeatsFrameDecoder.java

/**
 * @see <a href="https://github.com/logstash-plugins/logstash-input-beats/blob/master/PROTOCOL.md#data-frame-type">'data' frame type</a>
 *///ww  w  .  j a  va2 s .  c o m
private ChannelBuffer[] parseDataFrame(Channel channel, ChannelBuffer channelBuffer) throws IOException {
    if (channelBuffer.readableBytes() >= 8) {
        sequenceNum = channelBuffer.readUnsignedInt();
        LOG.trace("Received sequence number {}", sequenceNum);

        final int pairs = Ints.saturatedCast(channelBuffer.readUnsignedInt());
        final JsonFactory jsonFactory = new JsonFactory();
        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try (final JsonGenerator jg = jsonFactory.createGenerator(outputStream)) {
            jg.writeStartObject();
            for (int i = 0; i < pairs; i++) {
                final String key = parseDataItem(channelBuffer);
                final String value = parseDataItem(channelBuffer);
                jg.writeStringField(key, value);
            }
            jg.writeEndObject();
        }

        final ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(outputStream.toByteArray());
        sendACK(channel);

        return new ChannelBuffer[] { buffer };
    }

    return null;
}

From source file:com.quinsoft.zeidon.standardoe.WriteOisToJsonStream.java

@Override
public void writeToStream(SerializeOi options, Writer writer) {
    this.viewList = options.getViewList();
    this.options = options;
    if (options.getFlags() == null)
        flags = EnumSet.noneOf(WriteOiFlags.class);
    else/*w  w  w  . jav  a 2  s .c om*/
        flags = options.getFlags();
    if (!flags.contains(WriteOiFlags.INCREMENTAL))
        throw new ZeidonException("This JSON stream writer intended for writing incremental.");

    // Create a set of all the OIs and turn off the record owner flag.  The record owner
    // flag will be used to determine if a linked EI has been written to the stream.
    for (View view : viewList) {
        ObjectInstance oi = ((InternalView) view).getViewImpl().getObjectInstance();
        ois.add(oi);
        for (EntityInstanceImpl ei = oi.getRootEntityInstance(); ei != null; ei = ei.getNextTwin())
            ei.setRecordOwner(false);
    }

    JsonFactory jsonF = new JsonFactory();
    try {
        jg = jsonF.createGenerator(writer);
        if (!options.isCompressed())
            jg.useDefaultPrettyPrinter(); // enable indentation just to make debug/testing easier

        jg.writeStartObject();

        // Write meta info for entire JSON object.
        jg.writeObjectFieldStart(".meta");
        jg.writeStringField("version", VERSION);
        if (options.isWriteDate())
            jg.writeStringField("datetime", new LocalDateTime().toString());
        jg.writeEndObject();

        jg.writeArrayFieldStart("OIs");

        for (View view : viewList) {
            currentView = view;
            jg.writeStartObject();
            writeOi(view);
            jg.writeEndObject();
        }
        jg.writeEndArray();
        jg.writeEndObject();
        jg.close();
    } catch (Exception e) {
        throw ZeidonException.wrapException(e);
    }
}

From source file:com.joliciel.jochre.search.highlight.HighlightManagerImpl.java

@Override
public void highlight(Highlighter highlighter, Set<Integer> docIds, Set<String> fields, Writer out) {
    try {/*from ww w .ja v a2  s . c om*/
        Map<Integer, Set<HighlightTerm>> termMap = highlighter.highlight(docIds, fields);
        JsonFactory jsonFactory = new JsonFactory();
        JsonGenerator jsonGen = jsonFactory.createGenerator(out);

        jsonGen.writeStartObject();

        for (int docId : docIds) {
            Document doc = indexSearcher.doc(docId);
            jsonGen.writeObjectFieldStart(doc.get("id"));
            jsonGen.writeStringField("path", doc.get("path"));
            jsonGen.writeNumberField("docId", docId);

            jsonGen.writeArrayFieldStart("terms");
            for (HighlightTerm term : termMap.get(docId)) {
                fields.add(term.getField());
                term.toJson(jsonGen, df);
            }
            jsonGen.writeEndArray();

            if (includeText) {
                for (String field : fields) {
                    jsonGen.writeObjectFieldStart("field" + field);
                    Set<HighlightTerm> terms = termMap.get(docId);
                    jsonGen.writeStringField("contents", this.displayHighlights(docId, field, terms));
                    jsonGen.writeEndObject();
                }
            }

            jsonGen.writeEndObject();
        }

        jsonGen.writeEndObject();
        jsonGen.flush();
    } catch (IOException ioe) {
        LogUtils.logError(LOG, ioe);
        throw new RuntimeException(ioe);
    }
}

From source file:com.yahoo.ycsb.db.CouchbaseClient.java

/**
 * Encode the object for couchbase storage.
 *
 * @param source the source value.//from   w w  w  .  ja v a2  s .c o m
 * @return the storable object.
 */
private Object encode(final HashMap<String, ByteIterator> source) {
    HashMap<String, String> stringMap = StringByteIterator.getStringMap(source);
    if (!useJson) {
        return stringMap;
    }

    ObjectNode node = JSON_MAPPER.createObjectNode();
    for (Map.Entry<String, String> pair : stringMap.entrySet()) {
        node.put(pair.getKey(), pair.getValue());
    }
    JsonFactory jsonFactory = new JsonFactory();
    Writer writer = new StringWriter();
    try {
        JsonGenerator jsonGenerator = jsonFactory.createGenerator(writer);
        JSON_MAPPER.writeTree(jsonGenerator, node);
    } catch (Exception e) {
        throw new RuntimeException("Could not encode JSON value");
    }
    return writer.toString();
}

From source file:eu.project.ttc.engines.exporter.JsonCasExporter.java

@Override
public void process(JCas aJCas) throws AnalysisEngineProcessException {
    /*//from  w  w w. j  a v a2 s.c  om
     *  Cette mthode est appele par le framework UIMA
     *  pour chaque document  de ta collection (corpus).
     *
     *  Tu peux gnrer ton fichier compagnon dans cette mthode.
     *  (Je te donne l'astuce pour retrouver le nom et le chemin du fichier
     *  de ton corpus correspondant au CAS pass en paramtre de cette
     *  mthode plus tard)
     */

    FSIterator<Annotation> it = aJCas.getAnnotationIndex().iterator();
    Annotation a;
    JsonFactory jsonFactory = new JsonFactory();
    String name = this.getExportFilePath(aJCas, "json");
    File file = new File(this.directoryFile, name);
    FileWriter writer = null;
    try {
        writer = new FileWriter(file);
        LOGGER.debug("Writing " + file.getPath());
        JsonGenerator jg = jsonFactory.createGenerator(writer);
        jg.useDefaultPrettyPrinter();
        jg.writeStartObject();
        jg.writeStringField("file", name);
        jg.writeArrayFieldStart("tag");
        while (it.hasNext()) {
            a = it.next();
            if (a instanceof WordAnnotation) {
                jg.writeStartObject();
                WordAnnotation wordAnno = (WordAnnotation) a;
                for (Feature feat : wordAnno.getType().getFeatures()) {
                    FeatureStructure featureValue = wordAnno.getFeatureValue(feat);
                    if (featureValue != null) {
                        jg.writeFieldName(feat.getName());
                        jg.writeObject(featureValue);
                    }
                }
                jg.writeStringField("tag", wordAnno.getTag());
                jg.writeStringField("lemma", wordAnno.getLemma());
                jg.writeNumberField("begin", wordAnno.getBegin());
                jg.writeNumberField("end", wordAnno.getEnd());
                jg.writeEndObject();
            }
        }
        jg.writeEndArray();
        jg.writeEndObject();
        jg.flush();
        writer.close();
    } catch (IOException e) {
        LOGGER.error("Failure while serializing " + name + "\nCaused by" + e.getClass().getCanonicalName() + ":"
                + e.getMessage(), e);
    }
}

From source file:org.eclipse.winery.repository.rest.resources.AbstractComponentsResource.java

/**
 * Used by org.eclipse.winery.repository.repository.client and by the artifactcreationdialog.tag. Especially the
 * "name" field is used there at the UI//from  w w w. j  av  a  2 s  .  co  m
 *
 * @param grouped if given, the JSON output is grouped by namespace
 * @return A list of all ids of all instances of this component type. <br /> Format: <code>[({"namespace":
 * "[namespace]", "id": "[id]"},)* ]</code>. <br /><br /> If grouped is set, the list will be grouped by namespace.
 * <br /> <code>[{"id": "[namsepace encoded]", "test": "[namespace decoded]", "children":[{"id": "[qName]", "text":
 * "[id]"}]}]</code>
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getListOfAllIds(@QueryParam("grouped") String grouped) {
    Class<? extends TOSCAComponentId> idClass = RestUtils
            .getComponentIdClassForComponentContainer(this.getClass());
    boolean supportsNameAttribute = Util.instanceSupportsNameAttribute(idClass);
    SortedSet<? extends TOSCAComponentId> allTOSCAcomponentIds = RepositoryFactory.getRepository()
            .getAllTOSCAComponentIds(idClass);
    JsonFactory jsonFactory = new JsonFactory();
    StringWriter sw = new StringWriter();
    try {
        JsonGenerator jg = jsonFactory.createGenerator(sw);
        // We produce org.eclipse.winery.repository.client.WineryRepositoryClient.NamespaceAndId by hand here
        // Refactoring could move this class to common and fill it here
        if (grouped == null) {
            jg.writeStartArray();
            for (TOSCAComponentId id : allTOSCAcomponentIds) {
                jg.writeStartObject();
                jg.writeStringField("namespace", id.getNamespace().getDecoded());
                jg.writeStringField("id", id.getXmlId().getDecoded());
                if (supportsNameAttribute) {
                    AbstractComponentInstanceResource componentInstaceResource = AbstractComponentsResource
                            .getComponentInstaceResource(id);
                    String name = ((IHasName) componentInstaceResource).getName();
                    jg.writeStringField("name", name);
                } else {
                    // used for winery-qNameSelector to avoid an if there
                    jg.writeStringField("name", id.getXmlId().getDecoded());
                }
                jg.writeStringField("qName", id.getQName().toString());
                jg.writeEndObject();
            }
            jg.writeEndArray();
        } else {
            jg.writeStartArray();
            Map<Namespace, ? extends List<? extends TOSCAComponentId>> groupedIds = allTOSCAcomponentIds
                    .stream().collect(Collectors.groupingBy(id -> id.getNamespace()));
            groupedIds.keySet().stream().sorted().forEach(namespace -> {
                try {
                    jg.writeStartObject();
                    jg.writeStringField("id", namespace.getEncoded());
                    jg.writeStringField("text", namespace.getDecoded());
                    jg.writeFieldName("children");
                    jg.writeStartArray();
                    groupedIds.get(namespace).forEach(id -> {
                        try {
                            jg.writeStartObject();
                            String text;
                            if (supportsNameAttribute) {
                                AbstractComponentInstanceResource componentInstaceResource = AbstractComponentsResource
                                        .getComponentInstaceResource(id);
                                text = ((IHasName) componentInstaceResource).getName();
                            } else {
                                text = id.getXmlId().getDecoded();
                            }
                            jg.writeStringField("id", id.getQName().toString());
                            jg.writeStringField("text", text);
                            jg.writeEndObject();
                        } catch (IOException e) {
                            AbstractComponentsResource.LOGGER.error("Could not create JSON", e);
                        }
                    });
                    jg.writeEndArray();
                    jg.writeEndObject();
                } catch (IOException e) {
                    AbstractComponentsResource.LOGGER.error("Could not create JSON", e);
                }
            });
            jg.writeEndArray();
        }
        jg.close();
    } catch (Exception e) {
        AbstractComponentsResource.LOGGER.error(e.getMessage(), e);
        return "[]";
    }
    return sw.toString();
}

From source file:com.joliciel.jochre.search.highlight.HighlightManagerImpl.java

@Override
public void findSnippets(Highlighter highlighter, Set<Integer> docIds, Set<String> fields, Writer out) {
    try {// w w  w  .  j  a  va 2s . c o  m
        Map<Integer, Set<HighlightTerm>> termMap = highlighter.highlight(docIds, fields);
        Map<Integer, List<Snippet>> snippetMap = this.findSnippets(docIds, fields, termMap,
                this.getSnippetCount(), this.getSnippetSize());

        JsonFactory jsonFactory = new JsonFactory();
        JsonGenerator jsonGen = jsonFactory.createGenerator(out);

        jsonGen.writeStartObject();

        for (int docId : docIds) {
            Document doc = indexSearcher.doc(docId);
            jsonGen.writeObjectFieldStart(doc.get("id"));
            jsonGen.writeStringField("path", doc.get("path"));
            jsonGen.writeNumberField("docId", docId);

            jsonGen.writeArrayFieldStart("snippets");
            for (Snippet snippet : snippetMap.get(docId)) {
                snippet.toJson(jsonGen, df);
            }
            jsonGen.writeEndArray();

            if (includeText) {
                jsonGen.writeArrayFieldStart("snippetText");
                for (Snippet snippet : snippetMap.get(docId)) {
                    jsonGen.writeStartObject();
                    jsonGen.writeStringField("snippet", this.displaySnippet(docId, snippet));
                    jsonGen.writeEndObject();
                }
                jsonGen.writeEndArray();
            }

            if (includeGraphics) {
                jsonGen.writeArrayFieldStart("snippetGraphics");
                for (Snippet snippet : snippetMap.get(docId)) {
                    jsonGen.writeStartObject();
                    ImageSnippet imageSnippet = this.getImageSnippet(snippet);
                    jsonGen.writeNumberField("left", imageSnippet.getRectangle().getLeft());
                    jsonGen.writeNumberField("top", imageSnippet.getRectangle().getTop());
                    jsonGen.writeNumberField("right", imageSnippet.getRectangle().getRight());
                    jsonGen.writeNumberField("bottom", imageSnippet.getRectangle().getBottom());

                    jsonGen.writeArrayFieldStart("highlights");
                    for (Rectangle highlight : imageSnippet.getHighlights()) {
                        jsonGen.writeStartObject();
                        jsonGen.writeNumberField("left", highlight.getLeft());
                        jsonGen.writeNumberField("top", highlight.getTop());
                        jsonGen.writeNumberField("right", highlight.getRight());
                        jsonGen.writeNumberField("bottom", highlight.getBottom());
                        jsonGen.writeEndObject();
                    }
                    jsonGen.writeEndArray();
                    jsonGen.writeEndObject();
                }
                jsonGen.writeEndArray();
            }
            jsonGen.writeEndObject();
        } // next doc

        jsonGen.writeEndObject();
        jsonGen.flush();
    } catch (IOException ioe) {
        LogUtils.logError(LOG, ioe);
        throw new RuntimeException(ioe);
    }
}

From source file:tds.student.web.backing.TestShellScriptsBacking.java

private void addTestSegments() throws IOException, ReturnStatusException {
    TestSession testSession = StudentContext.getSession();
    // _studentSettings = FacesContextHelper.getBean ("studentSettings",
    // StudentSettings.class);
    OpportunitySegments oppSegments = null;

    // load opp segments only if there are any test segments
    if (_testProps.getSegments().size() > 0) {
        oppSegments = this._iOpportunityService.getSegments(this._testOpportunity.getOppInstance(),
                !this._studentSettings.isReadOnly());
    }//  www  . ja v  a2  s  .c o m

    StringWriter sw = new StringWriter();
    JsonFactory jsonFactory = new JsonFactory();
    JsonGenerator writer = jsonFactory.createGenerator(sw);

    writer.writeStartArray(); // [

    for (final TestSegment testSegment : _testProps.getSegments()) {
        OpportunitySegment oppSegment = null;

        // find opportunity segment
        if (oppSegments != null) {
            oppSegment = (OpportunitySegment) CollectionUtils.find(oppSegments, new Predicate() {
                @Override
                public boolean evaluate(Object arg0) {
                    if (StringUtils.equals(((OpportunitySegment) arg0).getId(), testSegment.getId()))
                        return true;
                    return false;
                }
            });
        }

        // figure out segment permeability
        int isPermeable = testSegment.getIsPermeable();
        int updatePermeable = isPermeable;

        // these are local override rules (reviewed with Larry)
        if (oppSegment != null) {
            /*
             * if -1, use the defined value for the segment as returned by
             * IB_GetSegments if not -1, then the local value defines the temporary
             * segment permeability
             */
            if (oppSegment.getIsPermeable() != -1) {
                isPermeable = oppSegment.getIsPermeable();

                /*
                 * The default permeability is restored when the student leaves the
                 * segment while testing. Assuming the segment is impermeable, this
                 * allows the student one entry into the segment during the sitting.
                 * When the student leaves the segment, is membrane is enforced by the
                 * student app. The database will restore the default value of the
                 * segment membrane when the test is paused.
                 */
                if (oppSegment.getRestorePermOn() != "segment") {
                    updatePermeable = oppSegment.getIsPermeable();
                }
            }

            // NOTE: When student enters segment, set isPermeable = updatePermeable
        }

        // if read only mode is enabled then we should let user have access
        if (_studentSettings.isReadOnly()) {
            isPermeable = 1;
            updatePermeable = 1;
        }

        // figure out segment approval
        int entryApproval = testSegment.getEntryApproval();
        int exitApproval = testSegment.getExitApproval();

        // NOTE: If proctorless test then don't require entry/exit approval
        // (nobody to approve it)
        if (testSession.isProctorless() || _studentSettings.isReadOnly()) {
            entryApproval = 0;
            exitApproval = 0;
        }
        // BUG #22642: Entry and Exit approvals are not needed from Test level
        // review screen when approval = 2
        else if (getViewPageNumber() > 0) {
            if (testSegment.getEntryApproval() == 2)
                entryApproval = 0;
            if (testSegment.getExitApproval() == 2)
                exitApproval = 0;
        }

        // write segment json
        writer.writeStartObject();
        writer.writeStringField("type", "object"); // {
        writer.writeStringField("id", testSegment.getId());
        writer.writeNumberField("position", testSegment.getPosition());
        writer.writeStringField("label", testSegment.getLabel());
        writer.writeBooleanField("itemReview", testSegment.isItemReview());
        writer.writeNumberField("isPermeable", isPermeable);
        writer.writeNumberField("updatePermeable", updatePermeable);
        writer.writeNumberField("entryApproval", entryApproval);
        writer.writeNumberField("exitApproval", exitApproval);

        // Looks like we don't use this variable in javascript (removed for 2012)
        // Test adaptiveSegment =
        // TestOpportunity.AdaptiveTest.GetSegmentTest(testSegment.ID);
        // writer.WriteObject("length", (adaptiveSegment != null) ?
        // adaptiveSegment.TotalMinLength : 0);

        writer.writeEndObject(); // }
    }

    writer.writeEndArray(); // ]

    writer.close();

    // write out javascript
    StringBuilder javascript = new StringBuilder();
    javascript.append("var tdsSegments = ");
    javascript.append(sw.toString());
    javascript.append("; ");

    this.getClientScript().addToJsCode(javascript.toString());

}