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

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

Introduction

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

Prototype

public final void writeNumberField(String fieldName, BigDecimal value)
        throws IOException, JsonGenerationException 

Source Link

Document

Convenience method for outputting a field entry ("member") that has the specified numeric value.

Usage

From source file:org.sead.repositories.reference.RefRepository.java

private static void indexChildren(File index, JsonParser jp) throws IOException {

    JsonGenerator generator = new JsonFactory().createGenerator(index, JsonEncoding.UTF8);
    generator.useDefaultPrettyPrinter();

    generator.writeStartObject();//from   ww w .  ja  v  a  2s .  c  o  m

    JsonToken cur = jp.nextToken();
    while (cur.equals(JsonToken.START_OBJECT)) {
        long start = jp.getTokenLocation().getByteOffset();
        int depth = 1;
        while (depth > 0) {
            cur = jp.nextToken();
            if (cur.equals(JsonToken.START_OBJECT)) {
                depth++;
            } else if (cur.equals(JsonToken.END_OBJECT)) {
                depth--;
            } else if (cur.equals(JsonToken.FIELD_NAME) && depth == 1) {
                if (jp.getText().equals("@id")) {
                    cur = jp.nextToken();

                    String vName = jp.getText();
                    generator.writeNumberField(vName, start);
                } else {
                    report(jp, cur);
                }
            }
        }
        cur = jp.nextToken();
    }
    generator.writeEndObject();
    generator.close();

}

From source file:com.basho.riak.client.query.MapReduce.java

/**
 * Creates the JSON string of the M/R job for submitting to the
 * {@link RawClient}/*from  ww w.j ava 2s.co m*/
 * 
 * Uses Jackson to write out the JSON string. I'm not very happy with this
 * method, it is a candidate for change.
 * 
 * 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.
 */
private String writeSpec() throws RiakException {

    final ByteArrayOutputStream out = new ByteArrayOutputStream();

    try {
        JsonGenerator jg = new JsonFactory().createJsonGenerator(out, JsonEncoding.UTF8);
        jg.setCodec(new ObjectMapper());

        jg.writeStartObject();

        jg.writeFieldName("inputs");
        writeInput(jg);

        jg.writeFieldName("query");
        jg.writeStartArray();

        writePhases(jg);

        jg.writeEndArray();
        if (timeout != null) {
            jg.writeNumberField("timeout", timeout);
        }

        jg.writeEndObject();
        jg.flush();

        return out.toString("UTF8");
    } catch (IOException e) {
        throw new RiakException(e);
    }
}

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

protected void doContainerSerialize(final ResWrap<EntityCollection> container, final JsonGenerator jgen)
        throws IOException, EdmPrimitiveTypeException {

    final EntityCollection entitySet = container.getPayload();

    jgen.writeStartObject();//from   w w w.ja  va2s  . c  om

    if (serverMode) {
        if (container.getContextURL() != null) {
            jgen.writeStringField(Constants.JSON_CONTEXT, container.getContextURL().toASCIIString());
        }

        if (StringUtils.isNotBlank(container.getMetadataETag())) {
            jgen.writeStringField(Constants.JSON_METADATA_ETAG, container.getMetadataETag());
        }
    }

    if (entitySet.getId() != null) {
        jgen.writeStringField(Constants.JSON_ID, entitySet.getId().toASCIIString());
    }
    jgen.writeNumberField(Constants.JSON_COUNT,
            entitySet.getCount() == null ? entitySet.getEntities().size() : entitySet.getCount());
    if (serverMode) {
        if (entitySet.getNext() != null) {
            jgen.writeStringField(Constants.JSON_NEXT_LINK, entitySet.getNext().toASCIIString());
        }
        if (entitySet.getDeltaLink() != null) {
            jgen.writeStringField(Constants.JSON_DELTA_LINK, entitySet.getDeltaLink().toASCIIString());
        }
    }

    for (Annotation annotation : entitySet.getAnnotations()) {
        valuable(jgen, annotation, "@" + annotation.getTerm());
    }

    jgen.writeArrayFieldStart(Constants.VALUE);
    final JsonEntitySerializer entitySerializer = new JsonEntitySerializer(serverMode, contentType);
    for (Entity entity : entitySet.getEntities()) {
        entitySerializer.doSerialize(entity, jgen);
    }
    jgen.writeEndArray();

    jgen.writeEndObject();
}

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 ava 2 s .  c om
 */
@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:org.springframework.cloud.netflix.metrics.atlas.AtlasMetricObserver.java

private int writeMetrics(JsonGenerator gen, List<Metric> metrics) throws IOException {
    int totalMetricsInBatch = 0;
    gen.writeArrayFieldStart("metrics");

    for (Metric m : metrics) {
        if (!validTags(m.getConfig().getTags()))
            continue;

        if (!Number.class.isAssignableFrom(m.getValue().getClass()))
            continue;

        gen.writeStartObject();//w w  w  .  jav a2 s .  c o  m

        gen.writeObjectFieldStart("tags");
        gen.writeStringField("name", m.getConfig().getName());
        for (Tag tag : m.getConfig().getTags())
            gen.writeStringField(tag.getKey(), tag.getValue());
        gen.writeEndObject();

        gen.writeNumberField("start", m.getTimestamp());
        gen.writeNumberField("value", m.getNumberValue().doubleValue());

        gen.writeEndObject();

        totalMetricsInBatch++;
    }

    gen.writeEndArray();
    return totalMetricsInBatch;
}

From source file:org.n52.ar.layar.LayarResponse.java

/**
 * /*w w w . j  a  va  2s  .  co m*/
 * "hotspots": [{
 * 
 * "id": "test_1",
 * 
 * "anchor": { "geolocation": { "lat": 52.3729, "lon": 4.93 } },
 * 
 * "text": { "title": "The Layar Office", "description": "The Location of the Layar Office", "footnote":
 * "Powered by Layar" },
 * 
 * "imageURL": "http:\/\/custom.layar.nl\/layarimage.jpeg", }
 * 
 * ]
 * 
 * See http://layar.com/documentation/browser/api/getpois-response/hotspots/
 * 
 * @param generator
 * @param hotspots2
 * @throws IOException
 * @throws JsonGenerationException
 */
private void createHotspots(JsonGenerator generator) throws JsonGenerationException, IOException {
    generator.writeFieldName("hotspots");
    generator.writeStartArray();
    for (Hotspot poi : this.hotspots) {

        generator.writeStartObject();
        generator.writeStringField("id", poi.id);

        // generator.writeFieldName("actions");
        // generator.writeStartArray();
        // if (layarPOI.actions != null) {
        // for (final LayarAction layarAction : layarPOI.actions) {
        // layarAction.toJSON(generator);
        // }
        // }
        // generator.writeEndArray();

        generator.writeObjectFieldStart("anchor");
        generator.writeObjectFieldStart("geolocation");
        generator.writeNumberField("lat", poi.lat);
        generator.writeNumberField("lon", poi.lon);
        generator.writeNumberField("alt", poi.alt);
        generator.writeEndObject();
        generator.writeEndObject();

        // generator.writeNumberField("distance", layarPOI.distance);
        // generator.writeNumberField("type", layarPOI.type);
        // generator.writeStringField("title", layarPOI.title);
        generator.writeObjectFieldStart("text");
        generator.writeStringField("title", poi.title);
        generator.writeStringField("description", poi.description);
        generator.writeStringField("footnote", "Service URL: ...");
        generator.writeEndObject();

        generator.writeStringField("attribution", poi.attribution);
        if (poi.imageURL != null) {
            generator.writeStringField("imageURL", poi.imageURL.toString());
        } else {
            generator.writeNullField("imageURL");
        }
        generator.writeEndObject();
    }
    generator.writeEndArray();

}

From source file:net.opentsdb.meta.UIDMeta.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
 *//*from w w w .j  a  v a 2  s .co  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("type", type.toString());
        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.writeEndObject();
        json.close();
        return output.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException("Unable to serialize UIDMeta", e);
    }
}

From source file:net.opentsdb.meta.Annotation.java

/**
 * Serializes the object in a uniform matter for storage. Needed for 
 * successful CAS calls//w  ww  .java  2 s  . c  o m
 * @return The serialized object as a byte array
 */
private byte[] getStorageJSON() {
    // TODO - precalculate size
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    try {
        final JsonGenerator json = JSON.getFactory().createGenerator(output);
        json.writeStartObject();
        if (tsuid != null && !tsuid.isEmpty()) {
            json.writeStringField("tsuid", tsuid);
        }
        json.writeNumberField("startTime", start_time);
        json.writeNumberField("endTime", end_time);
        json.writeStringField("description", description);
        json.writeStringField("notes", notes);
        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.writeEndObject();
        json.close();
        return output.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException("Unable to serialize Annotation", e);
    }
}

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

@Override
public void write(@Nonnull Writer writer, @Nonnull Server server, @Nonnull Query query,
        @Nonnull Iterable<Result> results) throws IOException {
    Closer closer = Closer.create();//from  w w w  . ja va2 s .  co m
    try {
        JsonGenerator g = closer.register(jsonFactory.createGenerator(writer));
        g.writeStartObject();
        g.writeArrayFieldStart("counters");
        g.writeEndArray();

        String source = getSource(server);

        g.writeArrayFieldStart("gauges");
        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", SECONDS.convert(result.getEpoch(), 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();
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}

From source file:tds.student.web.controls.dummy.GlobalJavascriptWriter.java

public void writeBrowserInfo() throws JsonGenerationException, IOException {
    StringWriter sw = new StringWriter();
    JsonFactory jsonFactory = new JsonFactory();
    JsonGenerator jsonWriter = jsonFactory.createGenerator(sw);

    jsonWriter.writeStartObject();// {

    // browser info
    BrowserParser browser = new BrowserParser();
    jsonWriter.writeStringField("userAgent", browser.getUserAgent());
    jsonWriter.writeStringField("osLabel", browser.getOSFullName());
    jsonWriter.writeStringField("osName", String.valueOf(browser.getOsName()));
    jsonWriter.writeNumberField("osVersion", browser.getVersion());
    jsonWriter.writeStringField("architecture", browser.getHardwareArchitecture());
    jsonWriter.writeStringField("name", browser.getName());
    jsonWriter.writeNumberField("version", browser.getVersion());
    jsonWriter.writeBooleanField("isSecure", browser.isSecureBrowser());

    String label;//  w ww.j  av  a  2  s  .co  m
    if (browser.isSecureBrowser())
        label = String.format("Secure v%s", "" + browser.getVersion());
    else
        label = String.format("%s v%s", browser.getName(), "" + browser.getVersion());
    jsonWriter.writeStringField("label", label);

    jsonWriter.writeEndObject(); // }
    jsonWriter.close();
    // TODO shiva: do we need to do sw.getBuffer () below.
    _writer.write(String.format("TDS.BrowserInfo = %s; ", sw.getBuffer().toString()));
    _writer.write("\n\r");
}