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.h2gis.drivers.geojson.GeoJsonWriteDriver.java

/**
 * Write the CRS in the geojson/* w w w  .  ja v a 2  s .  com*/
 *
 * @param jsonGenerator
 * @param authorityAndSRID
 * @throws IOException
 */
private void writeCRS(JsonGenerator jsonGenerator, String[] authorityAndSRID) throws IOException {
    if (authorityAndSRID[1] != null) {
        jsonGenerator.writeObjectFieldStart("crs");
        jsonGenerator.writeStringField("type", "name");
        jsonGenerator.writeObjectFieldStart("properties");
        StringBuilder sb = new StringBuilder("urn:ogc:def:crs:");
        sb.append(authorityAndSRID[0]).append("::").append(authorityAndSRID[1]);
        jsonGenerator.writeStringField("name", sb.toString());
        jsonGenerator.writeEndObject();
        jsonGenerator.writeEndObject();
    }
}

From source file:org.emfjson.jackson.streaming.StreamWriter.java

public void generate(final JsonGenerator generator, final EObject object) throws IOException {
    prepare(generator, object.eResource());

    final EClass eClass = object.eClass();
    final List<EAttribute> attributes = cache.getAttributes(eClass);
    final List<EReference> references = cache.getReferences(eClass);

    generator.writeStartObject();/*from   w ww .j  a v a2s  .  co  m*/

    if (options.serializeTypes) {
        generator.writeStringField(EJS_TYPE_KEYWORD, cache.getHref(null, eClass));
    }

    if (object.eResource() instanceof UuidResource) {
        String id = ((UuidResource) object.eResource()).getID(object);
        if (id != null) {
            generator.writeStringField(EJS_UUID_ANNOTATION, id);
        }
    } else {
        if (options.useId) {
            String id = object.eResource().getURIFragment(object);
            if (id != null) {
                generator.writeStringField(EJS_UUID_ANNOTATION, id);
            }
        }
    }

    for (final EAttribute attribute : attributes) {
        if (isCandidate(object, attribute)) {
            final String key = cache.getKey(attribute);
            final Object value = object.eGet(attribute);

            if (isFeatureMap(attribute)) {
                serializeFeatureMap(generator, attribute, object);
            } else {
                values.serialize(generator, key, attribute, value);
            }
        }
    }

    for (final EReference reference : references) {
        if (isCandidate(object, reference)) {
            final Object value = object.eGet(reference);
            final String key = cache.getKey(reference);

            if (isMapEntry(reference.getEReferenceType())) {
                serializeMapEntry(generator, key, reference, value);
            } else if (!reference.isContainment()) {
                referenceWriter.serialize(generator, key, reference, value);
            } else {
                serializeContainment(generator, key, reference, object, value);
            }
        }
    }

    generator.writeEndObject();
}

From source file:org.eclipse.winery.repository.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//w  w  w. j a va 2 s .c o m
 * 
 * @return A list of all ids of all instances of this component type. If the
 *         "name" attribute is required, that name is used as id <br />
 *         Format:
 *         <code>[({"namespace": "<namespace>", "id": "<id>"},)* ]</code>. A
 *         <code>name<code> field is added if the model allows an additional name attribute
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getListOfAllIds() {
    Class<? extends TOSCAComponentId> idClass = Utils.getComponentIdClassForComponentContainer(this.getClass());
    boolean supportsNameAttribute = Util.instanceSupportsNameAttribute(idClass);
    SortedSet<? extends TOSCAComponentId> allTOSCAcomponentIds = Repository.INSTANCE
            .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
        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);
            }
            jg.writeEndObject();
        }
        jg.writeEndArray();
        jg.close();
    } catch (Exception e) {
        AbstractComponentsResource.logger.error(e.getMessage(), e);
        return "[]";
    }
    return sw.toString();
}

From source file:org.emfjson.jackson.streaming.StreamWriter.java

private void serializeMapEntry(JsonGenerator generator, String key, EReference reference, Object value)
        throws IOException {

    generator.writeFieldName(key);/*from   www  .ja  va 2s .c o m*/
    generator.writeStartObject();

    if (reference.isMany()) {
        @SuppressWarnings("unchecked")
        Collection<Map.Entry<String, String>> entries = (Collection<Entry<String, String>>) value;

        for (Map.Entry<String, String> entry : entries) {
            generator.writeStringField(entry.getKey(), entry.getValue());
        }
    } else {
        @SuppressWarnings("unchecked")
        Map.Entry<String, String> entry = (Entry<String, String>) value;
        generator.writeStringField(entry.getKey(), entry.getValue());
    }
    generator.writeEndObject();
}

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();//from  w  w  w .j ava 2  s.c om

        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:com.joliciel.jochre.search.highlight.HighlightManagerImpl.java

@Override
public void findSnippets(Highlighter highlighter, Set<Integer> docIds, Set<String> fields, Writer out) {
    try {//from ww  w . ja  v a2s . co  m
        Map<Integer, Set<HighlightTerm>> termMap = highlighter.highlight(docIds, fields);
        Map<Integer, List<Snippet>> snippetMap = this.findSnippets(docIds, fields, termMap,
                this.getSnippetCount(), this.getSnippetSize());

        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("snippets");
            for (Snippet snippet : snippetMap.get(docId)) {
                snippet.toJson(jsonGen, df);
            }
            jsonGen.writeEndArray();

            if (includeText) {
                jsonGen.writeArrayFieldStart("snippetText");
                for (Snippet snippet : snippetMap.get(docId)) {
                    jsonGen.writeStartObject();
                    jsonGen.writeStringField("snippet", this.displaySnippet(docId, snippet));
                    jsonGen.writeEndObject();
                }
                jsonGen.writeEndArray();
            }

            if (includeGraphics) {
                jsonGen.writeArrayFieldStart("snippetGraphics");
                for (Snippet snippet : snippetMap.get(docId)) {
                    jsonGen.writeStartObject();
                    ImageSnippet imageSnippet = this.getImageSnippet(snippet);
                    jsonGen.writeNumberField("left", imageSnippet.getRectangle().getLeft());
                    jsonGen.writeNumberField("top", imageSnippet.getRectangle().getTop());
                    jsonGen.writeNumberField("right", imageSnippet.getRectangle().getRight());
                    jsonGen.writeNumberField("bottom", imageSnippet.getRectangle().getBottom());

                    jsonGen.writeArrayFieldStart("highlights");
                    for (Rectangle highlight : imageSnippet.getHighlights()) {
                        jsonGen.writeStartObject();
                        jsonGen.writeNumberField("left", highlight.getLeft());
                        jsonGen.writeNumberField("top", highlight.getTop());
                        jsonGen.writeNumberField("right", highlight.getRight());
                        jsonGen.writeNumberField("bottom", highlight.getBottom());
                        jsonGen.writeEndObject();
                    }
                    jsonGen.writeEndArray();
                    jsonGen.writeEndObject();
                }
                jsonGen.writeEndArray();
            }
            jsonGen.writeEndObject();
        } // next doc

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

From source file:org.elasticsearch.metrics.ElasticsearchReporter.java

/**
 * This index template is automatically applied to all indices which start with the index name
 * The index template simply configures the name not to be analyzed
 *//*from  w w w  . ja  v  a 2 s .c o m*/
private void checkForIndexTemplate() {
    try {
        HttpURLConnection connection = openConnection("/_template/metrics_template", "HEAD");
        if (connection == null) {
            LOGGER.error("Could not connect to any configured elasticsearch instances: {}",
                    Arrays.asList(hosts));
            return;
        }
        connection.disconnect();

        boolean isTemplateMissing = connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND;

        // nothing there, lets create it
        if (isTemplateMissing) {
            LOGGER.debug("No metrics template found in elasticsearch. Adding...");
            HttpURLConnection putTemplateConnection = openConnection("/_template/metrics_template", "PUT");
            if (putTemplateConnection == null) {
                LOGGER.error("Error adding metrics template to elasticsearch");
                return;
            }

            JsonGenerator json = new JsonFactory().createGenerator(putTemplateConnection.getOutputStream());
            json.writeStartObject();
            json.writeStringField("template", index + "*");
            json.writeObjectFieldStart("mappings");

            json.writeObjectFieldStart("_default_");
            json.writeObjectFieldStart("_all");
            json.writeBooleanField("enabled", false);
            json.writeEndObject();
            json.writeObjectFieldStart("properties");
            json.writeObjectFieldStart("name");
            json.writeObjectField("type", "string");
            json.writeObjectField("index", "not_analyzed");
            json.writeEndObject();
            json.writeEndObject();
            json.writeEndObject();

            json.writeEndObject();
            json.writeEndObject();
            json.flush();

            putTemplateConnection.disconnect();
            if (putTemplateConnection.getResponseCode() != 200) {
                LOGGER.error(
                        "Error adding metrics template to elasticsearch: {}/{}"
                                + putTemplateConnection.getResponseCode(),
                        putTemplateConnection.getResponseMessage());
            }
        }
        checkedForIndexTemplate = true;
    } catch (IOException e) {
        LOGGER.error("Error when checking/adding metrics template to elasticsearch", e);
    }
}

From source file:com.oneops.metrics.es.ElasticsearchReporter.java

/**
 * This index template is automatically applied to all indices which start with the index name
 * The index template simply configures the name not to be analyzed
 *///from   w  ww .j a va2 s  . c  o m
private void checkForIndexTemplate() {
    try {
        HttpURLConnection connection = openConnection("/_template/metrics_template", "HEAD");
        if (connection == null) {
            LOGGER.error("Could not connect to any configured elasticsearch instances: {}",
                    Arrays.asList(hosts));
            return;
        }
        connection.disconnect();

        boolean isTemplateMissing = connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND;

        // nothing there, lets create it
        if (isTemplateMissing) {
            LOGGER.debug("No metrics template found in elasticsearch. Adding...");
            HttpURLConnection putTemplateConnection = openConnection("/_template/metrics_template", "PUT");
            JsonGenerator json = new JsonFactory().createGenerator(putTemplateConnection.getOutputStream());
            json.writeStartObject();
            json.writeStringField("template", index + "*");
            json.writeObjectFieldStart("mappings");

            json.writeObjectFieldStart("_default_");
            json.writeObjectFieldStart("_all");
            json.writeBooleanField("enabled", false);
            json.writeEndObject();
            json.writeObjectFieldStart("properties");
            json.writeObjectFieldStart("name");
            json.writeObjectField("type", "string");
            json.writeObjectField("index", "not_analyzed");
            json.writeEndObject();
            json.writeEndObject();
            json.writeEndObject();

            json.writeEndObject();
            json.writeEndObject();
            json.flush();

            putTemplateConnection.disconnect();
            if (putTemplateConnection.getResponseCode() != 200) {
                LOGGER.error(
                        "Error adding metrics template to elasticsearch: {}/{}"
                                + putTemplateConnection.getResponseCode(),
                        putTemplateConnection.getResponseMessage());
            }
        }
        checkedForIndexTemplate = true;
    } catch (IOException e) {
        LOGGER.error("Error when checking/adding metrics template to elasticsearch", e);
    }
}

From source file:com.attribyte.essem.model.StoredGraph.java

/**
 * Generates JSON for this key./*from   ww  w. java  2  s  . c  o m*/
 * @param generator The generator.
 * @throws java.io.IOException on generation error.
 */
public void generateJSON(final JsonGenerator generator) throws IOException {
    generator.writeStartObject();
    generator.writeStringField("id", id);
    generator.writeStringField("uid", uid);
    generator.writeStringField("index", index);
    generator.writeStringField("application", key.application);
    generator.writeStringField("host", key.host);
    generator.writeStringField("instance", key.instance);
    generator.writeStringField("name", key.name);
    generator.writeStringField("field", key.field);
    generator.writeStringField("range", range);
    generator.writeNumberField("startTimestamp", startTimestamp);
    generator.writeNumberField("endTimestamp", endTimestamp);
    generator.writeStringField("downsampleFn", downsampleFn);
    if (rateUnit != null)
        generator.writeStringField("rateUnit", rateUnit);
    generator.writeStringField("title", title);
    generator.writeStringField("description", description);
    generator.writeStringField("xLabel", xLabel);
    generator.writeStringField("yLabel", yLabel);

    generator.writeArrayFieldStart("tag");
    for (String tag : tags) {
        generator.writeString(tag);
    }
    generator.writeEndArray();

    generator.writeStringField("created", DateTime.standardFormat(this.createTime));
    generator.writeEndObject();
}