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.n52.ar.layar.LayarResponse.java

public void toJSON(final JsonGenerator generator) throws IOException {
    generator.writeStartObject();/*from  w  w w .ja  va 2  s .  c  om*/

    /*
     * mandatory:
     */
    generator.writeStringField("layer", this.layer);
    if (this.errorCode != CODE_ERROR && this.hotspots.size() < 1) {
        this.errorString = "No POI found. Please increase the search range to try again.";
        this.errorCode = CODE_ERROR;
    }
    generator.writeStringField("errorString", this.errorString);
    generator.writeNumberField("errorCode", this.errorCode);

    // paging is not implemented yet
    generator.writeBooleanField("morePages", this.morePages);
    if (this.nextPageKey != null) {
        generator.writeStringField("nextPageKey", this.nextPageKey);
    } else {
        generator.writeNullField("nextPageKey");
    }
    // generator.writeNumberField("refreshInterval", 3600);
    // generator.writeNumberField("refreshDistance", 50);
    // generator.writeBooleanField("fullRefresh", false);
    // actions for the entire layer: http://layar.com/documentation/browser/api/getpois-response/actions/
    if (this.errorCode == CODE_OK)
        this.showMessage = "You got " + this.hotspots.size() + " hits in the area around you!";
    generator.writeStringField("showMessage", this.showMessage);
    // deletedHotspots
    // animations
    // showDialog: title, description, iconURL, actions
    generator.writeNullField("biwStyle");

    /*
     * hotspots (mandatory):
     */
    createHotspots(generator);

    generator.writeEndObject();
}

From source file:com.predic8.membrane.core.interceptor.administration.AdminRESTInterceptor.java

@Mapping("/admin/rest/exchanges(/?\\?.*)?")
public Response getExchanges(QueryParameter params, String relativeRootPath) throws Exception {

    if (params.getString("waitForModification") != null) {
        getRouter().getExchangeStore().waitForModification(params.getLong("waitForModification"));
    }//from w  w  w  .  ja v a  2  s  .c o m

    List<AbstractExchange> exchanges;
    synchronized (getRouter().getExchangeStore().getAllExchangesAsList()) {
        exchanges = new ArrayList<AbstractExchange>(getRouter().getExchangeStore().getAllExchangesAsList());
    }

    exchanges = filter(params, exchanges);

    Collections.sort(exchanges, ComparatorFactory.getAbstractExchangeComparator(
            params.getString("sort", "time"), params.getString("order", "desc")));

    int offset = params.getInt("offset", 0);
    int max = params.getInt("max", exchanges.size());

    final int total = exchanges.size();
    final List<AbstractExchange> paginated = exchanges.subList(offset,
            Math.min(offset + max, exchanges.size()));

    return json(new JSONContent() {
        public void write(JsonGenerator gen) throws Exception {
            gen.writeStartObject();
            gen.writeArrayFieldStart("exchanges");
            for (AbstractExchange e : paginated) {
                writeExchange(e, gen);
            }
            gen.writeEndArray();
            gen.writeNumberField("total", total);
            gen.writeNumberField("lastModified", getRouter().getExchangeStore().getLastModified());
            gen.writeEndObject();
        }
    });
}

From source file:com.attribyte.essem.es.SearchRequest.java

@Override
public void generate(final JsonGenerator generator) throws IOException {
    generator.writeStartObject();//from  w  ww.  j  av  a  2  s. co  m
    {
        if (!retrieveSource)
            generator.writeBooleanField("_source", false);
        if (explain)
            generator.writeBooleanField("explain", true);
        if (!disablePaging) {
            generator.writeNumberField("from", start);
            generator.writeNumberField("size", limit);
        }
        if (timeoutSeconds > 0) {
            generator.writeNumberField("timeout", timeoutSeconds * 1000);
        }
        if (sortField != null)
            generateSort(generator);
        if (fields != null && fields.size() > 0)
            generateFields(generator);
        if (query != null) {
            generator.writeFieldName("query");
            query.generate(generator);
        }

        if (sort != null) {
            sort.generate(generator);
        }

        if (aggregations != null && aggregations.size() > 0) {
            generator.writeObjectFieldStart(Aggregation.AGGREGATION_OBJECT_NAME);
            for (Aggregation aggregation : aggregations) {
                aggregation.generate(generator);
            }
            generator.writeEndObject();
        }
    }
    generator.writeEndObject();
}

From source file:com.predic8.membrane.core.interceptor.administration.AdminRESTInterceptor.java

@Mapping("/admin/rest/clients(/?\\?.*)?")
public Response getClients(QueryParameter params, String relativeRootPath) throws Exception {
    final List<? extends ClientStatistics> clients = getRouter().getExchangeStore().getClientStatistics();

    Collections.sort(clients, ComparatorFactory.getClientStatisticsComparator(params.getString("sort", "name"),
            params.getString("order", "asc")));

    int offset = params.getInt("offset", 0);
    int max = params.getInt("max", clients.size());

    final int total = clients.size();
    final List<? extends ClientStatistics> paginated = clients.subList(offset,
            Math.min(offset + max, clients.size()));

    return json(new JSONContent() {
        public void write(JsonGenerator gen) throws Exception {
            gen.writeStartObject();// w ww.  j a  v a  2s.  co m
            gen.writeArrayFieldStart("clients");
            for (ClientStatistics s : paginated) {
                gen.writeStartObject();
                gen.writeStringField("name", s.getClient());
                gen.writeNumberField("count", s.getCount());
                gen.writeNumberField("min", s.getMinDuration());
                gen.writeNumberField("max", s.getMaxDuration());
                gen.writeNumberField("avg", s.getAvgDuration());
                gen.writeEndObject();
            }
            gen.writeEndArray();
            gen.writeNumberField("total", total);
            gen.writeEndObject();
        }
    });
}

From source file:io.mesosphere.mesos.frameworks.cassandra.scheduler.api.ConfigController.java

/**
 * Returns the configuration as JSON./* w w  w  .j ava2 s  . c  om*/
 *
 *     Example: <pre>{@code {
 * "frameworkName" : "cassandra",
 * "frameworkId" : "20150318-143436-16777343-5050-5621-0000",
 * "defaultConfigRole" : {
 *     "cassandraVersion" : "2.1.4",
 *     "targetNodeCount" : 2,
 *     "seedNodeCount" : 1,
 *     "diskMb" : 2048,
 *     "cpuCores" : 2.0,
 *     "memJavaHeapMb" : 1024,
 *     "memAssumeOffHeapMb" : 1024,
 *     "memMb" : 2048,
 *     "taskEnv" : null
 * },
 * "nativePort" : 9042,
 * "rpcPort" : 9160,
 * "storagePort" : 7000,
 * "sslStoragePort" : 7001,
 * "seeds" : [ "127.0.0.1" ],
 * "healthCheckIntervalSeconds" : 10,
 * "bootstrapGraceTimeSeconds" : 0,
 * "currentClusterTask" : null,
 * "lastRepair" : null,
 * "lastCleanup" : null,
 * "nextPossibleServerLaunchTimestamp" : 1426685858805
 * }}</pre>
 */
@GET
public Response config() {
    return JaxRsUtils.buildStreamingResponse(factory, new StreamingJsonResponse() {
        @Override
        public void write(final JsonGenerator json) throws IOException {

            final PersistedCassandraFrameworkConfiguration configuration = cluster.getConfiguration();
            final CassandraFrameworkProtos.CassandraFrameworkConfiguration config = configuration.get();

            json.writeStringField("frameworkName", config.getFrameworkName());
            json.writeStringField("frameworkId", config.getFrameworkId());
            json.writeStringField("clusterName", config.getClusterName());
            json.writeNumberField("targetNumberOfNodes", config.getTargetNumberOfNodes());
            json.writeNumberField("targetNumberOfSeeds", config.getTargetNumberOfSeeds());

            final NodeCounts nodeCounts = cluster.getClusterState().nodeCounts();
            json.writeNumberField("currentNumberOfNodes", nodeCounts.getNodeCount());
            json.writeNumberField("currentNumberOfSeeds", nodeCounts.getSeedCount());
            json.writeNumberField("nodesToAcquire",
                    CassandraCluster.numberOfNodesToAcquire(nodeCounts, configuration));
            json.writeNumberField("seedsToAcquire",
                    CassandraCluster.numberOfSeedsToAcquire(nodeCounts, configuration));

            final CassandraFrameworkProtos.CassandraConfigRole configRole = config.getDefaultConfigRole();
            json.writeObjectFieldStart("defaultConfigRole");
            JaxRsUtils.writeConfigRole(json, configRole);
            json.writeEndObject();

            json.writeNumberField("nativePort",
                    CassandraCluster.getPortMapping(config, CassandraCluster.PORT_NATIVE));
            json.writeNumberField("rpcPort",
                    CassandraCluster.getPortMapping(config, CassandraCluster.PORT_RPC));
            json.writeNumberField("storagePort",
                    CassandraCluster.getPortMapping(config, CassandraCluster.PORT_STORAGE));
            json.writeNumberField("sslStoragePort",
                    CassandraCluster.getPortMapping(config, CassandraCluster.PORT_STORAGE_SSL));

            JaxRsUtils.writeSeedIps(cluster, json);

            json.writeNumberField("healthCheckIntervalSeconds", config.getHealthCheckIntervalSeconds());
            json.writeNumberField("bootstrapGraceTimeSeconds", config.getBootstrapGraceTimeSeconds());

            final CassandraFrameworkProtos.ClusterJobStatus currentTask = cluster.getCurrentClusterJob();
            JaxRsUtils.writeClusterJob(cluster, json, "currentClusterTask", currentTask);

            final CassandraFrameworkProtos.ClusterJobStatus lastRepair = cluster
                    .getLastClusterJob(CassandraFrameworkProtos.ClusterJobType.REPAIR);
            JaxRsUtils.writeClusterJob(cluster, json, "lastRepair", lastRepair);

            final CassandraFrameworkProtos.ClusterJobStatus lastCleanup = cluster
                    .getLastClusterJob(CassandraFrameworkProtos.ClusterJobType.CLEANUP);
            JaxRsUtils.writeClusterJob(cluster, json, "lastCleanup", lastCleanup);

            json.writeNumberField("nextPossibleServerLaunchTimestamp",
                    cluster.nextPossibleServerLaunchTimestamp());

        }
    });
}

From source file:org.springframework.security.oauth2.common.OAuth2AccessTokenJackson2Serializer.java

@Override
public void serialize(OAuth2AccessToken token, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonGenerationException {
    jgen.writeStartObject();/*from  ww w.j  a  v a2s .  c om*/
    jgen.writeStringField(OAuth2AccessToken.ACCESS_TOKEN, token.getValue());
    jgen.writeStringField(OAuth2AccessToken.TOKEN_TYPE, token.getTokenType());
    OAuth2RefreshToken refreshToken = token.getRefreshToken();
    if (refreshToken != null) {
        jgen.writeStringField(OAuth2AccessToken.REFRESH_TOKEN, refreshToken.getValue());
    }
    Date expiration = token.getExpiration();
    if (expiration != null) {
        long now = System.currentTimeMillis();
        jgen.writeNumberField(OAuth2AccessToken.EXPIRES_IN, (expiration.getTime() - now) / 1000);
    }
    Set<String> scope = token.getScope();
    if (scope != null && !scope.isEmpty()) {
        StringBuffer scopes = new StringBuffer();
        for (String s : scope) {
            Assert.hasLength(s, "Scopes cannot be null or empty. Got " + scope + "");
            scopes.append(s);
            scopes.append(" ");
        }
        jgen.writeStringField(OAuth2AccessToken.SCOPE, scopes.substring(0, scopes.length() - 1));
    }
    Map<String, Object> additionalInformation = token.getAdditionalInformation();
    for (String key : additionalInformation.keySet()) {
        jgen.writeObjectField(key, additionalInformation.get(key));
    }
    jgen.writeEndObject();
}

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

@Override
public void highlight(Highlighter highlighter, Set<Integer> docIds, Set<String> fields, Writer out) {
    try {/*from w  ww.ja v a2 s. co  m*/
        Map<Integer, Set<HighlightTerm>> termMap = highlighter.highlight(docIds, fields);
        JsonFactory jsonFactory = new JsonFactory();
        JsonGenerator jsonGen = jsonFactory.createGenerator(out);

        jsonGen.writeStartObject();

        for (int docId : docIds) {
            Document doc = indexSearcher.doc(docId);
            jsonGen.writeObjectFieldStart(doc.get("id"));
            jsonGen.writeStringField("path", doc.get("path"));
            jsonGen.writeNumberField("docId", docId);

            jsonGen.writeArrayFieldStart("terms");
            for (HighlightTerm term : termMap.get(docId)) {
                fields.add(term.getField());
                term.toJson(jsonGen, df);
            }
            jsonGen.writeEndArray();

            if (includeText) {
                for (String field : fields) {
                    jsonGen.writeObjectFieldStart("field" + field);
                    Set<HighlightTerm> terms = termMap.get(docId);
                    jsonGen.writeStringField("contents", this.displayHighlights(docId, field, terms));
                    jsonGen.writeEndObject();
                }
            }

            jsonGen.writeEndObject();
        }

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

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

public void serialize(@Nonnull Iterable<QueryResult> counters, @Nonnull Iterable<QueryResult> gauges,
        @Nonnull OutputStream out) throws IOException {
    JsonGenerator g = jsonFactory.createGenerator(out, JsonEncoding.UTF8);
    g.writeStartObject();//from   w  w  w.  j av  a 2s. c om
    g.writeArrayFieldStart("counters");

    for (QueryResult counter : counters) {
        g.writeStartObject();
        g.writeStringField("name", counter.getName());
        if (source != null && !source.isEmpty()) {
            g.writeStringField("source", source);
        }
        g.writeNumberField("measure_time", counter.getEpoch(TimeUnit.SECONDS));
        if (counter.getValue() instanceof Integer) {
            g.writeNumberField("value", (Integer) counter.getValue());
        } else if (counter.getValue() instanceof Long) {
            g.writeNumberField("value", (Long) counter.getValue());
        } else if (counter.getValue() instanceof Float) {
            g.writeNumberField("value", (Float) counter.getValue());
        } else if (counter.getValue() instanceof Double) {
            g.writeNumberField("value", (Double) counter.getValue());
        } else if (counter.getValue() instanceof AtomicInteger) {
            g.writeNumberField("value", ((AtomicInteger) counter.getValue()).get());
        } else if (counter.getValue() instanceof AtomicLong) {
            g.writeNumberField("value", ((AtomicLong) counter.getValue()).get());
        }
        g.writeEndObject();
    }
    g.writeEndArray();

    g.writeArrayFieldStart("gauges");

    for (QueryResult gauge : gauges) {
        g.writeStartObject();
        g.writeStringField("name", gauge.getName());
        if (source != null && !source.isEmpty()) {
            g.writeStringField("source", source);
        }
        g.writeNumberField("measure_time", gauge.getEpoch(TimeUnit.SECONDS));
        if (gauge.getValue() instanceof Integer) {
            g.writeNumberField("value", (Integer) gauge.getValue());
        } else if (gauge.getValue() instanceof Long) {
            g.writeNumberField("value", (Long) gauge.getValue());
        } else if (gauge.getValue() instanceof Float) {
            g.writeNumberField("value", (Float) gauge.getValue());
        } else if (gauge.getValue() instanceof Double) {
            g.writeNumberField("value", (Double) gauge.getValue());
        } else if (gauge.getValue() instanceof AtomicInteger) {
            g.writeNumberField("value", ((AtomicInteger) gauge.getValue()).get());
        } else if (gauge.getValue() instanceof AtomicLong) {
            g.writeNumberField("value", ((AtomicLong) gauge.getValue()).get());
        }
        g.writeEndObject();
    }
    g.writeEndArray();
    g.writeEndObject();
    g.flush();
    g.close();
}

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 w  w w.j a v  a2 s  .co  m*/

    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());
}

From source file:com.cloudera.exhibit.server.json.ExhibitSerializer.java

private void serializeObs(Obs obs, ObsDescriptor desc, JsonGenerator gen) throws IOException {
    for (int i = 0; i < desc.size(); i++) {
        ObsDescriptor.Field f = desc.get(i);
        Object value = obs.get(i);
        if (value == null) {
            gen.writeNullField(f.name);//  ww  w .java 2 s.  com
        } else {
            switch (f.type) {
            case STRING:
                gen.writeStringField(f.name, value.toString());
                break;
            case BOOLEAN:
                gen.writeBooleanField(f.name, (Boolean) value);
                break;
            case INTEGER:
                gen.writeNumberField(f.name, ((Number) value).intValue());
                break;
            case FLOAT:
                gen.writeNumberField(f.name, ((Number) value).floatValue());
                break;
            case DOUBLE:
                gen.writeNumberField(f.name, ((Number) value).doubleValue());
                break;
            case LONG:
                gen.writeNumberField(f.name, ((Number) value).longValue());
                break;
            default:
                throw new UnsupportedOperationException("Unknown type for field: " + f);
            }
        }
    }
}