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:webFramework.MappingJackson2PrettyJsonView.java

@Override
protected void writeContent(OutputStream stream, Object object) throws IOException {
    JsonGenerator generator = this.getObjectMapper().getFactory().createGenerator(stream, this.getEncoding());

    writePrefix(generator, object);/*from w  ww  . j  ava 2s  .c  om*/
    Class<?> serializationView = null;
    FilterProvider filters = null;
    Object value = object;

    if (value instanceof MappingJacksonValue) {
        MappingJacksonValue container = (MappingJacksonValue) value;
        value = container.getValue();
        serializationView = container.getSerializationView();
        filters = container.getFilters();
    }
    if (serializationView != null) {
        this.getObjectMapper().writerWithView(serializationView).withDefaultPrettyPrinter()
                .writeValue(generator, value);
    } else if (filters != null) {
        this.getObjectMapper().writer(filters).withDefaultPrettyPrinter().writeValue(generator, value);
    } else {
        this.getObjectMapper().writerWithDefaultPrettyPrinter().writeValue(generator, value);
    }
    writeSuffix(generator, object);
    generator.flush();
}

From source file:com.basho.riak.client.api.commands.mapreduce.MapReduce.java

/**
 * Creates the JSON string of the M/R job for submitting to the client
 * <p/>//from  ww  w.  j  a v a 2 s  .  c o  m
 * Uses Jackson to write out the JSON string. I'm not very happy with this method, it is a candidate for change.
 * <p/>
 * TODO re-evaluate this method, look for something smaller and more elegant.
 *
 * @return a String of JSON
 * @throws RiakException if, for some reason, we can't create a JSON string.
 */
String writeSpec() throws RiakException {

    final ByteArrayOutputStream out = new ByteArrayOutputStream();

    try {
        JsonGenerator jg = new JsonFactory().createGenerator(out, JsonEncoding.UTF8);

        ObjectMapper objectMapper = new ObjectMapper();
        SimpleModule specModule = new SimpleModule("SpecModule", Version.unknownVersion());
        specModule.addSerializer(LinkPhase.class, new LinkPhaseSerializer());
        specModule.addSerializer(FunctionPhase.class, new FunctionPhaseSerializer());
        specModule.addSerializer(BucketInput.class, new BucketInputSerializer());
        specModule.addSerializer(SearchInput.class, new SearchInputSerializer());
        specModule.addSerializer(BucketKeyInput.class, new BucketKeyInputSerializer());
        specModule.addSerializer(IndexInput.class, new IndexInputSerializer());
        objectMapper.registerModule(specModule);

        jg.setCodec(objectMapper);

        List<MapReducePhase> phases = spec.getPhases();
        phases.get(phases.size() - 1).setKeep(true);
        jg.writeObject(spec);

        jg.flush();

        return out.toString("UTF8");

    } catch (IOException e) {
        throw new RiakException(e);
    }
}

From source file:com.neoteric.starter.metrics.report.elastic.ElasticsearchReporter.java

private void checkForIndexTemplate() {
    try {//  ww w .j av a 2 s .c om
        HttpURLConnection connection = openConnection("/_template/metrics_template", "HEAD");
        connection.disconnect();
        boolean isTemplateMissing = connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND;

        // nothing there, lets create it
        if (isTemplateMissing) {
            LOGGER.debug("No metrics template found in elasticsearch. Adding...");
            HttpURLConnection putTemplateConnection = openConnection("/_template/metrics_template", "PUT");
            JsonGenerator json = new JsonFactory().createGenerator(putTemplateConnection.getOutputStream());
            json.writeStartObject();
            json.writeStringField("template", index + "*");
            json.writeObjectFieldStart("mappings");

            json.writeObjectFieldStart("_default_");
            json.writeObjectFieldStart("_all");
            json.writeBooleanField("enabled", false);
            json.writeEndObject();
            json.writeObjectFieldStart("properties");
            json.writeObjectFieldStart("name");
            json.writeObjectField("type", "string");
            json.writeObjectField("index", "not_analyzed");
            json.writeEndObject();
            json.writeEndObject();
            json.writeEndObject();

            json.writeEndObject();
            json.writeEndObject();
            json.flush();

            putTemplateConnection.disconnect();
            if (putTemplateConnection.getResponseCode() != HttpStatus.OK.value()) {
                LOGGER.error(
                        "Error adding metrics template to elasticsearch: {}/{}"
                                + putTemplateConnection.getResponseCode(),
                        putTemplateConnection.getResponseMessage());
            }
        }
        checkedForIndexTemplate = true;
    } catch (IOException e) {
        LOGGER.error("Error when checking/adding metrics template to elasticsearch", e);
    }
}

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

private void reportGauge(String index, long timestamp, String name, Gauge gauge) throws IOException {
    Object value = gauge.getValue();
    if (value == null) {
        return;/*w  w w.jav  a2 s  . c  o  m*/
    }
    StringWriter writer = new StringWriter();
    JsonGenerator jsonGenerator = jsonFactory.createGenerator(writer);
    jsonGenerator.writeStartObject();
    jsonGenerator.writeNumberField(timestampFieldName, timestamp);
    jsonGenerator.writeStringField("@name", prefixMetricName(name));

    if (value instanceof Float) {
        jsonGenerator.writeNumberField("floatValue", (Float) value);
    } else if (value instanceof Double) {
        jsonGenerator.writeNumberField("doubleValue", (Double) value);
    } else if (value instanceof Byte) {
        jsonGenerator.writeNumberField("byteValue", ((Byte) value).intValue());
    } else if (value instanceof Short) {
        jsonGenerator.writeNumberField("shortValue", (Short) value);
    } else if (value instanceof Integer) {
        jsonGenerator.writeNumberField("integerValue", (Integer) value);
    } else if (value instanceof Long) {
        jsonGenerator.writeNumberField("longValue", (Long) value);
    } else {
        jsonGenerator.writeStringField("stringValue", value.toString());
    }

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

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

@Override
public void process(JCas aJCas) throws AnalysisEngineProcessException {
    /*/*from ww w .  ja  v a 2 s.  co m*/
     *  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.seedstack.seed.core.internal.data.DataManagerImpl.java

private void dumpAll(List<DataSetMarker<Object>> dataSetMarker, OutputStream outputStream) {
    try {//from ww w .j av a 2s  .  c  o  m
        JsonGenerator jsonGenerator = this.jsonFactory
                .createGenerator(new OutputStreamWriter(outputStream, Charset.forName(UTF_8)));
        ObjectWriter objectWriter = objectMapper.writer();

        jsonGenerator.writeStartArray();

        for (DataSetMarker<Object> objectDataSetMarker : dataSetMarker) {
            // start
            jsonGenerator.writeStartObject();

            // metadata
            jsonGenerator.writeStringField(GROUP, objectDataSetMarker.getGroup());
            jsonGenerator.writeStringField(NAME, objectDataSetMarker.getName());

            // items
            jsonGenerator.writeArrayFieldStart(ITEMS);
            while (objectDataSetMarker.getItems().hasNext()) {
                objectWriter.writeValue(jsonGenerator, objectDataSetMarker.getItems().next());
            }
            jsonGenerator.writeEndArray();

            // end
            jsonGenerator.writeEndObject();
        }

        jsonGenerator.writeEndArray();

        jsonGenerator.flush();
    } catch (Exception e) {
        throw SeedException.wrap(e, DataErrorCode.EXPORT_FAILED);
    }
}

From source file:org.elasticsearch.metrics.ElasticsearchReporter.java

/**
 * This index template is automatically applied to all indices which start with the index name
 * The index template simply configures the name not to be analyzed
 *//*from ww  w.j av a 2 s  .c o m*/
private void checkForIndexTemplate() {
    try {
        HttpURLConnection connection = openConnection("/_template/metrics_template", "HEAD");
        if (connection == null) {
            LOGGER.error("Could not connect to any configured elasticsearch instances: {}",
                    Arrays.asList(hosts));
            return;
        }
        connection.disconnect();

        boolean isTemplateMissing = connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND;

        // nothing there, lets create it
        if (isTemplateMissing) {
            LOGGER.debug("No metrics template found in elasticsearch. Adding...");
            HttpURLConnection putTemplateConnection = openConnection("/_template/metrics_template", "PUT");
            if (putTemplateConnection == null) {
                LOGGER.error("Error adding metrics template to elasticsearch");
                return;
            }

            JsonGenerator json = new JsonFactory().createGenerator(putTemplateConnection.getOutputStream());
            json.writeStartObject();
            json.writeStringField("template", index + "*");
            json.writeObjectFieldStart("mappings");

            json.writeObjectFieldStart("_default_");
            json.writeObjectFieldStart("_all");
            json.writeBooleanField("enabled", false);
            json.writeEndObject();
            json.writeObjectFieldStart("properties");
            json.writeObjectFieldStart("name");
            json.writeObjectField("type", "string");
            json.writeObjectField("index", "not_analyzed");
            json.writeEndObject();
            json.writeEndObject();
            json.writeEndObject();

            json.writeEndObject();
            json.writeEndObject();
            json.flush();

            putTemplateConnection.disconnect();
            if (putTemplateConnection.getResponseCode() != 200) {
                LOGGER.error(
                        "Error adding metrics template to elasticsearch: {}/{}"
                                + putTemplateConnection.getResponseCode(),
                        putTemplateConnection.getResponseMessage());
            }
        }
        checkedForIndexTemplate = true;
    } catch (IOException e) {
        LOGGER.error("Error when checking/adding metrics template to elasticsearch", e);
    }
}

From source file:com.oneops.metrics.es.ElasticsearchReporter.java

/**
 * This index template is automatically applied to all indices which start with the index name
 * The index template simply configures the name not to be analyzed
 */// w  w w .  ja v a 2s . com
private void checkForIndexTemplate() {
    try {
        HttpURLConnection connection = openConnection("/_template/metrics_template", "HEAD");
        if (connection == null) {
            LOGGER.error("Could not connect to any configured elasticsearch instances: {}",
                    Arrays.asList(hosts));
            return;
        }
        connection.disconnect();

        boolean isTemplateMissing = connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND;

        // nothing there, lets create it
        if (isTemplateMissing) {
            LOGGER.debug("No metrics template found in elasticsearch. Adding...");
            HttpURLConnection putTemplateConnection = openConnection("/_template/metrics_template", "PUT");
            JsonGenerator json = new JsonFactory().createGenerator(putTemplateConnection.getOutputStream());
            json.writeStartObject();
            json.writeStringField("template", index + "*");
            json.writeObjectFieldStart("mappings");

            json.writeObjectFieldStart("_default_");
            json.writeObjectFieldStart("_all");
            json.writeBooleanField("enabled", false);
            json.writeEndObject();
            json.writeObjectFieldStart("properties");
            json.writeObjectFieldStart("name");
            json.writeObjectField("type", "string");
            json.writeObjectField("index", "not_analyzed");
            json.writeEndObject();
            json.writeEndObject();
            json.writeEndObject();

            json.writeEndObject();
            json.writeEndObject();
            json.flush();

            putTemplateConnection.disconnect();
            if (putTemplateConnection.getResponseCode() != 200) {
                LOGGER.error(
                        "Error adding metrics template to elasticsearch: {}/{}"
                                + putTemplateConnection.getResponseCode(),
                        putTemplateConnection.getResponseMessage());
            }
        }
        checkedForIndexTemplate = true;
    } catch (IOException e) {
        LOGGER.error("Error when checking/adding metrics template to elasticsearch", e);
    }
}

From source file:com.basho.riak.client.raw.http.ConversionUtil.java

/**
 * Converts a {@link BucketProperties} to a JSON string
 * @param bp//w  w  w  .  j a v  a2  s.c  o m
 * @return a String of JSON that is acceptable to {@link RiakBucketInfo}
 * @throws IOException
 * TODO: move this to a custom serializer?
 */
private static String toJSON(BucketProperties bp) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    JsonGenerator jg = new JsonFactory().createJsonGenerator(out, JsonEncoding.UTF8);

    jg.writeStartObject();
    writeIfNotNull(jg, bp.getAllowSiblings(), Constants.FL_SCHEMA_ALLOW_MULT);
    writeIfNotNull(jg, bp.getNVal(), Constants.FL_SCHEMA_NVAL);
    writeIfNotNull(jg, bp.getLastWriteWins(), Constants.FL_SCHEMA_LAST_WRITE_WINS);
    writeIfNotNull(jg, bp.getBackend(), Constants.FL_SCHEMA_BACKEND);
    writeIfNotNull(jg, bp.getSmallVClock(), Constants.FL_SCHEMA_SMALL_VCLOCK);
    writeIfNotNull(jg, bp.getBigVClock(), Constants.FL_SCHEMA_BIG_VCLOCK);
    writeIfNotNull(jg, bp.getYoungVClock(), Constants.FL_SCHEMA_YOUNG_VCLOCK);
    writeIfNotNull(jg, bp.getOldVClock(), Constants.FL_SCHEMA_OLD_VCLOCK);
    writeIfNotNull(jg, bp.getR(), Constants.FL_SCHEMA_R);
    writeIfNotNull(jg, bp.getRW(), Constants.FL_SCHEMA_RW);
    writeIfNotNull(jg, bp.getW(), Constants.FL_SCHEMA_W);
    writeIfNotNull(jg, bp.getDW(), Constants.FL_SCHEMA_DW);
    writeIfNotNull(jg, bp.getPR(), Constants.FL_SCHEMA_PR);
    writeIfNotNull(jg, bp.getPW(), Constants.FL_SCHEMA_PW);
    writeIfNotNull(jg, bp.getBasicQuorum(), Constants.FL_SCHEMA_BASIC_QUORUM);
    writeIfNotNull(jg, bp.getNotFoundOK(), Constants.FL_SCHEMA_NOT_FOUND_OK);
    writeIfNotNull(jg, bp.getChashKeyFunction(), Constants.FL_SCHEMA_CHASHFUN);
    writeIfNotNull(jg, bp.getLinkWalkFunction(), Constants.FL_SCHEMA_LINKFUN);
    writeIfNotNull(jg, bp.getPostcommitHooks(), Constants.FL_SCHEMA_POSTCOMMIT);
    writeIfNotNull(jg, bp.getPrecommitHooks(), Constants.FL_SCHEMA_PRECOMMIT);
    writeIfNotNull(jg, bp.getSearch(), Constants.FL_SCHEMA_SEARCH);

    jg.writeEndObject();

    jg.flush();
    return CharsetUtils.asUTF8String(out.toByteArray());
}

From source file:com.msopentech.odatajclient.engine.performance.BasicPerfTest.java

@Test
public void writeJSONViaLowerlevelLibs() throws IOException {
    final StringWriter writer = new StringWriter();

    final ObjectMapper mapper = new ObjectMapper();

    final JsonGenerator jgen = mapper.getFactory().createGenerator(writer);

    jgen.writeStartObject();//from ww w .  ja  va2s .  com

    jgen.writeStringField("odata.type", "Microsoft.Test.OData.Services.AstoriaDefaultService.Customer");

    jgen.writeStringField("Name@odata.type", "Edm.String");
    jgen.writeStringField("Name", "A name");

    jgen.writeStringField("CustomerId@odata.type", "Edm.Int32");
    jgen.writeNumberField("CustomerId", 0);

    jgen.writeArrayFieldStart("BackupContactInfo");

    jgen.writeStartObject();

    jgen.writeArrayFieldStart("AlternativeNames");
    jgen.writeString("myname");
    jgen.writeEndArray();

    jgen.writeArrayFieldStart("EmailBag");
    jgen.writeString("myname@mydomain.com");
    jgen.writeEndArray();

    jgen.writeObjectFieldStart("ContactAlias");
    jgen.writeStringField("odata.type", "Microsoft.Test.OData.Services.AstoriaDefaultService.Aliases");
    jgen.writeArrayFieldStart("AlternativeNames");
    jgen.writeString("myAlternativeName");
    jgen.writeEndArray();
    jgen.writeEndObject();

    jgen.writeEndObject();

    jgen.writeEndArray();

    jgen.writeEndObject();

    jgen.flush();

    assertFalse(writer.toString().isEmpty());
}