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

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

Introduction

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

Prototype

public void writeStringField(String fieldName, String value) throws IOException, JsonGenerationException 

Source Link

Document

Convenience method for outputting a field entry ("member") that has a String value.

Usage

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

/**
 * Retrieve a list of all nodes including their status.
 *
 *     <pre>{@code {/*  w w w.  ja va 2 s . c  om*/
 * "replaceNodes" : [ ],
 * "nodesToAcquire" : 0,
 * "nodes" : [ {
 *     "tasks" : {
 *         "METADATA" : {
 *             "cpuCores" : 0.1,
 *             "diskMb" : 16,
 *             "memMb" : 16,
 *             "taskId" : "cassandra.node.0.executor"
 *         },
 *         "SERVER" : {
 *             "cpuCores" : 2.0,
 *             "diskMb" : 2048,
 *             "memMb" : 2048,
 *             "taskId" : "cassandra.node.0.executor.server"
 *         }
 *     },
 *     "executorId" : "cassandra.node.0.executor",
 *     "ip" : "127.0.0.2",
 *     "hostname" : "127.0.0.2",
 *     "targetRunState" : "RUN",
 *     "jmxPort" : 64112,
 *     "seedNode" : true,
 *     "cassandraDaemonPid" : 6104,
 *     "lastHealthCheck" : 1426686217128,
 *     "healthCheckDetails" : {
 *         "healthy" : true,
 *         "msg" : "",
 *         "version" : "2.1.4",
 *         "operationMode" : "NORMAL",
 *         "clusterName" : "cassandra",
 *         "dataCenter" : "DC1",
 *         "rack" : "RAC1",
 *         "endpoint" : "127.0.0.2",
 *         "hostId" : "4207396e-6aa0-432e-97d9-1a4df3c1057f",
 *         "joined" : true,
 *         "gossipInitialized" : true,
 *         "gossipRunning" : true,
 *         "nativeTransportRunning" : true,
 *         "rpcServerRunning" : true,
 *         "tokenCount" : 256,
 *         "uptimeMillis" : 29072
 *     }
 * }, {
 *     "tasks" : {
 *     "METADATA" : {
 *         "cpuCores" : 0.1,
 *         "diskMb" : 16,
 *         "memMb" : 16,
 *         "taskId" : "cassandra.node.1.executor"
 *     },
 *     "SERVER" : {
 *         "cpuCores" : 2.0,
 *         "diskMb" : 2048,
 *         "memMb" : 2048,
 *         "taskId" : "cassandra.node.1.executor.server"
 *     }
 *     },
 *     "executorId" : "cassandra.node.1.executor",
 *     "ip" : "127.0.0.1",
 *     "hostname" : "localhost",
 *     "targetRunState" : "RUN",
 *     "jmxPort" : 64113,
 *     "seedNode" : false,
 *     "cassandraDaemonPid" : 6127,
 *     "lastHealthCheck" : 1426686217095,
 *     "healthCheckDetails" : {
 *         "healthy" : true,
 *         "msg" : "",
 *         "version" : "2.1.4",
 *         "operationMode" : "JOINING",
 *         "clusterName" : "cassandra",
 *         "dataCenter" : "",
 *         "rack" : "",
 *         "endpoint" : "",
 *         "hostId" : "",
 *         "joined" : true,
 *         "gossipInitialized" : true,
 *         "gossipRunning" : true,
 *         "nativeTransportRunning" : false,
 *         "rpcServerRunning" : false,
 *         "tokenCount" : 0,
 *         "uptimeMillis" : 16936
 *     }
 * } ]
 * }}</pre>
 */
@GET
@Path("/all")
public Response nodes() {
    return JaxRsUtils.buildStreamingResponse(factory, new StreamingJsonResponse() {
        @Override
        public void write(final JsonGenerator json) throws IOException {
            final CassandraFrameworkProtos.CassandraClusterState clusterState = cluster.getClusterState().get();

            json.writeArrayFieldStart("replaceNodes");
            for (final String ip : clusterState.getReplaceNodeIpsList()) {
                json.writeString(ip);
            }
            json.writeEndArray();

            final NodeCounts nodeCounts = cluster.getClusterState().nodeCounts();
            json.writeNumberField("nodesToAcquire",
                    CassandraCluster.numberOfNodesToAcquire(nodeCounts, cluster.getConfiguration()));

            json.writeArrayFieldStart("nodes");
            for (final CassandraFrameworkProtos.CassandraNode cassandraNode : clusterState.getNodesList()) {
                json.writeStartObject();

                if (cassandraNode.hasReplacementForIp()) {
                    json.writeStringField("replacementForIp", cassandraNode.getReplacementForIp());
                }

                json.writeObjectFieldStart("tasks");
                for (final CassandraFrameworkProtos.CassandraNodeTask cassandraNodeTask : cassandraNode
                        .getTasksList()) {
                    JaxRsUtils.writeTask(json, cassandraNodeTask);
                }
                json.writeEndObject();
                // TODO                cassandraNode.getDataVolumesList();

                if (!cassandraNode.hasCassandraNodeExecutor()) {
                    json.writeNullField("executorId");
                    json.writeNullField("workdir");
                } else {
                    json.writeStringField("executorId",
                            cassandraNode.getCassandraNodeExecutor().getExecutorId());
                    final CassandraFrameworkProtos.ExecutorMetadata executorMetadata = cluster
                            .metadataForExecutor(cassandraNode.getCassandraNodeExecutor().getExecutorId());
                    if (executorMetadata != null) {
                        json.writeStringField("workdir", executorMetadata.getWorkdir());
                    } else {
                        json.writeNullField("workdir");
                    }
                }
                json.writeStringField("ip", cassandraNode.getIp());
                json.writeStringField("hostname", cassandraNode.getHostname());
                json.writeStringField("targetRunState", cassandraNode.getTargetRunState().name());
                json.writeNumberField("jmxPort", cassandraNode.getJmxConnect().getJmxPort());
                json.writeBooleanField("seedNode", cassandraNode.getSeed());

                CassandraFrameworkProtos.RackDc rackDc = cassandraNode.getRackDc();
                json.writeObjectFieldStart("rackDc");
                json.writeStringField("rack", rackDc.getRack());
                json.writeStringField("dc", rackDc.getDc());
                json.writeEndObject();

                if (!cassandraNode.hasCassandraDaemonPid()) {
                    json.writeNullField("cassandraDaemonPid");
                } else {
                    json.writeNumberField("cassandraDaemonPid", cassandraNode.getCassandraDaemonPid());
                }

                final CassandraFrameworkProtos.HealthCheckHistoryEntry lastHealthCheck = cassandraNode
                        .hasCassandraNodeExecutor()
                                ? cluster.lastHealthCheck(
                                        cassandraNode.getCassandraNodeExecutor().getExecutorId())
                                : null;

                if (lastHealthCheck != null) {
                    json.writeNumberField("lastHealthCheck", lastHealthCheck.getTimestampEnd());
                } else {
                    json.writeNullField("lastHealthCheck");
                }

                if (lastHealthCheck != null) {
                    json.writeObjectFieldStart("healthCheckDetails");

                    final CassandraFrameworkProtos.HealthCheckDetails hcd = lastHealthCheck.getDetails();

                    json.writeBooleanField("healthy", hcd.getHealthy());
                    json.writeStringField("msg", hcd.getMsg());

                    json.writeStringField("version", hcd.getInfo().getVersion());
                    json.writeStringField("operationMode", hcd.getInfo().getOperationMode());
                    json.writeStringField("clusterName", hcd.getInfo().getClusterName());
                    json.writeStringField("dataCenter", hcd.getInfo().getDataCenter());
                    json.writeStringField("rack", hcd.getInfo().getRack());
                    json.writeStringField("endpoint", hcd.getInfo().getEndpoint());
                    json.writeStringField("hostId", hcd.getInfo().getHostId());
                    json.writeBooleanField("joined", hcd.getInfo().getJoined());
                    json.writeBooleanField("gossipInitialized", hcd.getInfo().getGossipInitialized());
                    json.writeBooleanField("gossipRunning", hcd.getInfo().getGossipRunning());
                    json.writeBooleanField("nativeTransportRunning", hcd.getInfo().getNativeTransportRunning());
                    json.writeBooleanField("rpcServerRunning", hcd.getInfo().getRpcServerRunning());
                    json.writeNumberField("tokenCount", hcd.getInfo().getTokenCount());
                    json.writeNumberField("uptimeMillis", hcd.getInfo().getUptimeMillis());

                    json.writeEndObject();
                } else {
                    json.writeNullField("healthCheckDetails");
                }

                final List<CassandraFrameworkProtos.DataVolume> dataVolumes = cassandraNode
                        .getDataVolumesList();
                json.writeArrayFieldStart("dataVolumes");
                for (final CassandraFrameworkProtos.DataVolume volume : dataVolumes) {
                    json.writeStartObject();
                    json.writeStringField("path", volume.getPath());
                    if (volume.hasSizeMb()) {
                        json.writeNumberField("size", volume.getSizeMb());
                    }
                    json.writeEndObject();
                }
                json.writeEndArray();

                json.writeEndObject();
            }
            json.writeEndArray();
        }
    });
}

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

private void writeOperations(final List<Operation> operations, final JsonGenerator json) throws IOException {
    if (isODataMetadataFull) {
        for (Operation operation : operations) {
            json.writeObjectFieldStart(operation.getMetadataAnchor());
            json.writeStringField(Constants.ATTR_TITLE, operation.getTitle());
            json.writeStringField(Constants.ATTR_TARGET, operation.getTarget().toASCIIString());
            json.writeEndObject();//from www  .j  a va 2 s .  c o m
        }
    }
}

From source file:com.google.openrtb.json.OpenRtbJsonWriter.java

protected void writeNativeFields(Native nativ, JsonGenerator gen) throws IOException {
    switch (nativ.getRequestOneofCase()) {
    case REQUEST_NATIVE:
        gen.writeFieldName("request");
        if (factory().isForceNativeAsObject()) {
            nativeWriter().writeNativeRequest(nativ.getRequestNative(), gen);
        } else {/*from   www.j ava 2 s .  c o m*/
            gen.writeString(nativeWriter().writeNativeRequest(nativ.getRequestNative()));
        }
        break;
    case REQUEST:
        gen.writeStringField("request", nativ.getRequest());
        break;
    case REQUESTONEOF_NOT_SET:
        checkRequired(false);
    }
    if (nativ.hasVer()) {
        gen.writeStringField("ver", nativ.getVer());
    }
    writeEnums("api", nativ.getApiList(), gen);
    writeEnums("battr", nativ.getBattrList(), gen);
}

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

void writeMetadataETag(final ServiceMetadata metadata, final JsonGenerator json) throws IOException {
    if (!isODataMetadataNone && metadata != null && metadata.getServiceMetadataETagSupport() != null
            && metadata.getServiceMetadataETagSupport().getMetadataETag() != null) {
        json.writeStringField(constants.getMetadataEtag(),
                metadata.getServiceMetadataETagSupport().getMetadataETag());
    }//w  ww .  ja  v  a  2s.c o  m
}

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

protected void writeEntitySet(final ServiceMetadata metadata, final EdmEntityType entityType,
        final AbstractEntityCollection entitySet, final ExpandOption expand, Integer toDepth,
        final SelectOption select, final boolean onlyReference, final Set<String> ancestors, String name,
        final JsonGenerator json) throws IOException, SerializerException, DecoderException {
    json.writeStartArray();//from   w  w  w. ja v a 2 s. c o m
    for (final Entity entity : entitySet) {
        if (onlyReference) {
            json.writeStartObject();
            json.writeStringField(constants.getId(), getEntityId(entity, entityType, name));
            json.writeEndObject();
        } else {
            writeEntity(metadata, entityType, entity, null, expand, toDepth, select, false, ancestors, name,
                    json);
        }
    }
    json.writeEndArray();
}

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

protected void clientLinks(final Linked linked, final JsonGenerator jgen)
        throws IOException, EdmPrimitiveTypeException {

    final Map<String, List<String>> entitySetLinks = new HashMap<String, List<String>>();
    for (Link link : linked.getNavigationLinks()) {
        for (Annotation annotation : link.getAnnotations()) {
            valuable(jgen, annotation, link.getTitle() + "@" + annotation.getTerm());
        }/* ww  w. j  a  va2 s.  com*/

        ODataLinkType type = null;
        try {
            type = ODataLinkType.fromString(version, link.getRel(), link.getType());
        } catch (IllegalArgumentException e) {
            // ignore
        }

        if (type == ODataLinkType.ENTITY_SET_NAVIGATION) {
            final List<String> uris;
            if (entitySetLinks.containsKey(link.getTitle())) {
                uris = entitySetLinks.get(link.getTitle());
            } else {
                uris = new ArrayList<String>();
                entitySetLinks.put(link.getTitle(), uris);
            }
            if (StringUtils.isNotBlank(link.getHref())) {
                uris.add(link.getHref());
            }
        } else {
            if (StringUtils.isNotBlank(link.getHref())) {
                jgen.writeStringField(link.getTitle() + Constants.JSON_BIND_LINK_SUFFIX, link.getHref());
            }
        }

        if (link.getInlineEntity() != null) {
            jgen.writeFieldName(link.getTitle());
            new JsonEntitySerializer(version, serverMode).doSerialize(link.getInlineEntity(), jgen);
        } else if (link.getInlineEntitySet() != null) {
            jgen.writeArrayFieldStart(link.getTitle());
            final JsonEntitySerializer entitySerializer = new JsonEntitySerializer(version, serverMode);
            for (Entity subEntry : link.getInlineEntitySet().getEntities()) {
                entitySerializer.doSerialize(subEntry, jgen);
            }
            jgen.writeEndArray();
        }
    }
    for (Map.Entry<String, List<String>> entitySetLink : entitySetLinks.entrySet()) {
        if (!entitySetLink.getValue().isEmpty()) {
            jgen.writeArrayFieldStart(entitySetLink.getKey() + Constants.JSON_BIND_LINK_SUFFIX);
            for (String uri : entitySetLink.getValue()) {
                jgen.writeString(uri);
            }
            jgen.writeEndArray();
        }
    }
}

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

@Override
public SerializerResult primitiveCollection(final ServiceMetadata metadata, final EdmPrimitiveType type,
        final Property property, final PrimitiveSerializerOptions options) throws SerializerException {
    OutputStream outputStream = null;
    SerializerException cachedException = null;
    try {//www . j  av  a  2s.  c  o  m
        final ContextURL contextURL = checkContextURL(options == null ? null : options.getContextURL());
        CircleStreamBuffer buffer = new CircleStreamBuffer();
        outputStream = buffer.getOutputStream();
        JsonGenerator json = new JsonFactory().createGenerator(outputStream);
        json.writeStartObject();
        writeContextURL(contextURL, json);
        writeMetadataETag(metadata, json);
        if (isODataMetadataFull) {
            json.writeStringField(constants.getType(),
                    "#Collection(" + type.getFullQualifiedName().getName() + ")");
        }
        writeOperations(property.getOperations(), json);
        json.writeFieldName(Constants.VALUE);
        writePrimitiveCollection(type, property, options == null ? null : options.isNullable(),
                options == null ? null : options.getMaxLength(),
                options == null ? null : options.getPrecision(), options == null ? null : options.getScale(),
                options == null ? null : options.isUnicode(), json);
        json.writeEndObject();

        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;
    } finally {
        closeCircleStreamBufferOutput(outputStream, cachedException);
    }
}

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

@Override
public SerializerResult complexCollection(final ServiceMetadata metadata, final EdmComplexType type,
        final Property property, final ComplexSerializerOptions options) throws SerializerException {
    OutputStream outputStream = null;
    SerializerException cachedException = null;
    try {//from w w  w .  j a  v  a  2  s.  co m
        final ContextURL contextURL = checkContextURL(options == null ? null : options.getContextURL());
        CircleStreamBuffer buffer = new CircleStreamBuffer();
        outputStream = buffer.getOutputStream();
        JsonGenerator json = new JsonFactory().createGenerator(outputStream);
        json.writeStartObject();
        writeContextURL(contextURL, json);
        writeMetadataETag(metadata, json);
        if (isODataMetadataFull) {
            json.writeStringField(constants.getType(),
                    "#Collection(" + type.getFullQualifiedName().getFullQualifiedNameAsString() + ")");
        }
        writeOperations(property.getOperations(), json);
        json.writeFieldName(Constants.VALUE);
        Set<List<String>> selectedPaths = null;
        if (null != options && null != options.getSelect()) {
            final boolean all = ExpandSelectHelper.isAll(options.getSelect());
            selectedPaths = all || property.isPrimitive() ? null
                    : ExpandSelectHelper.getSelectedPaths(options.getSelect().getSelectItems());
        }
        Set<List<String>> expandPaths = null;
        if (null != options && null != options.getExpand()) {
            expandPaths = ExpandSelectHelper.getExpandedItemsPath(options.getExpand());
        }
        writeComplexCollection(metadata, type, property, selectedPaths, json, expandPaths, null,
                options == null ? null : options.getExpand());
        json.writeEndObject();

        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;
    } finally {
        closeCircleStreamBufferOutput(outputStream, cachedException);
    }
}

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

protected void writeNavigationProperties(final ServiceMetadata metadata, final EdmStructuredType type,
        final Linked linked, final ExpandOption expand, final Integer toDepth, final Set<String> ancestors,
        final String name, final JsonGenerator json) throws SerializerException, IOException, DecoderException {
    if (isODataMetadataFull) {
        for (final String propertyName : type.getNavigationPropertyNames()) {
            final Link navigationLink = linked.getNavigationLink(propertyName);
            if (navigationLink != null) {
                json.writeStringField(propertyName + constants.getNavigationLink(), navigationLink.getHref());
            }/*w w w.java2 s .  c o  m*/
            final Link associationLink = linked.getAssociationLink(propertyName);
            if (associationLink != null) {
                json.writeStringField(propertyName + constants.getAssociationLink(), associationLink.getHref());
            }
        }
    }
    if ((toDepth != null && toDepth > 1) || (toDepth == null && ExpandSelectHelper.hasExpand(expand))) {
        final ExpandItem expandAll = ExpandSelectHelper.getExpandAll(expand);
        for (final String propertyName : type.getNavigationPropertyNames()) {
            final ExpandItem innerOptions = ExpandSelectHelper.getExpandItemBasedOnType(expand.getExpandItems(),
                    propertyName, type, name);
            if (innerOptions != null || expandAll != null || toDepth != null) {
                Integer levels = null;
                final EdmNavigationProperty property = type.getNavigationProperty(propertyName);
                final Link navigationLink = linked.getNavigationLink(property.getName());
                ExpandOption childExpand = null;
                LevelsExpandOption levelsOption = null;
                if (innerOptions != null) {
                    levelsOption = innerOptions.getLevelsOption();
                    childExpand = levelsOption == null ? innerOptions.getExpandOption()
                            : new ExpandOptionImpl().addExpandItem(innerOptions);
                } else if (expandAll != null) {
                    levels = 1;
                    levelsOption = expandAll.getLevelsOption();
                    childExpand = new ExpandOptionImpl().addExpandItem(expandAll);
                }

                if (levelsOption != null) {
                    levels = levelsOption.isMax() ? Integer.MAX_VALUE : levelsOption.getValue();
                }
                if (toDepth != null) {
                    levels = toDepth - 1;
                    childExpand = expand;
                }

                writeExpandedNavigationProperty(metadata, property, navigationLink, childExpand, levels,
                        innerOptions == null ? null : innerOptions.getSelectOption(),
                        innerOptions == null ? null : innerOptions.getCountOption(),
                        innerOptions == null ? false : innerOptions.hasCountPath(),
                        innerOptions == null ? false : innerOptions.isRef(), ancestors, name, json);
            }
        }
    }
}

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

private void writePropertyType(final EdmProperty edmProperty, JsonGenerator json)
        throws SerializerException, IOException {
    if (!isODataMetadataFull) {
        return;//from  w  w w. j a v  a  2 s .c  om
    }
    String typeName = edmProperty.getName() + constants.getType();
    final EdmType type = edmProperty.getType();
    if (type.getKind() == EdmTypeKind.ENUM || type.getKind() == EdmTypeKind.DEFINITION) {
        if (edmProperty.isCollection()) {
            json.writeStringField(typeName,
                    "#Collection(" + type.getFullQualifiedName().getFullQualifiedNameAsString() + ")");
        } else {
            json.writeStringField(typeName, "#" + type.getFullQualifiedName().getFullQualifiedNameAsString());
        }
    } else if (edmProperty.isPrimitive()) {
        if (edmProperty.isCollection()) {
            json.writeStringField(typeName, "#Collection(" + type.getFullQualifiedName().getName() + ")");
        } else {
            // exclude the properties that can be heuristically determined
            if (type != EdmPrimitiveTypeFactory.getInstance(EdmPrimitiveTypeKind.Boolean)
                    && type != EdmPrimitiveTypeFactory.getInstance(EdmPrimitiveTypeKind.Double)
                    && type != EdmPrimitiveTypeFactory.getInstance(EdmPrimitiveTypeKind.String)) {
                json.writeStringField(typeName, "#" + type.getFullQualifiedName().getName());
            }
        }
    } else if (type.getKind() == EdmTypeKind.COMPLEX) {
        // non-collection case written in writeComplex method directly.
        if (edmProperty.isCollection()) {
            json.writeStringField(typeName,
                    "#Collection(" + type.getFullQualifiedName().getFullQualifiedNameAsString() + ")");
        }
    } else {
        throw new SerializerException("Property type not yet supported!",
                SerializerException.MessageKeys.UNSUPPORTED_PROPERTY_TYPE, edmProperty.getName());
    }
}