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

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

Introduction

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

Prototype

@Override
public abstract void close() throws IOException;

Source Link

Document

Method called to close this generator, so that no more content can be written.

Usage

From source file:org.h2gis.drivers.geojson.GeoJsonWriteDriver.java

/**
 * Write the spatial table to GeoJSON format.
 *
 * @param progress//from   www. ja  va  2 s .  c  o m
 * @throws SQLException
 */
private void writeGeoJson(ProgressVisitor progress) throws SQLException, IOException {
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(fileName);
        // Read Geometry Index and type
        final TableLocation parse = TableLocation.parse(tableName,
                JDBCUtilities.isH2DataBase(connection.getMetaData()));
        List<String> spatialFieldNames = SFSUtilities.getGeometryFields(connection, parse);
        if (spatialFieldNames.isEmpty()) {
            throw new SQLException(String.format("The table %s does not contain a geometry field", tableName));
        }

        // Read table content
        Statement st = connection.createStatement();
        try {
            JsonFactory jsonFactory = new JsonFactory();
            JsonGenerator jsonGenerator = jsonFactory.createGenerator(new BufferedOutputStream(fos),
                    JsonEncoding.UTF8);

            // header of the GeoJSON file
            jsonGenerator.writeStartObject();
            jsonGenerator.writeStringField("type", "FeatureCollection");
            writeCRS(jsonGenerator,
                    SFSUtilities.getAuthorityAndSRID(connection, parse, spatialFieldNames.get(0)));
            jsonGenerator.writeArrayFieldStart("features");

            ResultSet rs = st.executeQuery(String.format("select * from `%s`", tableName));

            try {
                ResultSetMetaData resultSetMetaData = rs.getMetaData();
                int geoFieldIndex = JDBCUtilities.getFieldIndex(resultSetMetaData, spatialFieldNames.get(0));

                cacheMetadata(resultSetMetaData);
                while (rs.next()) {
                    writeFeature(jsonGenerator, rs, geoFieldIndex);
                }
                progress.endStep();
                // footer
                jsonGenerator.writeEndArray();
                jsonGenerator.writeEndObject();
                jsonGenerator.flush();
                jsonGenerator.close();

            } finally {
                rs.close();
            }
        } finally {
            st.close();
        }
    } catch (FileNotFoundException ex) {
        throw new SQLException(ex);

    } finally {
        try {
            if (fos != null) {
                fos.close();
            }
        } catch (IOException ex) {
            throw new SQLException(ex);
        }
    }
}

From source file:com.spotify.docker.client.DefaultDockerClient.java

@Override
public List<Image> listImages(ListImagesParam... params) throws DockerException, InterruptedException {
    WebTarget resource = resource().path("images").path("json");

    final Map<String, String> filters = newHashMap();
    for (ListImagesParam param : params) {
        if (param instanceof ListImagesFilterParam) {
            filters.put(param.name(), param.value());
        } else {/*from w  w  w . j  a  v a 2  s  . com*/
            resource = resource.queryParam(param.name(), param.value());
        }
    }

    // If filters were specified, we must put them in a JSON object and pass them using the
    // 'filters' query param like this: filters={"dangling":["true"]}
    try {
        if (!filters.isEmpty()) {
            final StringWriter writer = new StringWriter();
            final JsonGenerator generator = objectMapper().getFactory().createGenerator(writer);
            generator.writeStartObject();
            for (Map.Entry<String, String> entry : filters.entrySet()) {
                generator.writeArrayFieldStart(entry.getKey());
                generator.writeString(entry.getValue());
                generator.writeEndArray();
            }
            generator.writeEndObject();
            generator.close();
            // We must URL encode the string, otherwise Jersey chokes on the double-quotes in the json.
            final String encoded = URLEncoder.encode(writer.toString(), UTF_8.name());
            resource = resource.queryParam("filters", encoded);
        }
    } catch (IOException e) {
        throw new DockerException(e);
    }

    return request(GET, IMAGE_LIST, resource, resource.request(APPLICATION_JSON_TYPE));
}

From source file:org.apache.olingo.server.core.serializer.json.ODataJsonSerializer.java

@Override
public SerializerResult entity(final ServiceMetadata metadata, final EdmEntityType entityType,
        final Entity entity, final EntitySerializerOptions options) throws SerializerException {
    OutputStream outputStream = null;
    SerializerException cachedException = null;
    try {/*w ww . j a  v a 2s. co  m*/
        final ContextURL contextURL = checkContextURL(options == null ? null : options.getContextURL());
        CircleStreamBuffer buffer = new CircleStreamBuffer();
        outputStream = buffer.getOutputStream();
        JsonGenerator json = new JsonFactory().createGenerator(outputStream);
        String name = contextURL == null ? null : contextURL.getEntitySetOrSingletonOrType();
        writeEntity(metadata, entityType, entity, contextURL, options == null ? null : options.getExpand(),
                null, options == null ? null : options.getSelect(),
                options == null ? false : options.getWriteOnlyReferences(), null, name, json);

        json.close();
        outputStream.close();
        return SerializerResultImpl.with().content(buffer.getInputStream()).build();
    } catch (final IOException e) {
        cachedException = new SerializerException(IO_EXCEPTION_TEXT, e,
                SerializerException.MessageKeys.IO_EXCEPTION);
        throw cachedException;
    } catch (DecoderException e) {
        cachedException = new SerializerException(IO_EXCEPTION_TEXT, e,
                SerializerException.MessageKeys.IO_EXCEPTION);
        throw cachedException;
    } finally {
        closeCircleStreamBufferOutput(outputStream, cachedException);
    }
}

From source file:com.spotify.docker.client.DefaultDockerClient.java

@Override
public String execCreate(String containerId, String[] cmd, ExecParameter... params)
        throws DockerException, InterruptedException {
    WebTarget resource = resource().path("containers").path(containerId).path("exec");

    final StringWriter writer = new StringWriter();
    try {/*  w  w  w . j av  a  2  s. c om*/
        final JsonGenerator generator = objectMapper().getFactory().createGenerator(writer);
        generator.writeStartObject();

        for (ExecParameter param : params) {
            generator.writeBooleanField(param.getName(), true);
        }

        generator.writeArrayFieldStart("Cmd");
        for (String s : cmd) {
            generator.writeString(s);
        }
        generator.writeEndArray();

        generator.writeEndObject();
        generator.close();
    } catch (IOException e) {
        throw new DockerException(e);
    }

    String response;
    try {
        response = request(POST, String.class, resource, resource.request(APPLICATION_JSON_TYPE),
                Entity.json(writer.toString()));
    } catch (DockerRequestException e) {
        switch (e.status()) {
        case 404:
            throw new ContainerNotFoundException(containerId);
        default:
            throw e;
        }
    }

    try {
        JsonNode json = objectMapper().readTree(response);
        return json.findValue("Id").textValue();
    } catch (IOException e) {
        throw new DockerException(e);
    }
}

From source file:com.bazaarvoice.jsonpps.PrettyPrintJson.java

public void prettyPrint(List<File> inputFiles, File outputFile) throws IOException {
    JsonFactory factory = new JsonFactory();
    factory.disable(JsonFactory.Feature.INTERN_FIELD_NAMES);
    if (!strict) {
        factory.enable(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER);
        factory.enable(JsonParser.Feature.ALLOW_COMMENTS);
        factory.enable(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS);
        factory.enable(JsonParser.Feature.ALLOW_NUMERIC_LEADING_ZEROS);
        factory.enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES);
        factory.enable(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS);
        factory.enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES);
    }//w  w w.j  a  v a  2 s . c om

    ObjectMapper mapper = null;
    if (sortKeys) {
        mapper = new ObjectMapper(factory);
        mapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);
        mapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE);
    }

    // Open the output stream and create the Json emitter.
    JsonGenerator generator;
    File tempOutputFile = null;
    if (STDINOUT.equals(outputFile)) {
        generator = factory.createGenerator(stdout, JsonEncoding.UTF8);
    } else if (!caseInsensitiveContains(inputFiles, outputFile)) {
        generator = factory.createGenerator(outputFile, JsonEncoding.UTF8);
    } else {
        // Writing to an input file.. use a temp file to stage the output until we're done.
        tempOutputFile = getTemporaryFileFor(outputFile);
        generator = factory.createGenerator(tempOutputFile, JsonEncoding.UTF8);
    }
    try {
        // Separate top-level objects by a newline in the output.
        String newline = System.getProperty("line.separator");
        generator.setPrettyPrinter(new DefaultPrettyPrinter(newline));

        if (wrap) {
            generator.writeStartArray();
        }

        for (File inputFile : inputFiles) {
            JsonParser parser;
            if (STDINOUT.equals(inputFile)) {
                parser = factory.createParser(stdin);
            } else {
                parser = factory.createParser(inputFile);
            }
            try {
                while (parser.nextToken() != null) {
                    copyCurrentStructure(parser, mapper, 0, generator);
                }
            } finally {
                parser.close();
            }
        }

        if (wrap) {
            generator.writeEndArray();
        }

        generator.writeRaw(newline);
    } finally {
        generator.close();
    }
    if (tempOutputFile != null && !tempOutputFile.renameTo(outputFile)) {
        System.err.println("error: unable to rename temporary file to output: " + outputFile);
        System.exit(1);
    }
}

From source file:net.opentsdb.tree.Tree.java

/**
 * Converts the object to a JSON byte array, necessary for CAS calls and to
 * keep redundant data down/*w ww  .  ja  v  a 2  s  .co m*/
 * @return A byte array with the serialized tree
 */
private byte[] toStorageJson() {
    // TODO - precalc how much memory to grab
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    try {
        final JsonGenerator json = JSON.getFactory().createGenerator(output);

        json.writeStartObject();

        // we only need to write a small amount of information
        //json.writeNumberField("treeId", tree_id);
        json.writeStringField("name", name);
        json.writeStringField("description", description);
        json.writeStringField("notes", notes);
        json.writeBooleanField("strictMatch", strict_match);
        json.writeNumberField("created", created);
        json.writeBooleanField("enabled", enabled);
        json.writeBooleanField("storeFailures", store_failures);
        json.writeEndObject();
        json.close();

        // TODO zero copy?
        return output.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.googlecode.jmxtrans.model.output.LibratoWriter.java

private void serialize(Server server, Query query, List<Result> results, OutputStream outputStream)
        throws IOException {
    JsonGenerator g = jsonFactory.createGenerator(outputStream, JsonEncoding.UTF8);
    g.writeStartObject();/*from  www . j a v  a  2 s . c o m*/
    g.writeArrayFieldStart("counters");
    g.writeEndArray();

    String source = getSource(server);

    g.writeArrayFieldStart("gauges");
    List<String> typeNames = getTypeNames();
    for (Result result : results) {
        Map<String, Object> resultValues = result.getValues();
        for (Map.Entry<String, Object> values : resultValues.entrySet()) {
            if (isNumeric(values.getValue())) {
                g.writeStartObject();
                g.writeStringField("name", KeyUtils.getKeyString(query, result, values, typeNames));
                if (source != null && !source.isEmpty()) {
                    g.writeStringField("source", source);
                }
                g.writeNumberField("measure_time",
                        TimeUnit.SECONDS.convert(result.getEpoch(), TimeUnit.MILLISECONDS));
                Object value = values.getValue();
                if (value instanceof Integer) {
                    g.writeNumberField("value", (Integer) value);
                } else if (value instanceof Long) {
                    g.writeNumberField("value", (Long) value);
                } else if (value instanceof Float) {
                    g.writeNumberField("value", (Float) value);
                } else if (value instanceof Double) {
                    g.writeNumberField("value", (Double) value);
                }
                g.writeEndObject();
            }
        }
    }
    g.writeEndArray();
    g.writeEndObject();
    g.flush();
    g.close();

}

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

/**
 * Data object for the JSP//from   www.jav  a  2  s. co  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:net.opentsdb.meta.TSMeta.java

/**
 * Formats the JSON output for writing to storage. It drops objects we don't
 * need or want to store (such as the UIDMeta objects or the total dps) to
 * save space. It also serializes in order so that we can make a proper CAS
 * call. Otherwise the POJO serializer may place the fields in any order
 * and CAS calls would fail all the time.
 * @return A byte array to write to storage
 *///w  w  w .  ja v a 2  s . c o  m
private byte[] getStorageJSON() {
    // 256 bytes is a good starting value, assumes default info
    final ByteArrayOutputStream output = new ByteArrayOutputStream(256);
    try {
        final JsonGenerator json = JSON.getFactory().createGenerator(output);
        json.writeStartObject();
        json.writeStringField("tsuid", tsuid);
        json.writeStringField("displayName", display_name);
        json.writeStringField("description", description);
        json.writeStringField("notes", notes);
        json.writeNumberField("created", created);
        if (custom == null) {
            json.writeNullField("custom");
        } else {
            json.writeObjectFieldStart("custom");
            for (Map.Entry<String, String> entry : custom.entrySet()) {
                json.writeStringField(entry.getKey(), entry.getValue());
            }
            json.writeEndObject();
        }
        json.writeStringField("units", units);
        json.writeStringField("dataType", data_type);
        json.writeNumberField("retention", retention);
        json.writeNumberField("max", max);
        json.writeNumberField("min", min);

        json.writeEndObject();
        json.close();
        return output.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException("Unable to serialize TSMeta", e);
    }
}

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

public void cue_serialize(@Nonnull Iterable<QueryResult> counters, @Nonnull OutputStream out)
        throws IOException {
    int first = 0;
    long time = 0;
    String myID = null;//w  w  w. ja va  2  s . c o  m
    JsonGenerator g = jsonFactory.createGenerator(out, JsonEncoding.UTF8);

    for (QueryResult counter : counters) {
        if (0 == first) {
            time = counter.getEpoch(TimeUnit.SECONDS);
            myID = counter.getType();
            first = 1;
            g.writeStartObject();
            g.writeStringField("identifier", myID);
            g.writeNumberField("timestamp", time);
            g.writeObjectFieldStart("values");
        }
        if (counter.getValue() instanceof Integer) {
            g.writeNumberField(counter.getName(), (Integer) counter.getValue());
        } else if (counter.getValue() instanceof Long) {
            g.writeNumberField(counter.getName(), (Long) counter.getValue());
        } else if (counter.getValue() instanceof Float) {
            g.writeNumberField(counter.getName(), (Float) counter.getValue());
        } else if (counter.getValue() instanceof Double) {
            g.writeNumberField(counter.getName(), (Double) counter.getValue());
        }
    }
    g.writeEndObject();
    g.writeEndObject();
    g.flush();
    g.close();
}