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

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

Introduction

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

Prototype

@Override
public abstract void flush() throws IOException;

Source Link

Document

Method called to flush any buffered content to the underlying target (output stream, writer), and to flush the target itself as well.

Usage

From source file:com.proofpoint.event.client.JsonEventWriter.java

public <T> Writer createEventWriter(final Iterator<T> eventIterator, final String token, final OutputStream out)
        throws IOException {
    checkNotNull(eventIterator, "eventIterator is null");
    checkNotNull(out, "out is null");

    final JsonGenerator jsonGenerator = jsonFactory.createGenerator(out, JsonEncoding.UTF8);

    jsonGenerator.writeStartArray();/*from  w w w .j  av  a  2 s .c o  m*/

    return new Writer() {
        @Override
        public void write() throws Exception {
            if (eventIterator.hasNext()) {
                T event = eventIterator.next();
                JsonSerializer<T> serializer = getSerializer(event, token);
                if (serializer == null) {
                    throw new InvalidEventException("Event class [%s] has not been registered as an event",
                            event.getClass().getName());
                }

                serializer.serialize(event, jsonGenerator, null);
            } else {
                jsonGenerator.writeEndArray();
                jsonGenerator.flush();
                out.close();
            }
        }
    };
}

From source file:com.attribyte.essem.ESReporter.java

static final void generateHistogram(final JsonGenerator generator,
        final ReportProtos.EssemReport.Histogram histogram, final String application, final String host,
        final String instance, final long timestamp) throws IOException {

    generator.writeStartObject();/*  w ww  .j a v  a2s  .  c  om*/
    writeStringField(generator, Fields.APPLICATION_FIELD, application);
    writeStringField(generator, Fields.HOST_FIELD, host);
    writeStringField(generator, Fields.INSTANCE_FIELD, instance);
    writeStringField(generator, Fields.NAME_FIELD, histogram.getName().trim());
    generator.writeNumberField(Fields.COUNT_FIELD, histogram.getCount());
    generator.writeNumberField(Fields.MAX_FIELD, histogram.getMax());
    generator.writeNumberField(Fields.MIN_FIELD, histogram.getMin());
    generator.writeNumberField(Fields.MEAN_FIELD, histogram.getMean());
    generator.writeNumberField(Fields.P50_FIELD, histogram.getMedian());
    generator.writeNumberField(Fields.P75_FIELD, histogram.getPercentile75());
    generator.writeNumberField(Fields.P95_FIELD, histogram.getPercentile95());
    generator.writeNumberField(Fields.P98_FIELD, histogram.getPercentile98());
    generator.writeNumberField(Fields.P99_FIELD, histogram.getPercentile99());
    generator.writeNumberField(Fields.P999_FIELD, histogram.getPercentile999());
    generator.writeNumberField(Fields.STD_FIELD, histogram.getStd());
    generator.writeNumberField(Fields.TIMESTAMP_FIELD, timestamp);
    generator.writeEndObject();
    generator.flush();
}

From source file:org.dswarm.graph.resources.MaintainResource.java

/**
 * note utilise this endpoint with care, because it cleans your complete db!
 *
 * @param database the graph database//w w  w. j av a 2  s. c  o m
 */
@DELETE
@Path("/delete")
@Produces("application/json")
public Response cleanGraph(@Context final GraphDatabaseService database) throws IOException, DMPGraphException {

    MaintainResource.LOG.debug("start cleaning up the db");

    final long deleted = deleteSomeStatements(database);

    MaintainResource.LOG.debug("finished delete-all-entities TXs");

    MaintainResource.LOG.debug("start legacy indices clean-up");

    // TODO: maybe separate index clean-up + observe index clean-up
    // => maybe we also need to do a label + relationship types clean-up ... => this is not supported right now ...

    deleteSomeLegacyIndices(database);

    MaintainResource.LOG.debug("finished legacy indices clean-up");

    MaintainResource.LOG.debug("start schema indices clean-up");

    deleteSomeSchemaIndices(database);

    MaintainResource.LOG.debug("finished schema indices clean-up");

    MaintainResource.LOG.debug("finished cleaning up the db");

    final StringWriter out = new StringWriter();
    final JsonGenerator generator = simpleObjectMapper.getFactory().createGenerator(out);

    generator.writeStartObject();
    generator.writeNumberField("deleted", deleted);
    generator.writeEndObject();
    generator.flush();
    generator.close();

    final String result = out.toString();

    out.flush();
    out.close();

    return Response.ok(result, MediaType.APPLICATION_JSON_TYPE).build();
}

From source file:com.viridiansoftware.metrics.elasticsearch.ElasticsearchReporter.java

private void reportMetered(String index, long timestamp, String name, Metered meter) throws IOException {
    StringWriter writer = new StringWriter();
    JsonGenerator jsonGenerator = jsonFactory.createGenerator(writer);
    jsonGenerator.writeStartObject();/*ww w.jav a  2  s .co m*/
    jsonGenerator.writeNumberField(timestampFieldName, timestamp);
    jsonGenerator.writeStringField("@name", prefixMetricName(name));

    jsonGenerator.writeNumberField("count", meter.getCount());
    jsonGenerator.writeNumberField("m1_rate", convertRate(meter.getOneMinuteRate()));
    jsonGenerator.writeNumberField("m5_rate", convertRate(meter.getFiveMinuteRate()));
    jsonGenerator.writeNumberField("m15_rate", convertRate(meter.getFifteenMinuteRate()));
    jsonGenerator.writeNumberField("mean_rate", convertRate(meter.getMeanRate()));

    jsonGenerator.writeEndObject();
    jsonGenerator.flush();
    addReportToBulkRequest(index, MetricElasticsearchTypes.METER, writer.toString());
}

From source file:org.apache.olingo.commons.core.serialization.JsonSerializer.java

@Override
public <T> void write(final Writer writer, final T obj) throws ODataSerializerException {
    try {// ww w  .j  a v a 2  s. c  o  m
        final JsonGenerator json = new JsonFactory().createGenerator(writer);
        if (obj instanceof EntitySet) {
            new JsonEntitySetSerializer(version, serverMode).doSerialize((EntitySet) obj, json);
        } else if (obj instanceof Entity) {
            new JsonEntitySerializer(version, serverMode).doSerialize((Entity) obj, json);
        } else if (obj instanceof Property) {
            new JsonPropertySerializer(version, serverMode).doSerialize((Property) obj, json);
        } else if (obj instanceof Link) {
            link((Link) obj, json);
        }
        json.flush();
    } catch (final IOException e) {
        throw new ODataSerializerException(e);
    } catch (final EdmPrimitiveTypeException e) {
        throw new ODataSerializerException(e);
    }
}

From source file:org.apache.olingo.client.core.serialization.JsonSerializer.java

@Override
public <T> void write(final Writer writer, final T obj) throws ODataSerializerException {
    try {//ww  w .  j ava  2  s . com
        final JsonGenerator json = new JsonFactory().createGenerator(writer);
        if (obj instanceof EntityCollection) {
            new JsonEntitySetSerializer(serverMode, contentType).doSerialize((EntityCollection) obj, json);
        } else if (obj instanceof Entity) {
            new JsonEntitySerializer(serverMode, contentType).doSerialize((Entity) obj, json);
        } else if (obj instanceof Property) {
            new JsonPropertySerializer(serverMode, contentType).doSerialize((Property) obj, json);
        } else if (obj instanceof Link) {
            link((Link) obj, json);
        }
        json.flush();
    } catch (final IOException e) {
        throw new ODataSerializerException(e);
    } catch (final EdmPrimitiveTypeException e) {
        throw new ODataSerializerException(e);
    }
}

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

public void toJson(JsonGenerator jsonGen, DecimalFormat df) {
    try {/*from   w  ww.jav a 2 s.  co  m*/
        jsonGen.writeStartObject();
        jsonGen.writeNumberField("docId", docId);
        jsonGen.writeStringField("field", this.getField());
        jsonGen.writeNumberField("start", this.getStartOffset());
        jsonGen.writeNumberField("end", this.getEndOffset());
        double roundedScore = df.parse(df.format(this.getScore())).doubleValue();
        jsonGen.writeNumberField("score", roundedScore);
        jsonGen.writeArrayFieldStart("terms");
        for (HighlightTerm term : this.getHighlightTerms()) {
            term.toJson(jsonGen, df);
        }
        jsonGen.writeEndArray(); // terms

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

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./*w  w  w . j  a  v  a  2  s  .  c o  m*/
 *
 * @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:org.apache.olingo.commons.core.serialization.JsonSerializer.java

@SuppressWarnings("unchecked")
@Override/*ww  w.  ja v  a2s .co m*/
public <T> void write(final Writer writer, final ResWrap<T> container) throws ODataSerializerException {
    final T obj = container == null ? null : container.getPayload();
    try {
        final JsonGenerator json = new JsonFactory().createGenerator(writer);
        if (obj instanceof EntitySet) {
            new JsonEntitySetSerializer(version, serverMode)
                    .doContainerSerialize((ResWrap<EntitySet>) container, json);
        } else if (obj instanceof Entity) {
            new JsonEntitySerializer(version, serverMode).doContainerSerialize((ResWrap<Entity>) container,
                    json);
        } else if (obj instanceof Property) {
            new JsonPropertySerializer(version, serverMode).doContainerSerialize((ResWrap<Property>) container,
                    json);
        } else if (obj instanceof Link) {
            link((Link) obj, json);
        }
        json.flush();
    } catch (final IOException e) {
        throw new ODataSerializerException(e);
    } catch (final EdmPrimitiveTypeException e) {
        throw new ODataSerializerException(e);
    }
}

From source file:org.jmxtrans.embedded.output.CopperEggWriter.java

public String write_tostring(JsonNode json) {
    ObjectMapper mapper = new ObjectMapper();
    StringWriter out = new StringWriter();

    try {//from   w  ww .jav  a2s.c  om
        JsonFactory fac = new JsonFactory();
        JsonGenerator gen = fac.createJsonGenerator(out);

        // Now write:
        mapper.writeTree(gen, json);
        gen.flush();
        gen.close();
        return out.toString();
    } catch (Exception e) {
        exceptionCounter.incrementAndGet();
        logger.warn("Exception in write_tostring: " + e);
    }
    return (null);
}