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:org.n52.tamis.core.json.serialize.processes.execute.ExecuteInputSerializer.java

private void writeAsReference(JsonGenerator jsonGenerator, ExecuteInput input) throws IOException {
    /*/* w w  w.j  a  va  2 s .c  om*/
     *  expected structure looks like:
    * 
        * "Reference": { "_href":
        * "http://fluggs.wupperverband.de/sos2/service?service=SOS&request=GetObservation&version=2.0.0&offering=Zeitreihen_2m_Tiefe&observedProperty=Grundwasserstand&responseFormat=http%3A//www.opengis.net/om/2.0",
        * "_mimeType": "application/om+xml; version=2.0", "_schema":
        * "http://schemas.opengis.net/om/2.0/observation.xsd" }, "_id":
        * "gw1" }
        * 
     */

    logger.info("Input \"{}\" is serialized as WPS \"Reference\".", input);

    jsonGenerator.writeStartObject();

    jsonGenerator.writeObjectFieldStart("Reference");

    // jsonGenerator.writeStartObject();

    jsonGenerator.writeStringField("_href", input.getValue());

    /*
     * parameters "_mimeType" and "_schema" can be set to SOS values, if
     * the link is a SOS request!
     * 
     * Else we do not know anything about the mimeType. Thus we cannot
     * set it.
     */

    jsonGenerator.writeEndObject();

    jsonGenerator.writeStringField("_id", input.getId());

    jsonGenerator.writeEndObject();
}

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

private void writeExchange(AbstractExchange exc, JsonGenerator gen)
        throws IOException, JsonGenerationException, SQLException {
    gen.writeStartObject();/*from  w w w  . j  av a2 s  .  co  m*/
    gen.writeNumberField("id", exc.getId());
    if (exc.getResponse() != null) {
        gen.writeNumberField("statusCode", exc.getResponse().getStatusCode());
        if (exc.getResponseContentLength() != -1) {
            gen.writeNumberField("respContentLength", exc.getResponseContentLength());
        } else {
            gen.writeNullField("respContentLength");
        }
    } else {
        gen.writeNullField("statusCode");
        gen.writeNullField("respContentLength");
    }
    gen.writeStringField("time", ExchangesUtil.getTime(exc));
    gen.writeStringField("proxy", exc.getRule().toString());
    gen.writeNumberField("listenPort", exc.getRule().getKey().getPort());
    gen.writeStringField("method", exc.getRequest().getMethod());
    gen.writeStringField("path", exc.getRequest().getUri());
    gen.writeStringField("client", exc.getRemoteAddr());
    gen.writeStringField("server", exc.getServer());
    gen.writeNumberField("serverPort", getServerPort(exc));
    gen.writeStringField("reqContentType", exc.getRequestContentType());
    if (exc.getRequestContentLength() != -1) {
        gen.writeNumberField("reqContentLength", exc.getRequestContentLength());
    } else {
        gen.writeNullField("reqContentLength");
    }

    gen.writeStringField("respContentType", exc.getResponseContentType());
    gen.writeStringField("respContentLength", exc.getResponseContentType());

    gen.writeNumberField("duration", exc.getTimeResReceived() - exc.getTimeReqSent());
    gen.writeStringField("msgFilePath", JDBCUtil.getFilePath(exc));
    gen.writeEndObject();
}

From source file:net.opentsdb.tsd.HttpSampleSerializer.java

/**
 * Format the results from a timeseries data query
 * @param data_query The TSQuery object used to fetch the results
 * @param results The data fetched from storage
 * @param globals An optional list of global annotation objects
 * @return A ChannelBuffer object to pass on to the caller
 *///from  w  ww  . jav  a2 s  .  c  o  m
public ChannelBuffer formatQueryV1(final TSQuery data_query, final List<DataPoints[]> results,
        final List<Annotation> globals) {

    final boolean as_arrays = this.query.hasQueryStringParam("arrays");
    final String jsonp = this.query.getQueryStringParam("jsonp");

    // todo - this should be streamed at some point since it could be HUGE
    final ChannelBuffer response = ChannelBuffers.dynamicBuffer();
    final OutputStream output = new ChannelBufferOutputStream(response);
    try {
        // don't forget jsonp
        if (jsonp != null && !jsonp.isEmpty()) {
            output.write((jsonp + "(").getBytes(query.getCharset()));
        }
        JsonGenerator json = JSON.getFactory().createGenerator(output);
        json.writeStartArray();

        for (DataPoints[] separate_dps : results) {
            for (DataPoints dps : separate_dps) {
                json.writeStartObject();

                json.writeStringField("metric", dps.metricName());

                json.writeFieldName("tags");
                json.writeStartObject();
                if (dps.getTags() != null) {
                    for (Map.Entry<String, String> tag : dps.getTags().entrySet()) {
                        json.writeStringField(tag.getKey(), tag.getValue());
                    }
                }
                json.writeEndObject();

                json.writeFieldName("aggregateTags");
                json.writeStartArray();
                if (dps.getAggregatedTags() != null) {
                    for (String atag : dps.getAggregatedTags()) {
                        json.writeString(atag);
                    }
                }
                json.writeEndArray();

                if (data_query.getShowTSUIDs()) {
                    json.writeFieldName("tsuids");
                    json.writeStartArray();
                    final List<String> tsuids = dps.getTSUIDs();
                    Collections.sort(tsuids);
                    for (String tsuid : tsuids) {
                        json.writeString(tsuid);
                    }
                    json.writeEndArray();
                }

                if (!data_query.getNoAnnotations()) {
                    final List<Annotation> annotations = dps.getAnnotations();
                    if (annotations != null) {
                        Collections.sort(annotations);
                        json.writeArrayFieldStart("annotations");
                        for (Annotation note : annotations) {
                            json.writeObject(note);
                        }
                        json.writeEndArray();
                    }

                    if (globals != null && !globals.isEmpty()) {
                        Collections.sort(globals);
                        json.writeArrayFieldStart("globalAnnotations");
                        for (Annotation note : globals) {
                            json.writeObject(note);
                        }
                        json.writeEndArray();
                    }
                }

                // now the fun stuff, dump the data
                json.writeFieldName("dps");

                // default is to write a map, otherwise write arrays
                if (as_arrays) {
                    json.writeStartArray();
                    for (final DataPoint dp : dps) {
                        if (dp.timestamp() < data_query.startTime() || dp.timestamp() > data_query.endTime()) {
                            continue;
                        }
                        final long timestamp = data_query.getMsResolution() ? dp.timestamp()
                                : dp.timestamp() / 1000;
                        json.writeStartArray();
                        json.writeNumber(timestamp);
                        json.writeNumber(dp.isInteger() ? dp.longValue() : dp.doubleValue());
                        json.writeEndArray();
                    }
                    json.writeEndArray();
                } else {
                    json.writeStartObject();
                    for (final DataPoint dp : dps) {
                        if (dp.timestamp() < (data_query.startTime())
                                || dp.timestamp() > (data_query.endTime())) {
                            continue;
                        }
                        final long timestamp = data_query.getMsResolution() ? dp.timestamp()
                                : dp.timestamp() / 1000;
                        json.writeNumberField(Long.toString(timestamp),
                                dp.isInteger() ? dp.longValue() : dp.doubleValue());
                    }
                    json.writeEndObject();
                }

                // close the results for this particular query
                json.writeEndObject();
            }
        }

        // close
        json.writeEndArray();
        json.close();

        if (jsonp != null && !jsonp.isEmpty()) {
            output.write(")".getBytes());
        }
        return response;
    } catch (IOException e) {
        LOG.error("Unexpected exception", e);
        throw new RuntimeException(e);
    }
}

From source file:com.github.hateoas.forms.spring.halforms.ValueSuggestSerializer.java

@Override
public void serialize(final ValueSuggest<?> value, final JsonGenerator gen, final SerializerProvider provider)
        throws IOException, JsonProcessingException {

    Iterator<?> iterator = value.getValues().iterator();
    if (!iterator.hasNext()) {
        return;/*from   ww w.  j a v a  2 s  . co  m*/
    }

    if (value.getType() == SuggestType.INTERNAL) {
        directSerializer.serialize(value, gen, provider);
    } else {
        gen.writeStartObject();

        Map<String, Object> curiedMap = mapper.map(value.getValues());

        if (value.getType() == SuggestType.EXTERNAL) {
            String embeddedRel;
            if (!curiedMap.isEmpty()) {
                embeddedRel = curiedMap.keySet().iterator().next();
            } else {
                embeddedRel = relProvider.getCollectionResourceRelFor(iterator.next().getClass());
            }
            gen.writeStringField("embedded", embeddedRel);
        } else {
            gen.writeStringField("href", (String) value.getValues().iterator().next());
        }

        if (value.getTextField() != null) {
            gen.writeStringField("prompt-field", value.getTextField());
        }
        if (value.getValueField() != null) {
            gen.writeStringField("value-field", value.getValueField());
        }
        gen.writeEndObject();
    }

}

From source file:com.microsoft.azure.storage.core.EncryptionData.java

public void serialize(JsonGenerator generator) throws IOException {

    // write wrapped content key
    generator.writeObjectFieldStart(Constants.EncryptionConstants.WRAPPED_CONTENT_KEY);
    this.getWrappedContentKey().serialize(generator);
    generator.writeEndObject();//from   ww w. j a  v a 2s .c  o  m

    // write encryption agent
    generator.writeObjectFieldStart(Constants.EncryptionConstants.ENCRYPTION_AGENT);
    this.getEncryptionAgent().serialize(generator);
    generator.writeEndObject();

    // write content encryption IV
    generator.writeBinaryField(Constants.EncryptionConstants.CONTENT_ENCRYPTION_IV,
            this.getContentEncryptionIV());

    // write key wrapping metadata
    generator.writeObjectFieldStart(Constants.EncryptionConstants.KEY_WRAPPING_METADATA);
    for (String key : this.keyWrappingMetadata.keySet()) {
        generator.writeStringField(key, this.keyWrappingMetadata.get(key));
    }
    generator.writeEndObject();

}

From source file:com.microsoft.windowsazure.storage.table.TableParser.java

/**
 * Reserved for internal use. Writes an entity to the specified <code>JsonGenerator</code> as an JSON resource
 * // w  w w  .ja v  a 2  s .  c o  m
 * @param generator
 *            The <code>JsonGenerator</code> to write the entity to.
 * @param format
 *            The {@link TablePayloadFormat} to use for parsing.
 * @param entity
 *            The instance implementing {@link TableEntity} to write to the output stream.
 * @param isTableEntry
 *            A flag indicating the entity is a reference to a table at the top level of the storage service when
 *            <code>true<code> and a reference to an entity within a table when <code>false</code>.
 * @param opContext
 *            An {@link OperationContext} object used to track the execution of the operation.
 * 
 * @throws StorageException
 *             if a Storage service error occurs.
 * @throws IOException
 *             if an error occurs while accessing the stream.
 */
private static void writeJsonEntity(final JsonGenerator generator, TablePayloadFormat format,
        final TableEntity entity, final boolean isTableEntry, final OperationContext opContext)
        throws StorageException, IOException {

    HashMap<String, EntityProperty> properties = entity.writeEntity(opContext);
    if (properties == null) {
        properties = new HashMap<String, EntityProperty>();
    }

    // start object
    generator.writeStartObject();

    if (!isTableEntry) {
        Utility.assertNotNull(TableConstants.PARTITION_KEY, entity.getPartitionKey());
        Utility.assertNotNull(TableConstants.ROW_KEY, entity.getRowKey());
        Utility.assertNotNull(TableConstants.TIMESTAMP, entity.getTimestamp());

        // PartitionKey
        generator.writeStringField(TableConstants.PARTITION_KEY, entity.getPartitionKey());

        // RowKey
        generator.writeStringField(TableConstants.ROW_KEY, entity.getRowKey());

        // Timestamp
        generator.writeStringField(TableConstants.TIMESTAMP, Utility
                .getTimeByZoneAndFormat(entity.getTimestamp(), Utility.UTC_ZONE, Utility.ISO8061_LONG_PATTERN));
    }

    for (final Entry<String, EntityProperty> ent : properties.entrySet()) {
        if (ent.getKey().equals(TableConstants.PARTITION_KEY) || ent.getKey().equals(TableConstants.ROW_KEY)
                || ent.getKey().equals(TableConstants.TIMESTAMP) || ent.getKey().equals("Etag")) {
            continue;
        }

        EntityProperty currProp = ent.getValue();
        if (currProp.getEdmType().mustAnnotateType()) {
            final String edmTypeString = currProp.getEdmType().toString();

            // property type
            generator.writeStringField(ent.getKey() + ODataConstants.ODATA_TYPE_SUFFIX, edmTypeString);

            // property key and value
            generator.writeStringField(ent.getKey(), ent.getValue().getValueAsString());
        } else if (currProp.getEdmType() == EdmType.DOUBLE && currProp.getIsNull() == false) {
            final String edmTypeString = currProp.getEdmType().toString();
            final Double value = currProp.getValueAsDouble();

            // property type, if needed
            if (value.equals(Double.POSITIVE_INFINITY) || value.equals(Double.NEGATIVE_INFINITY)
                    || value.equals(Double.NaN)) {
                generator.writeStringField(ent.getKey() + ODataConstants.ODATA_TYPE_SUFFIX, edmTypeString);

                // property key and value
                generator.writeStringField(ent.getKey(), ent.getValue().getValueAsString());
            } else {
                writeJsonProperty(generator, ent);
            }

        } else {
            writeJsonProperty(generator, ent);
        }
    }

    // end object
    generator.writeEndObject();
}

From source file:de.escalon.hypermedia.hydra.serialize.JacksonHydraSerializer.java

private void serializeType(Object bean, JsonGenerator jgen, SerializerProvider provider) throws IOException {
    // adds @type attribute, reflecting the simple name of the class or the exposed annotation on the class.
    final Expose classExpose = getAnnotation(bean.getClass(), Expose.class);
    // TODO allow to search up the hierarchy for ResourceSupport mixins and cache find result?
    final Class<?> mixin = provider.getConfig().findMixInClassFor(bean.getClass());
    final Expose mixinExpose = getAnnotation(mixin, Expose.class);
    final String val;
    if (mixinExpose != null) {
        val = mixinExpose.value(); // mixin wins over class
    } else if (classExpose != null) {
        val = classExpose.value(); // expose is better than Java type
    } else {/*from  w w  w  . j a  v a2 s .  co  m*/
        val = bean.getClass().getSimpleName();
    }

    jgen.writeStringField(AT_TYPE, val);
}

From source file:de.escalon.hypermedia.spring.hydra.LinkListSerializer.java

private void writeSupportedProperty(JsonGenerator jgen, String currentVocab,
        ActionInputParameter actionInputParameter, String propertyName,
        @SuppressWarnings("unused") Object[] possiblePropertyValues) throws IOException {

    jgen.writeStartObject();//from w  w  w  .  j a  v a 2  s .c  o  m

    if (actionInputParameter.hasValue() || actionInputParameter.hasInputConstraints()) {
        // jgen.writeArrayFieldStart("@type");
        // jgen.writeString("hydra:SupportedProperty");

        jgen.writeStringField(JsonLdKeywords.AT_TYPE, getPropertyOrClassNameInVocab(currentVocab,
                "PropertyValueSpecification", LdContextFactory.HTTP_SCHEMA_ORG, "schema:"));

        //jgen.writeEndArray();
    }
    jgen.writeStringField("hydra:property", propertyName);

    writePossiblePropertyValues(jgen, currentVocab, actionInputParameter, possiblePropertyValues);

    jgen.writeEndObject();
}