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

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

Introduction

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

Prototype

public abstract void writeObject(Object pojo) throws IOException, JsonProcessingException;

Source Link

Document

Method for writing given Java object (POJO) as Json.

Usage

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

@Override
public void process(JCas aJCas) throws AnalysisEngineProcessException {
    /*//w  w w  .ja  va2s.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.killbill.billing.plugin.meter.api.user.DefaultJsonSamplesOutputer.java

@Override
protected void writeJsonForChunks(final JsonGenerator generator,
        final Collection<? extends TimelineChunk> chunksForSourceAndMetric) throws IOException {
    for (final TimelineChunk chunk : chunksForSourceAndMetric) {
        final String source = timelineDao.getSource(chunk.getSourceId(), context);
        final CategoryRecordIdAndMetric categoryIdAndMetric = timelineDao
                .getCategoryIdAndMetric(chunk.getMetricId(), context);
        final String eventCategory = timelineDao.getEventCategory(categoryIdAndMetric.getEventCategoryId(),
                context);//from w w w . j av a  2s .  c  o m
        final String metric = categoryIdAndMetric.getMetric();

        final String samples = CSVConsumer.getSamplesAsCSV(sampleCoder, chunk);

        // Don't write out empty samples
        if (!Strings.isNullOrEmpty(samples)) {
            generator.writeObject(new SamplesForMetricAndSource(source, eventCategory, metric, samples));
        }
    }
}

From source file:models.CategorySerializer.java

@Override
public void serialize(Category cat, JsonGenerator jgen, SerializerProvider provider) throws IOException {
    jgen.writeStartObject();//from   ww w .  jav a2  s  .  c  o m
    jgen.writeStringField("id", cat.getId());
    jgen.writeStringField("label", cat.getLabel());
    jgen.writeFieldName("children");
    jgen.writeStartArray();
    for (Object obj : cat.getChildren()) {
        if (obj instanceof Group) {
            Group group = (Group) obj;
            jgen.writeStartObject();
            jgen.writeStringField("id", group.getId());
            jgen.writeStringField("label", group.getLabel());
            if (group.getType() == Type.PROCESS) {
                jgen.writeStringField("type", "PROCESS");
            } else {
                jgen.writeStringField("type", "COEFFICIENT");
            }
            jgen.writeEndObject();
        } else {
            jgen.writeObject(obj);
        }
    }
    jgen.writeEndArray();
    jgen.writeEndObject();
}

From source file:org.hawkular.rest.json.RelationshipJacksonSerializer.java

/**
 * <pre>compact:/* w  w  w .  j  a  va2s .c  o m*/
 * {
 *   "id": "1337",
 *   "source": "/tenants/28026b36-8fe4-4332-84c8-524e173a68bf",
 *   "name": "contains",
 *   "target": "28026b36-8fe4-4332-84c8-524e173a68bf/environments/test"
 * }</pre>
 * <p/>
 * <pre>embedded:
 * {
 *   "@context": "http://hawkular.org/inventory/0.1.0/relationship.jsonld",
 *   "id": "1337",
 *   "name": "contains",
 *   "source": {
 *      id: "/tenants/28026b36-8fe4-4332-84c8-524e173a68bf",
 *      shortId: "28026b36-8fe4-4332-84c8-524e173a68bf",
 *      type: "Tenant"
 *   },
 *   "target": {
 *      id: "28026b36-8fe4-4332-84c8-524e173a68bf/environments/test",
 *      shortId: "test",
 *      type: "Environment"
 *   }
 * }</pre>
 */
@Override
public void serialize(Relationship relationship, JsonGenerator jg, SerializerProvider serializerProvider)
        throws IOException {
    jg.writeStartObject();

    jg.writeFieldName(FIELD_ID);
    jg.writeString(relationship.getId());

    jg.writeFieldName(FIELD_NAME);
    jg.writeString(relationship.getName());

    jg.writeFieldName(FIELD_SOURCE);
    jg.writeString(relationship.getSource().toString());

    jg.writeFieldName(FIELD_TARGET);
    jg.writeString(relationship.getTarget().toString());

    if (relationship.getProperties() != null && !relationship.getProperties().isEmpty()) {
        jg.writeFieldName(FIELD_PROPERTIES);
        jg.writeStartObject();
        for (Map.Entry<String, Object> property : relationship.getProperties().entrySet()) {
            jg.writeFieldName(property.getKey());
            jg.writeObject(property.getValue());
        }
        jg.writeEndObject();
    }

    jg.writeEndObject();
}

From source file:org.killbill.billing.plugin.meter.api.user.AccumulatingJsonSamplesOutputer.java

@Override
protected void writeJsonForChunks(final JsonGenerator generator,
        final Collection<? extends TimelineChunk> chunksForSourceAndMetric) throws IOException {
    for (final TimelineChunk chunk : chunksForSourceAndMetric) {
        final String source = timelineDao.getSource(chunk.getSourceId(), context);
        final CategoryRecordIdAndMetric categoryIdAndMetric = timelineDao
                .getCategoryIdAndMetric(chunk.getMetricId(), context);
        final String eventCategory = timelineDao.getEventCategory(categoryIdAndMetric.getEventCategoryId(),
                context);/* ww w  .  j ava 2 s . co  m*/
        final String metric = categoryIdAndMetric.getMetric();

        final String samples = CSVConsumer.getSamplesAsCSV(sampleCoder, chunk, accumulatorSampleConsumer);

        // Don't write out empty samples
        if (!Strings.isNullOrEmpty(samples)) {
            generator.writeObject(new SamplesForMetricAndSource(source, eventCategory, metric, samples));
        }

        lastSource = source;
        lastEventCategory = eventCategory;
        lastMetric = metric;
    }
}

From source file:gov.bnl.channelfinder.ChannelsResource.java

/**
 * GET method for retrieving a collection of Channel instances,
 * based on a multi-parameter query specifiying patterns for tags, property values,
 * and channel names to match against./*from w  ww  .j a  v  a  2s  .c om*/
 *
 * @return HTTP Response
 */
@GET
@Produces({ "application/json" })
public Response query() {
    StringBuffer performance = new StringBuffer();
    long start = System.currentTimeMillis();
    long totalStart = System.currentTimeMillis();
    Client client = ElasticSearchClient.getSearchClient();
    start = System.currentTimeMillis();
    String user = securityContext.getUserPrincipal() != null ? securityContext.getUserPrincipal().getName()
            : "";
    try {
        MultivaluedMap<String, String> parameters = uriInfo.getQueryParameters();
        BoolQueryBuilder qb = boolQuery();
        int size = 10000;
        for (Entry<String, List<String>> parameter : parameters.entrySet()) {
            switch (parameter.getKey()) {
            case "~name":
                for (String value : parameter.getValue()) {
                    DisMaxQueryBuilder nameQuery = disMaxQuery();
                    for (String pattern : value.split("\\|")) {
                        nameQuery.add(wildcardQuery("name", pattern.trim()));
                    }
                    qb.must(nameQuery);
                }
                break;
            case "~tag":
                for (String value : parameter.getValue()) {
                    DisMaxQueryBuilder tagQuery = disMaxQuery();
                    for (String pattern : value.split("\\|")) {
                        tagQuery.add(wildcardQuery("tags.name", pattern.trim()));
                    }
                    qb.must(nestedQuery("tags", tagQuery));
                }
                break;
            case "~size":
                Optional<String> maxSize = parameter.getValue().stream().max((o1, o2) -> {
                    return Integer.valueOf(o1).compareTo(Integer.valueOf(o2));
                });
                if (maxSize.isPresent()) {
                    size = Integer.valueOf(maxSize.get());
                }
            default:
                DisMaxQueryBuilder propertyQuery = disMaxQuery();
                for (String value : parameter.getValue()) {
                    for (String pattern : value.split("\\|")) {
                        propertyQuery.add(nestedQuery("properties",
                                boolQuery().must(matchQuery("properties.name", parameter.getKey().trim()))
                                        .must(wildcardQuery("properties.value", pattern.trim()))));
                    }
                }
                qb.must(propertyQuery);
                break;
            }
        }

        performance.append("|prepare:" + (System.currentTimeMillis() - start));
        start = System.currentTimeMillis();
        final SearchResponse qbResult = client.prepareSearch("channelfinder").setQuery(qb).setSize(size)
                .execute().actionGet();
        performance.append(
                "|query:(" + qbResult.getHits().getTotalHits() + ")" + (System.currentTimeMillis() - start));
        start = System.currentTimeMillis();
        final ObjectMapper mapper = new ObjectMapper();
        mapper.addMixIn(XmlProperty.class, OnlyXmlProperty.class);
        mapper.addMixIn(XmlTag.class, OnlyXmlTag.class);
        start = System.currentTimeMillis();

        StreamingOutput stream = new StreamingOutput() {

            @Override
            public void write(OutputStream os) throws IOException, WebApplicationException {
                JsonGenerator jg = mapper.getFactory().createGenerator(os, JsonEncoding.UTF8);
                jg.writeStartArray();
                if (qbResult != null) {
                    for (SearchHit hit : qbResult.getHits()) {
                        jg.writeObject(mapper.readValue(hit.source(), XmlChannel.class));
                        jg.flush();
                    }
                }
                jg.writeEndArray();
                jg.flush();
                jg.close();
            }
        };

        performance.append("|parse:" + (System.currentTimeMillis() - start));
        Response r = Response.ok(stream).build();
        log.info(user + "|" + uriInfo.getPath() + "|GET|OK" + performance.toString() + "|total:"
                + (System.currentTimeMillis() - totalStart) + "|" + r.getStatus() + "|returns "
                + qbResult.getHits().getTotalHits() + " channels");
        //            log.info( qbResult.getHits().getTotalHits() + " " +(System.currentTimeMillis() - totalStart));
        return r;
    } catch (Exception e) {
        return handleException(user, "GET", Response.Status.INTERNAL_SERVER_ERROR, e);
    } finally {
    }
}

From source file:gov.bnl.channelfinder.PropertiesResource.java

/**
 * GET method for retrieving the list of properties in the database.
 *
 * @return list of properties/*from  ww  w. j a  v  a2 s  . c  om*/
 */
@GET
@Produces({ MediaType.APPLICATION_JSON })
public Response list() {
    Client client = getNewClient();
    final String user = securityContext.getUserPrincipal() != null
            ? securityContext.getUserPrincipal().getName()
            : "";
    final ObjectMapper mapper = new ObjectMapper();
    mapper.addMixIn(XmlProperty.class, OnlyXmlProperty.class);
    try {
        MultivaluedMap<String, String> parameters = uriInfo.getQueryParameters();
        int size = 10000;
        if (parameters.containsKey("~size")) {
            Optional<String> maxSize = parameters.get("~size").stream().max((o1, o2) -> {
                return Integer.valueOf(o1).compareTo(Integer.valueOf(o2));
            });
            if (maxSize.isPresent()) {
                size = Integer.valueOf(maxSize.get());
            }

        }
        final SearchResponse response = client.prepareSearch("properties").setTypes("property")
                .setQuery(new MatchAllQueryBuilder()).setSize(size).execute().actionGet();
        StreamingOutput stream = new StreamingOutput() {
            @Override
            public void write(OutputStream os) throws IOException, WebApplicationException {
                JsonGenerator jg = mapper.getFactory().createGenerator(os, JsonEncoding.UTF8);
                jg.writeStartArray();
                if (response != null) {
                    for (SearchHit hit : response.getHits()) {
                        jg.writeObject(mapper.readValue(hit.source(), XmlProperty.class));
                    }
                }
                jg.writeEndArray();
                jg.flush();
                jg.close();
            }
        };
        Response r = Response.ok(stream).build();
        audit.info(user + "|" + uriInfo.getPath() + "|GET|OK|" + r.getStatus() + "|returns "
                + response.getHits().getTotalHits() + " properties");
        return r;
    } catch (Exception e) {
        return handleException(user, "GET", Response.Status.INTERNAL_SERVER_ERROR, e);
    } finally {
        client.close();
    }
}

From source file:com.spotify.apollo.meta.TypesafeConfigSerializer.java

@Override
public void serialize(ConfigValue value, JsonGenerator jgen, SerializerProvider provider) throws IOException {

    if (value.valueType() == ConfigValueType.OBJECT) {
        final ConfigObject object = (ConfigObject) value;

        jgen.writeStartObject();/* w ww .j  a v  a2s  .  c  om*/
        for (Map.Entry<String, ConfigValue> valueEntry : object.entrySet()) {
            if (withOrigins) {
                final ConfigOrigin origin = valueEntry.getValue().origin();
                jgen.writeStringField(valueEntry.getKey() + "__origin",
                        origin.description() + (origin.filename() != null ? ", " + origin.filename() : ""));
            }
            jgen.writeObjectField(valueEntry.getKey(), valueEntry.getValue());
        }
        jgen.writeEndObject();
    } else if (value.valueType() == ConfigValueType.LIST) {
        final ConfigList list = (ConfigList) value;

        jgen.writeStartArray();
        for (ConfigValue configValue : list) {
            jgen.writeObject(configValue);
        }
        jgen.writeEndArray();
    } else {
        jgen.writeObject(value.unwrapped());
    }
}

From source file:gov.bnl.channelfinder.TagsResource.java

/**
 * GET method for retrieving the list of tags in the database.
 *
 * @return list of tags/*from   w w w . j  a  v  a  2 s.com*/
 */
@GET
@Produces({ MediaType.APPLICATION_JSON })
public Response list() {
    Client client = getNewClient();
    String user = securityContext.getUserPrincipal() != null ? securityContext.getUserPrincipal().getName()
            : "";
    final ObjectMapper mapper = new ObjectMapper();
    mapper.addMixIn(XmlTag.class, OnlyXmlTag.class);
    try {
        MultivaluedMap<String, String> parameters = uriInfo.getQueryParameters();
        int size = 10000;
        if (parameters.containsKey("~size")) {
            Optional<String> maxSize = parameters.get("~size").stream().max((o1, o2) -> {
                return Integer.valueOf(o1).compareTo(Integer.valueOf(o2));
            });
            if (maxSize.isPresent()) {
                size = Integer.valueOf(maxSize.get());
            }

        }
        final SearchResponse response = client.prepareSearch("tags").setTypes("tag")
                .setQuery(new MatchAllQueryBuilder()).setSize(size).execute().actionGet();
        StreamingOutput stream = new StreamingOutput() {
            @Override
            public void write(OutputStream os) throws IOException, WebApplicationException {
                JsonGenerator jg = mapper.getFactory().createGenerator(os, JsonEncoding.UTF8);
                jg.writeStartArray();
                if (response != null) {
                    for (SearchHit hit : response.getHits()) {
                        jg.writeObject(mapper.readValue(hit.source(), XmlTag.class));
                    }
                }
                jg.writeEndArray();
                jg.flush();
                jg.close();
            }
        };
        Response r = Response.ok(stream).build();
        log.fine(user + "|" + uriInfo.getPath() + "|GET|OK|" + r.getStatus() + response.getTook() + "|returns "
                + response.getHits().getTotalHits() + " tags");
        return r;
    } catch (Exception e) {
        return handleException(user, Response.Status.INTERNAL_SERVER_ERROR, e);
    } finally {
        client.close();
    }
}