Example usage for com.fasterxml.jackson.core JsonGenerator writeStartArray

List of usage examples for com.fasterxml.jackson.core JsonGenerator writeStartArray

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonGenerator writeStartArray.

Prototype

public abstract void writeStartArray() throws IOException, JsonGenerationException;

Source Link

Document

Method for writing starting marker of a JSON Array value (character '['; plus possible white space decoration if pretty-printing is enabled).

Usage

From source file:com.netflix.spectator.tdigest.Json.java

/** Encode the measurement using the generator. */
void encode(Map<String, String> commonTags, TDigestMeasurement m, JsonGenerator gen) throws IOException {
    TDigest digest = m.value();/*from www  . j  av a2  s.  c  o  m*/
    digest.compress();
    ByteBuffer buf = ByteBuffer.allocate(digest.byteSize());
    digest.asBytes(buf);

    gen.writeStartArray();
    gen.writeStartObject();
    gen.writeStringField("name", m.id().name());
    for (Map.Entry<String, String> e : commonTags.entrySet()) {
        gen.writeStringField(e.getKey(), e.getValue());
    }
    for (Tag t : m.id().tags()) {
        gen.writeStringField(t.key(), t.value());
    }
    gen.writeEndObject();
    gen.writeNumber(m.timestamp());
    gen.writeBinary(buf.array());
    gen.writeEndArray();
}

From source file:com.sdl.odata.renderer.json.writer.JsonPropertyWriter.java

private void writePrimitive(Object element, JsonGenerator generator) throws IOException, ODataRenderException {
    if (isCollection(element)) {
        LOG.debug("element is collection {}", element);
        generator.writeStartArray();
        for (Object obj : (List<?>) element) {
            writePrimitiveValue(obj, generator);
        }//from w  w w  .  j  av a2s.  com
        generator.writeEndArray();
    } else if (element == null) {
        generateNullPropertyString();
    } else {
        writePrimitiveValue(element, generator);
    }
}

From source file:org.emfjson.jackson.databind.ser.ResourceSerializer.java

@Override
public void serialize(Resource value, JsonGenerator jg, SerializerProvider provider) throws IOException {
    provider.setAttribute("cache", new Cache());
    provider.setAttribute("typeFactory", factory2);

    if (value.getContents().size() == 1) {
        serializeOne(value.getContents().get(0), jg, provider);
    } else {/* w  w w.  ja va 2 s . c om*/
        jg.writeStartArray();
        for (EObject o : value.getContents()) {
            serializeOne(o, jg, provider);
        }
        jg.writeEndArray();
    }
}

From source file:org.eclipse.winery.repository.resources.servicetemplates.plans.PlansResourceData.java

/**
 * Data object for the JSP/*from  w w  w.j  a v  a2  s  . c  o m*/
 *
 * @param plans the plans this resource manages
 */
public PlansResourceData(List<TPlan> plans) {
    if (plans.isEmpty()) {
        this.embeddedPlansTableData = "[]";
        this.linkedPlansTableData = "[]";
        return;
    }
    JsonFactory jsonFactory = new JsonFactory();
    StringWriter embeddedPlansTableDataSW = new StringWriter();
    StringWriter linkedPlansTableDataSW = new StringWriter();
    try {
        JsonGenerator jGeneratorEmbedded = jsonFactory.createGenerator(embeddedPlansTableDataSW);
        JsonGenerator jGeneratorLinked = jsonFactory.createGenerator(linkedPlansTableDataSW);

        jGeneratorEmbedded.writeStartArray();
        jGeneratorLinked.writeStartArray();

        for (TPlan plan : plans) {
            String name = plan.getName();
            if (name == null) {
                // name defaults to id
                name = plan.getId();
            }
            String type = PlanTypesManager.INSTANCE.getShortName(plan.getPlanType());
            String language = PlanLanguagesManager.INSTANCE.getShortName(plan.getPlanLanguage());
            PlanModelReference planModelReference = plan.getPlanModelReference();
            String reference = planModelReference != null ? planModelReference.getReference() : null;
            JsonGenerator gen;
            boolean writeReference;
            if (reference == null) {
                gen = jGeneratorEmbedded;
                writeReference = false;
            } else if (reference.startsWith("../")) {
                gen = jGeneratorEmbedded;
                writeReference = false;
            } else {
                gen = jGeneratorLinked;
                writeReference = true;
            }

            gen.writeStartArray();
            gen.writeString(plan.getId());
            gen.writeString(""); // precondition
            gen.writeString(name);
            gen.writeString(type);
            gen.writeString(language);
            if (writeReference) {
                gen.writeString(reference);
            }
            gen.writeEndArray();
        }

        jGeneratorEmbedded.writeEndArray();
        jGeneratorLinked.writeEndArray();

        jGeneratorEmbedded.close();
        embeddedPlansTableDataSW.close();
        jGeneratorLinked.close();
        linkedPlansTableDataSW.close();
    } catch (JsonGenerationException e) {
        PlansResourceData.LOGGER.error(e.getMessage(), e);
        this.embeddedPlansTableData = "[]";
        this.linkedPlansTableData = "[]";
        return;
    } catch (IOException e) {
        PlansResourceData.LOGGER.error("", e);
        this.embeddedPlansTableData = "[]";
        this.linkedPlansTableData = "[]";
        return;
    }
    this.embeddedPlansTableData = embeddedPlansTableDataSW.toString();
    this.linkedPlansTableData = linkedPlansTableDataSW.toString();
}

From source file:com.sdl.odata.renderer.json.writer.JsonPropertyWriter.java

private void processData(Object data, StructuredType type, JsonGenerator generator)
        throws IllegalAccessException, IOException, ODataException {
    if (isCollection(data)) {
        LOG.debug("Given property is collection of complex values");
        generator.writeStartArray();
        for (Object obj : (List) data) {
            writeAllProperties(obj, type, generator);
        }/*from  www  . j  av  a2  s .c o  m*/
        generator.writeEndArray();
    } else {
        LOG.debug("Given property is single complex value");
        writeAllProperties(data, type, generator);
    }

}

From source file:com.github.lynxdb.server.api.http.handlers.EpQuery.java

private void saveResponse(OutputStream _output, List<Query> _queries) throws IOException {
    JsonFactory jFactory = new JsonFactory();
    JsonGenerator jGenerator;

    jGenerator = jFactory.createGenerator(_output, JsonEncoding.UTF8);
    jGenerator.writeStartArray();

    for (Query q : _queries) {
        TimeSerie ts;/*from  www .j  av a 2s .  com*/

        ts = engine.query(q);

        jGenerator.writeStartObject();

        jGenerator.writeStringField("metric", q.getName());

        //tags
        jGenerator.writeObjectFieldStart("tags");
        if (q.getTags() != null) {
            for (String tagk : q.getTags().keySet()) {
                jGenerator.writeStringField(tagk, q.getTags().get(tagk));
            }
        }
        jGenerator.writeEndObject();

        //dps
        jGenerator.writeObjectFieldStart("dps");
        while (ts.hasNext()) {
            Entry e = ts.next();
            jGenerator.writeNumberField(String.valueOf(e.getTime()), e.getValue());
        }
        jGenerator.writeEndObject();

        //endQuery
        jGenerator.writeEndObject();
    }
    jGenerator.writeEndArray();
    jGenerator.close();
    _output.flush();
    _output.close();

}

From source file:org.lambdamatic.internal.elasticsearch.codec.BooleanQuerySerializer.java

@Override
public void serialize(final BooleanQuery booleanQuery, final JsonGenerator generator,
        final SerializerProvider serializers) throws IOException, JsonProcessingException {
    // if the booleanQuery does not contain other boolean queries in its elements, just write the
    // elements as an array
    if (!containsBooleanQueries(booleanQuery)) {
        generator.writeStartArray();
        for (Query query : booleanQuery.getQueries()) {
            generator.writeObject(query);
        }// w  w  w . j a  v a  2  s.c  om
        generator.writeEndArray();
    } else {
        // otherwise...
        generator.writeStartObject();
        generator.writeObjectFieldStart("bool");
        switch (booleanQuery.getType()) {
        case AND:
            // TODO: also support 'must_not' if the query is inverted.
            generator.writeArrayFieldStart("must");
            for (Query query : booleanQuery.getQueries()) {
                generator.writeObject(query);
            }
            generator.writeEndArray(); // end of 'must'
            break;
        case OR:
            generator.writeArrayFieldStart("should");
            for (Query query : booleanQuery.getQueries()) {
                generator.writeObject(query);
            }
            generator.writeEndArray();// end of 'should'
            break;
        default:
            throw new CodecException("Unexpected boolean type:" + booleanQuery.getType());
        }
        generator.writeEndObject(); // end of 'bool'
        generator.writeEndObject(); // end of root
    }
}

From source file:de.tudarmstadt.ukp.dkpro.core.io.brat.internal.model.BratAnnotationDocument.java

public void write(JsonGenerator aJG, String aText) throws IOException {
    aJG.writeStartObject();/*from w  ww  .jav a 2  s  .  com*/

    aJG.writeStringField("text", aText);

    aJG.writeFieldName("entities");
    aJG.writeStartArray();
    for (BratAnnotation ann : annotations.values()) {
        if (ann instanceof BratTextAnnotation) {
            ann.write(aJG);
        }
    }
    aJG.writeEndArray();

    aJG.writeFieldName("relations");
    aJG.writeStartArray();
    for (BratAnnotation ann : annotations.values()) {
        if (ann instanceof BratRelationAnnotation) {
            ann.write(aJG);
        }
    }
    aJG.writeEndArray();

    aJG.writeFieldName("triggers");
    aJG.writeStartArray();
    for (BratAnnotation ann : annotations.values()) {
        if (ann instanceof BratEventAnnotation) {
            ((BratEventAnnotation) ann).getTriggerAnnotation().write(aJG);
        }
    }
    aJG.writeEndArray();

    aJG.writeFieldName("events");
    aJG.writeStartArray();
    for (BratAnnotation ann : annotations.values()) {
        if (ann instanceof BratEventAnnotation) {
            ann.write(aJG);
        }
    }
    aJG.writeEndArray();

    aJG.writeFieldName("attributes");
    aJG.writeStartArray();
    for (BratAnnotation ann : annotations.values()) {
        for (BratAttribute attr : ann.getAttributes()) {
            attr.write(aJG);
        }
    }
    aJG.writeEndArray();

    aJG.writeEndObject();
}

From source file:com.cloudera.exhibit.server.json.FrameSerializer.java

@Override
public void serialize(Frame res, JsonGenerator gen, SerializerProvider provider) throws IOException {
    gen.writeStartObject();//from w  w  w .jav a  2 s.  c  o m
    gen.writeArrayFieldStart("columns");
    for (int i = 0; i < res.descriptor().size(); i++) {
        gen.writeString(res.descriptor().get(i).name);
    }
    gen.writeEndArray();

    gen.writeArrayFieldStart("data");
    for (Obs obs : res) {
        gen.writeStartArray();
        for (int i = 0; i < res.descriptor().size(); i++) {
            gen.writeObject(obs.get(i));
        }
        gen.writeEndArray();
    }
    gen.writeEndArray();
    gen.writeEndObject();
}

From source file:org.eclipse.winery.repository.resources.servicetemplates.plans.PlansResource.java

@POST
@RestDoc(methodDescription = "<p>Linked plans are currently not supported. Existing plans with the same id are overwritten</p> <p>@return JSON with .tableData: Array with row data for dataTable</p>")
@Consumes({ MediaType.MULTIPART_FORM_DATA })
@Produces(MediaType.APPLICATION_JSON)//from   ww w  .j  av  a  2 s .c  om
// the supertype consumes JSON and XML at org.eclipse.winery.repository.resources._support.collections.EntityCollectionResource.addNewElement(EntityT)
// @formatter:off
public Response onPost(@FormDataParam("planName") String name, @FormDataParam("planType") String type,
        @FormDataParam("planLanguage") @RestDocParam(description = "the plan language (e..g, BPMN or BPEL). Full URL.") String language,
        @FormDataParam("file") @RestDocParam(description = "(optional in the case of BPMN4TOSCA) file containing the plan.") InputStream uploadedInputStream,
        @FormDataParam("file") FormDataContentDisposition fileDetail,
        @FormDataParam("file") FormDataBodyPart body) {
    // @formatter:on
    if (StringUtils.isEmpty(name)) {
        return Response.status(Status.BAD_REQUEST).entity("planName must be given").build();
    }
    if (StringUtils.isEmpty(type)) {
        return Response.status(Status.BAD_REQUEST).entity("planType must be given").build();
    }
    if (StringUtils.isEmpty(language)) {
        return Response.status(Status.BAD_REQUEST).entity("planLanguage must be given").build();
    }

    boolean bpmn4toscaMode = org.eclipse.winery.common.constants.Namespaces.URI_BPMN4TOSCA_20.equals(language);
    if (!bpmn4toscaMode) {
        if (uploadedInputStream == null) {
            return Response.status(Status.BAD_REQUEST).entity("file must be given").build();
        }
    }

    // A plan carries both a name and an ID
    // To be user-friendly, we create the ID based on the name
    // the drawback is, that we do not allow two plans with the same name
    // during creation, but allow renaming plans to the same name (as we do
    // not allow ID renaming)
    String xmlId = Utils.createXMLidAsString(name);

    // BEGIN: Store plan file

    // Determine Id
    PlansId plansId = new PlansId((ServiceTemplateId) ((ServiceTemplateResource) this.res).getId());
    PlanId planId = new PlanId(plansId, new XMLId(xmlId, false));
    // Ensure overwriting
    if (Repository.INSTANCE.exists(planId)) {
        try {
            Repository.INSTANCE.forceDelete(planId);
            // Quick hack to remove the deleted plan from the plans element
            ((ServiceTemplateResource) this.res).synchronizeReferences();
        } catch (IOException e) {
            return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
        }
    }

    String fileName;
    if (bpmn4toscaMode) {
        fileName = xmlId + Constants.SUFFIX_BPMN4TOSCA;
        RepositoryFileReference ref = new RepositoryFileReference(planId, fileName);
        try {
            Repository.INSTANCE.putContentToFile(ref, "{}", MediaType.APPLICATION_JSON_TYPE);
        } catch (IOException e1) {
            return Response.status(Status.INTERNAL_SERVER_ERROR)
                    .entity("Could not create empty plan. " + e1.getMessage()).build();
        }
    } else {
        // We use the filename also as local file name. Alternatively, we could use the xml id
        // With URL encoding, this should not be an issue
        fileName = Util.URLencode(fileDetail.getFileName());

        // Really store it
        RepositoryFileReference ref = new RepositoryFileReference(planId, fileName);
        try {
            Repository.INSTANCE.putContentToFile(ref, uploadedInputStream, body.getMediaType());
        } catch (IOException e1) {
            return Response.status(Status.INTERNAL_SERVER_ERROR)
                    .entity("Could not store plan. " + e1.getMessage()).build();
        }
    }
    // END: Store plan file

    TPlan plan = new TPlan();
    plan.setId(xmlId);
    plan.setName(name);
    plan.setPlanType(type);
    plan.setPlanLanguage(language);
    PlansResource.setPlanModelReference(plan, planId, fileName);
    this.list.add(plan);

    // prepare result
    JsonFactory jsonFactory = new JsonFactory();
    StringWriter sw = new StringWriter();
    try {
        JsonGenerator jGenerator = jsonFactory.createGenerator(sw);
        jGenerator.writeStartObject();
        jGenerator.writeFieldName("tableData");
        jGenerator.writeStartArray();
        jGenerator.writeString(xmlId);
        jGenerator.writeString(""); // precondition
        jGenerator.writeString(name);
        jGenerator.writeString(PlanTypesManager.INSTANCE.getShortName(type));
        jGenerator.writeString(PlanLanguagesManager.INSTANCE.getShortName(language));
        jGenerator.writeEndArray();
        jGenerator.writeEndObject();
        jGenerator.close();
        sw.close();
    } catch (JsonGenerationException e) {
        PlansResource.logger.error(e.getMessage(), e);
        return Response.serverError().build();
    } catch (IOException e) {
        PlansResource.logger.error(e.getMessage(), e);
        return Response.serverError().build();
    }

    Response res = BackendUtils.persist(this.res);
    if (res.getStatus() == 204) {
        // everything OK, return created
        return Response.created(Utils.createURI(Util.URLencode(xmlId))).entity(sw.toString()).build();
    } else {
        return res;
    }
}