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

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

Introduction

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

Prototype

public abstract void writeFieldName(SerializableString name) throws IOException, JsonGenerationException;

Source Link

Document

Method similar to #writeFieldName(String) , main difference being that it may perform better as some of processing (such as quoting of certain characters, or encoding into external encoding if supported by generator) can be done just once and reused for later calls.

Usage

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

@Override
public SerializerResult primitive(final ServiceMetadata metadata, final EdmPrimitiveType type,
        final Property property, final PrimitiveSerializerOptions options) throws SerializerException {
    OutputStream outputStream = null;
    SerializerException cachedException = null;
    try {//from  w  w  w  .j a v  a  2 s .com
        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);
        writeOperations(property.getOperations(), json);
        if (property.isNull()) {
            throw new SerializerException("Property value can not be null.",
                    SerializerException.MessageKeys.NULL_INPUT);
        } else {
            json.writeFieldName(Constants.VALUE);
            writePrimitive(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;
    } catch (final EdmPrimitiveTypeException e) {
        cachedException = new SerializerException("Wrong value for property!", e,
                SerializerException.MessageKeys.WRONG_PROPERTY_VALUE, property.getName(),
                property.getValue().toString());
        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 ww  w .j  a va 2  s  . 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().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

public void entityCollectionIntoStream(final ServiceMetadata metadata, final EdmEntityType entityType,
        final EntityIterator entitySet, final EntityCollectionSerializerOptions options,
        final OutputStream outputStream) throws SerializerException {

    SerializerException cachedException;
    boolean pagination = false;
    try {/*from w w  w  . j a  v  a  2  s.  c  o m*/
        JsonGenerator json = new JsonFactory().createGenerator(outputStream);
        json.writeStartObject();

        final ContextURL contextURL = checkContextURL(options == null ? null : options.getContextURL());
        writeContextURL(contextURL, json);

        writeMetadataETag(metadata, json);

        if (options != null && options.getCount() != null && options.getCount().getValue()) {
            writeInlineCount("", entitySet.getCount(), json);
        }
        json.writeFieldName(Constants.VALUE);
        String name = contextURL == null ? null : contextURL.getEntitySetOrSingletonOrType();
        if (options == null) {
            writeEntitySet(metadata, entityType, entitySet, null, null, null, false, null, name, json);
        } else {
            writeEntitySet(metadata, entityType, entitySet, options.getExpand(), null, options.getSelect(),
                    options.getWriteOnlyReferences(), null, name, json);
        }
        // next link support for streaming results
        writeNextLink(entitySet, json, pagination);

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

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

@Override
public SerializerResult entityCollection(final ServiceMetadata metadata, final EdmEntityType entityType,
        final AbstractEntityCollection entitySet, final EntityCollectionSerializerOptions options)
        throws SerializerException {
    OutputStream outputStream = null;
    SerializerException cachedException = null;
    boolean pagination = false;
    try {/*www .  ja va  2  s.  c  o m*/
        CircleStreamBuffer buffer = new CircleStreamBuffer();
        outputStream = buffer.getOutputStream();
        JsonGenerator json = new JsonFactory().createGenerator(outputStream);
        json.writeStartObject();

        final ContextURL contextURL = checkContextURL(options == null ? null : options.getContextURL());
        String name = contextURL == null ? null : contextURL.getEntitySetOrSingletonOrType();
        writeContextURL(contextURL, json);

        writeMetadataETag(metadata, json);

        if (options != null && options.getCount() != null && options.getCount().getValue()) {
            writeInlineCount("", entitySet.getCount(), json);
        }
        writeOperations(entitySet.getOperations(), json);
        json.writeFieldName(Constants.VALUE);
        if (options == null) {
            writeEntitySet(metadata, entityType, entitySet, null, null, null, false, null, name, json);
        } else {
            writeEntitySet(metadata, entityType, entitySet, options.getExpand(), null, options.getSelect(),
                    options.getWriteOnlyReferences(), null, name, json);
        }
        writeNextLink(entitySet, json, pagination);
        writeDeltaLink(entitySet, json, pagination);

        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:org.apache.olingo.server.core.serializer.json.ODataJsonSerializer.java

/** Writes a geospatial value following the GeoJSON specification defined in RFC 7946. */
protected void writeGeoValue(final String name, final EdmPrimitiveType type, final Geospatial geoValue,
        final Boolean isNullable, JsonGenerator json, SRID parentSrid)
        throws EdmPrimitiveTypeException, IOException, SerializerException {
    if (geoValue == null) {
        if (isNullable == null || isNullable) {
            json.writeNull();/*  ww  w. j a  v a 2s  . c o  m*/
        } else {
            throw new EdmPrimitiveTypeException("The literal 'null' is not allowed.");
        }
    } else {
        if (!type.getDefaultType().isAssignableFrom(geoValue.getClass())) {
            throw new EdmPrimitiveTypeException("The value type " + geoValue.getClass() + " is not supported.");
        }
        json.writeStartObject();
        json.writeStringField(Constants.ATTR_TYPE, geoValueTypeToJsonName.get(geoValue.getGeoType()));
        json.writeFieldName(
                geoValue.getGeoType() == Geospatial.Type.GEOSPATIALCOLLECTION ? Constants.JSON_GEOMETRIES
                        : Constants.JSON_COORDINATES);
        json.writeStartArray();
        switch (geoValue.getGeoType()) {
        case POINT:
            writeGeoPoint(json, (Point) geoValue);
            break;
        case MULTIPOINT:
            writeGeoPoints(json, (MultiPoint) geoValue);
            break;
        case LINESTRING:
            writeGeoPoints(json, (LineString) geoValue);
            break;
        case MULTILINESTRING:
            for (final LineString lineString : (MultiLineString) geoValue) {
                json.writeStartArray();
                writeGeoPoints(json, lineString);
                json.writeEndArray();
            }
            break;
        case POLYGON:
            writeGeoPolygon(json, (Polygon) geoValue);
            break;
        case MULTIPOLYGON:
            for (final Polygon polygon : (MultiPolygon) geoValue) {
                json.writeStartArray();
                writeGeoPolygon(json, polygon);
                json.writeEndArray();
            }
            break;
        case GEOSPATIALCOLLECTION:
            for (final Geospatial element : (GeospatialCollection) geoValue) {
                writeGeoValue(name, EdmPrimitiveTypeFactory.getInstance(element.getEdmPrimitiveTypeKind()),
                        element, isNullable, json, geoValue.getSrid());
            }
            break;
        }
        json.writeEndArray();

        if (geoValue.getSrid() != null && geoValue.getSrid().isNotDefault()
                && (parentSrid == null || !parentSrid.equals(geoValue.getSrid()))) {
            srid(json, geoValue.getSrid());
        }
        json.writeEndObject();
    }
}

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

protected void writeExpandedNavigationProperty(final ServiceMetadata metadata,
        final EdmNavigationProperty property, final Link navigationLink, final ExpandOption innerExpand,
        Integer toDepth, final SelectOption innerSelect, final CountOption innerCount,
        final boolean writeOnlyCount, final boolean writeOnlyRef, final Set<String> ancestors, String name,
        final JsonGenerator json) throws IOException, SerializerException, DecoderException {

    if (property.isCollection()) {
        if (writeOnlyCount) {
            if (navigationLink == null || navigationLink.getInlineEntitySet() == null) {
                writeInlineCount(property.getName(), 0, json);
            } else {
                writeInlineCount(property.getName(), navigationLink.getInlineEntitySet().getCount(), json);
            }/*from   ww w . java  2s  .  c  o m*/
        } else {
            if (navigationLink == null || navigationLink.getInlineEntitySet() == null) {
                if (innerCount != null && innerCount.getValue()) {
                    writeInlineCount(property.getName(), 0, json);
                }
                json.writeFieldName(property.getName());
                json.writeStartArray();
                json.writeEndArray();
            } else {
                if (innerCount != null && innerCount.getValue()) {
                    writeInlineCount(property.getName(), navigationLink.getInlineEntitySet().getCount(), json);
                }
                json.writeFieldName(property.getName());
                writeEntitySet(metadata, property.getType(), navigationLink.getInlineEntitySet(), innerExpand,
                        toDepth, innerSelect, writeOnlyRef, ancestors, name, json);
            }
        }
    } else {
        json.writeFieldName(property.getName());
        if (navigationLink == null || navigationLink.getInlineEntity() == null) {
            json.writeNull();
        } else {
            writeEntity(metadata, property.getType(), navigationLink.getInlineEntity(), null, innerExpand,
                    toDepth, innerSelect, writeOnlyRef, ancestors, name, json);
        }
    }
}

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

protected void writeAppFields(App app, JsonGenerator gen) throws IOException {
    if (app.hasId()) {
        gen.writeStringField("id", app.getId());
    }/* w  w  w.  j  a  v a  2s .  c o  m*/
    if (app.hasName()) {
        gen.writeStringField("name", app.getName());
    }
    if (app.hasBundle()) {
        gen.writeStringField("bundle", app.getBundle());
    }
    if (app.hasDomain()) {
        gen.writeStringField("domain", app.getDomain());
    }
    if (app.hasStoreurl()) {
        gen.writeStringField("storeurl", app.getStoreurl());
    }
    writeContentCategories("cat", app.getCatList(), gen);
    writeContentCategories("sectioncat", app.getSectioncatList(), gen);
    writeContentCategories("pagecat", app.getPagecatList(), gen);
    if (app.hasVer()) {
        gen.writeStringField("ver", app.getVer());
    }
    if (app.hasPrivacypolicy()) {
        writeIntBoolField("privacypolicy", app.getPrivacypolicy(), gen);
    }
    if (app.hasPaid()) {
        writeIntBoolField("paid", app.getPaid(), gen);
    }
    if (app.hasPublisher()) {
        gen.writeFieldName("publisher");
        writePublisher(app.getPublisher(), gen);
    }
    if (app.hasContent()) {
        gen.writeFieldName("content");
        writeContent(app.getContent(), gen);
    }
    if (app.hasKeywords()) {
        gen.writeStringField("keywords", app.getKeywords());
    }
}

From source file:org.eclipse.winery.repository.rest.resources.AbstractComponentsResource.java

/**
 * Used by org.eclipse.winery.repository.repository.client and by the artifactcreationdialog.tag. Especially the
 * "name" field is used there at the UI/*  ww  w .  jav a 2s.  c  o  m*/
 *
 * @param grouped if given, the JSON output is grouped by namespace
 * @return A list of all ids of all instances of this component type. <br /> Format: <code>[({"namespace":
 * "[namespace]", "id": "[id]"},)* ]</code>. <br /><br /> If grouped is set, the list will be grouped by namespace.
 * <br /> <code>[{"id": "[namsepace encoded]", "test": "[namespace decoded]", "children":[{"id": "[qName]", "text":
 * "[id]"}]}]</code>
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getListOfAllIds(@QueryParam("grouped") String grouped) {
    Class<? extends TOSCAComponentId> idClass = RestUtils
            .getComponentIdClassForComponentContainer(this.getClass());
    boolean supportsNameAttribute = Util.instanceSupportsNameAttribute(idClass);
    SortedSet<? extends TOSCAComponentId> allTOSCAcomponentIds = RepositoryFactory.getRepository()
            .getAllTOSCAComponentIds(idClass);
    JsonFactory jsonFactory = new JsonFactory();
    StringWriter sw = new StringWriter();
    try {
        JsonGenerator jg = jsonFactory.createGenerator(sw);
        // We produce org.eclipse.winery.repository.client.WineryRepositoryClient.NamespaceAndId by hand here
        // Refactoring could move this class to common and fill it here
        if (grouped == null) {
            jg.writeStartArray();
            for (TOSCAComponentId id : allTOSCAcomponentIds) {
                jg.writeStartObject();
                jg.writeStringField("namespace", id.getNamespace().getDecoded());
                jg.writeStringField("id", id.getXmlId().getDecoded());
                if (supportsNameAttribute) {
                    AbstractComponentInstanceResource componentInstaceResource = AbstractComponentsResource
                            .getComponentInstaceResource(id);
                    String name = ((IHasName) componentInstaceResource).getName();
                    jg.writeStringField("name", name);
                } else {
                    // used for winery-qNameSelector to avoid an if there
                    jg.writeStringField("name", id.getXmlId().getDecoded());
                }
                jg.writeStringField("qName", id.getQName().toString());
                jg.writeEndObject();
            }
            jg.writeEndArray();
        } else {
            jg.writeStartArray();
            Map<Namespace, ? extends List<? extends TOSCAComponentId>> groupedIds = allTOSCAcomponentIds
                    .stream().collect(Collectors.groupingBy(id -> id.getNamespace()));
            groupedIds.keySet().stream().sorted().forEach(namespace -> {
                try {
                    jg.writeStartObject();
                    jg.writeStringField("id", namespace.getEncoded());
                    jg.writeStringField("text", namespace.getDecoded());
                    jg.writeFieldName("children");
                    jg.writeStartArray();
                    groupedIds.get(namespace).forEach(id -> {
                        try {
                            jg.writeStartObject();
                            String text;
                            if (supportsNameAttribute) {
                                AbstractComponentInstanceResource componentInstaceResource = AbstractComponentsResource
                                        .getComponentInstaceResource(id);
                                text = ((IHasName) componentInstaceResource).getName();
                            } else {
                                text = id.getXmlId().getDecoded();
                            }
                            jg.writeStringField("id", id.getQName().toString());
                            jg.writeStringField("text", text);
                            jg.writeEndObject();
                        } catch (IOException e) {
                            AbstractComponentsResource.LOGGER.error("Could not create JSON", e);
                        }
                    });
                    jg.writeEndArray();
                    jg.writeEndObject();
                } catch (IOException e) {
                    AbstractComponentsResource.LOGGER.error("Could not create JSON", e);
                }
            });
            jg.writeEndArray();
        }
        jg.close();
    } catch (Exception e) {
        AbstractComponentsResource.LOGGER.error(e.getMessage(), e);
        return "[]";
    }
    return sw.toString();
}

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

protected void writeSiteFields(Site site, JsonGenerator gen) throws IOException {
    if (site.hasId()) {
        gen.writeStringField("id", site.getId());
    }//from   ww  w .  ja v a2s  .c om
    if (site.hasName()) {
        gen.writeStringField("name", site.getName());
    }
    if (site.hasDomain()) {
        gen.writeStringField("domain", site.getDomain());
    }
    writeContentCategories("cat", site.getCatList(), gen);
    writeContentCategories("sectioncat", site.getSectioncatList(), gen);
    writeContentCategories("pagecat", site.getPagecatList(), gen);
    if (site.hasPage()) {
        gen.writeStringField("page", site.getPage());
    }
    if (site.hasRef()) {
        gen.writeStringField("ref", site.getRef());
    }
    if (site.hasSearch()) {
        gen.writeStringField("search", site.getSearch());
    }
    if (site.hasMobile()) {
        writeIntBoolField("mobile", site.getMobile(), gen);
    }
    if (site.hasPrivacypolicy()) {
        writeIntBoolField("privacypolicy", site.getPrivacypolicy(), gen);
    }
    if (site.hasPublisher()) {
        gen.writeFieldName("publisher");
        writePublisher(site.getPublisher(), gen);
    }
    if (site.hasContent()) {
        gen.writeFieldName("content");
        writeContent(site.getContent(), gen);
    }
    if (site.hasKeywords()) {
        gen.writeStringField("keywords", site.getKeywords());
    }
}