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.elasticsearch.client.sniff.ElasticsearchNodesSnifferTests.java

private static SniffResponse buildSniffResponse(ElasticsearchNodesSniffer.Scheme scheme) throws IOException {
    int numNodes = RandomNumbers.randomIntBetween(getRandom(), 1, 5);
    List<Node> nodes = new ArrayList<>(numNodes);
    JsonFactory jsonFactory = new JsonFactory();
    StringWriter writer = new StringWriter();
    JsonGenerator generator = jsonFactory.createGenerator(writer);
    generator.writeStartObject();/*from  w w  w  .  ja  va 2s  . c  o m*/
    if (getRandom().nextBoolean()) {
        generator.writeStringField("cluster_name", "elasticsearch");
    }
    if (getRandom().nextBoolean()) {
        generator.writeObjectFieldStart("bogus_object");
        generator.writeEndObject();
    }
    generator.writeObjectFieldStart("nodes");
    for (int i = 0; i < numNodes; i++) {
        String nodeId = RandomStrings.randomAsciiOfLengthBetween(getRandom(), 5, 10);
        String host = "host" + i;
        int port = RandomNumbers.randomIntBetween(getRandom(), 9200, 9299);
        HttpHost publishHost = new HttpHost(host, port, scheme.toString());
        Set<HttpHost> boundHosts = new HashSet<>();
        boundHosts.add(publishHost);

        if (randomBoolean()) {
            int bound = between(1, 5);
            for (int b = 0; b < bound; b++) {
                boundHosts.add(new HttpHost(host + b, port, scheme.toString()));
            }
        }

        int numAttributes = between(0, 5);
        Map<String, List<String>> attributes = new HashMap<>(numAttributes);
        for (int j = 0; j < numAttributes; j++) {
            int numValues = frequently() ? 1 : between(2, 5);
            List<String> values = new ArrayList<>();
            for (int v = 0; v < numValues; v++) {
                values.add(j + "value" + v);
            }
            attributes.put("attr" + j, values);
        }

        Node node = new Node(publishHost, boundHosts, randomAsciiAlphanumOfLength(5),
                randomAsciiAlphanumOfLength(5),
                new Node.Roles(randomBoolean(), randomBoolean(), randomBoolean()), attributes);

        generator.writeObjectFieldStart(nodeId);
        if (getRandom().nextBoolean()) {
            generator.writeObjectFieldStart("bogus_object");
            generator.writeEndObject();
        }
        if (getRandom().nextBoolean()) {
            generator.writeArrayFieldStart("bogus_array");
            generator.writeStartObject();
            generator.writeEndObject();
            generator.writeEndArray();
        }
        boolean isHttpEnabled = rarely() == false;
        if (isHttpEnabled) {
            nodes.add(node);
            generator.writeObjectFieldStart("http");
            generator.writeArrayFieldStart("bound_address");
            for (HttpHost bound : boundHosts) {
                generator.writeString(bound.toHostString());
            }
            generator.writeEndArray();
            if (getRandom().nextBoolean()) {
                generator.writeObjectFieldStart("bogus_object");
                generator.writeEndObject();
            }
            generator.writeStringField("publish_address", publishHost.toHostString());
            if (getRandom().nextBoolean()) {
                generator.writeNumberField("max_content_length_in_bytes", 104857600);
            }
            generator.writeEndObject();
        }

        List<String> roles = Arrays.asList(new String[] { "master", "data", "ingest" });
        Collections.shuffle(roles, getRandom());
        generator.writeArrayFieldStart("roles");
        for (String role : roles) {
            if ("master".equals(role) && node.getRoles().isMasterEligible()) {
                generator.writeString("master");
            }
            if ("data".equals(role) && node.getRoles().isData()) {
                generator.writeString("data");
            }
            if ("ingest".equals(role) && node.getRoles().isIngest()) {
                generator.writeString("ingest");
            }
        }
        generator.writeEndArray();

        generator.writeFieldName("version");
        generator.writeString(node.getVersion());
        generator.writeFieldName("name");
        generator.writeString(node.getName());

        if (numAttributes > 0) {
            generator.writeObjectFieldStart("attributes");
            for (Map.Entry<String, List<String>> entry : attributes.entrySet()) {
                if (entry.getValue().size() == 1) {
                    generator.writeStringField(entry.getKey(), entry.getValue().get(0));
                } else {
                    for (int v = 0; v < entry.getValue().size(); v++) {
                        generator.writeStringField(entry.getKey() + "." + v, entry.getValue().get(v));
                    }
                }
            }
            generator.writeEndObject();
        }
        generator.writeEndObject();
    }
    generator.writeEndObject();
    generator.writeEndObject();
    generator.close();
    return SniffResponse.buildResponse(writer.toString(), nodes);
}

From source file:com.netflix.hystrix.serial.SerialHystrixDashboardData.java

private static void writeThreadPoolMetrics(final HystrixThreadPoolMetrics threadPoolMetrics, JsonGenerator json)
        throws IOException {
    HystrixThreadPoolKey key = threadPoolMetrics.getThreadPoolKey();

    json.writeStartObject();//w  w w.  j ava  2  s .  com

    json.writeStringField("type", "HystrixThreadPool");
    json.writeStringField("name", key.name());
    json.writeNumberField("currentTime", System.currentTimeMillis());

    json.writeNumberField("currentActiveCount", threadPoolMetrics.getCurrentActiveCount().intValue());
    json.writeNumberField("currentCompletedTaskCount",
            threadPoolMetrics.getCurrentCompletedTaskCount().longValue());
    json.writeNumberField("currentCorePoolSize", threadPoolMetrics.getCurrentCorePoolSize().intValue());
    json.writeNumberField("currentLargestPoolSize", threadPoolMetrics.getCurrentLargestPoolSize().intValue());
    json.writeNumberField("currentMaximumPoolSize", threadPoolMetrics.getCurrentMaximumPoolSize().intValue());
    json.writeNumberField("currentPoolSize", threadPoolMetrics.getCurrentPoolSize().intValue());
    json.writeNumberField("currentQueueSize", threadPoolMetrics.getCurrentQueueSize().intValue());
    json.writeNumberField("currentTaskCount", threadPoolMetrics.getCurrentTaskCount().longValue());
    safelyWriteNumberField(json, "rollingCountThreadsExecuted", new Func0<Long>() {
        @Override
        public Long call() {
            return threadPoolMetrics.getRollingCount(HystrixEventType.ThreadPool.EXECUTED);
        }
    });
    json.writeNumberField("rollingMaxActiveThreads", threadPoolMetrics.getRollingMaxActiveThreads());
    safelyWriteNumberField(json, "rollingCountCommandRejections", new Func0<Long>() {
        @Override
        public Long call() {
            return threadPoolMetrics.getRollingCount(HystrixEventType.ThreadPool.REJECTED);
        }
    });

    json.writeNumberField("propertyValue_queueSizeRejectionThreshold",
            threadPoolMetrics.getProperties().queueSizeRejectionThreshold().get());
    json.writeNumberField("propertyValue_metricsRollingStatisticalWindowInMilliseconds",
            threadPoolMetrics.getProperties().metricsRollingStatisticalWindowInMilliseconds().get());

    json.writeNumberField("reportingHosts", 1); // this will get summed across all instances in a cluster

    json.writeEndObject();
}

From source file:jvmoptions.OptionAnalyzer.java

static Path toJson(String java6, String java7, String java8) throws Exception {
    Map<String, Map<String, String>> map6 = makeMap(java6);
    Map<String, Map<String, String>> map7 = makeMap(java7);
    Map<String, Map<String, String>> map8 = makeMap(java8);

    Path output = Paths.get("result", filename("json"));

    JsonFactory factory = new JsonFactory();
    JsonGenerator jg = factory.createGenerator(output.toFile(), JsonEncoding.UTF8).useDefaultPrettyPrinter();

    jg.writeStartObject();/* w w w .java 2s. c o  m*/
    Stream.of(map6, map7, map8).map(Map::keySet).flatMap(Collection::stream).sorted().distinct().forEach(k -> {
        try {
            jg.writeFieldName(k);
            jg.writeStartObject();

            Map<String, String> base = pick(k, map8, map7, map6);
            jg.writeStringField("kind", base.get("kind"));
            jg.writeStringField("type", base.get("type"));
            jg.writeStringField("description", base.get("description"));
            jg.writeStringField("file", base.get("file"));

            write(jg, "java6", map6.get(k));
            write(jg, "java7", map7.get(k));
            write(jg, "java8", map8.get(k));

            jg.writeEndObject();
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    });
    jg.writeEndObject();

    jg.close();

    return output;
}

From source file:com.netflix.hystrix.serial.SerialHystrixDashboardData.java

private static void writeCollapserMetrics(final HystrixCollapserMetrics collapserMetrics, JsonGenerator json)
        throws IOException {
    HystrixCollapserKey key = collapserMetrics.getCollapserKey();

    json.writeStartObject();/*from ww w . ja  v a  2  s  . c o  m*/

    json.writeStringField("type", "HystrixCollapser");
    json.writeStringField("name", key.name());
    json.writeNumberField("currentTime", System.currentTimeMillis());

    safelyWriteNumberField(json, "rollingCountRequestsBatched", new Func0<Long>() {
        @Override
        public Long call() {
            return collapserMetrics.getRollingCount(HystrixEventType.Collapser.ADDED_TO_BATCH);
        }
    });
    safelyWriteNumberField(json, "rollingCountBatches", new Func0<Long>() {
        @Override
        public Long call() {
            return collapserMetrics.getRollingCount(HystrixEventType.Collapser.BATCH_EXECUTED);
        }
    });
    safelyWriteNumberField(json, "rollingCountResponsesFromCache", new Func0<Long>() {
        @Override
        public Long call() {
            return collapserMetrics.getRollingCount(HystrixEventType.Collapser.RESPONSE_FROM_CACHE);
        }
    });

    // batch size percentiles
    json.writeNumberField("batchSize_mean", collapserMetrics.getBatchSizeMean());
    json.writeObjectFieldStart("batchSize");
    json.writeNumberField("25", collapserMetrics.getBatchSizePercentile(25));
    json.writeNumberField("50", collapserMetrics.getBatchSizePercentile(50));
    json.writeNumberField("75", collapserMetrics.getBatchSizePercentile(75));
    json.writeNumberField("90", collapserMetrics.getBatchSizePercentile(90));
    json.writeNumberField("95", collapserMetrics.getBatchSizePercentile(95));
    json.writeNumberField("99", collapserMetrics.getBatchSizePercentile(99));
    json.writeNumberField("99.5", collapserMetrics.getBatchSizePercentile(99.5));
    json.writeNumberField("100", collapserMetrics.getBatchSizePercentile(100));
    json.writeEndObject();

    // shard size percentiles (commented-out for now)
    //json.writeNumberField("shardSize_mean", collapserMetrics.getShardSizeMean());
    //json.writeObjectFieldStart("shardSize");
    //json.writeNumberField("25", collapserMetrics.getShardSizePercentile(25));
    //json.writeNumberField("50", collapserMetrics.getShardSizePercentile(50));
    //json.writeNumberField("75", collapserMetrics.getShardSizePercentile(75));
    //json.writeNumberField("90", collapserMetrics.getShardSizePercentile(90));
    //json.writeNumberField("95", collapserMetrics.getShardSizePercentile(95));
    //json.writeNumberField("99", collapserMetrics.getShardSizePercentile(99));
    //json.writeNumberField("99.5", collapserMetrics.getShardSizePercentile(99.5));
    //json.writeNumberField("100", collapserMetrics.getShardSizePercentile(100));
    //json.writeEndObject();

    //json.writeNumberField("propertyValue_metricsRollingStatisticalWindowInMilliseconds", collapserMetrics.getProperties().metricsRollingStatisticalWindowInMilliseconds().get());
    json.writeBooleanField("propertyValue_requestCacheEnabled",
            collapserMetrics.getProperties().requestCacheEnabled().get());
    json.writeNumberField("propertyValue_maxRequestsInBatch",
            collapserMetrics.getProperties().maxRequestsInBatch().get());
    json.writeNumberField("propertyValue_timerDelayInMilliseconds",
            collapserMetrics.getProperties().timerDelayInMilliseconds().get());

    json.writeNumberField("reportingHosts", 1); // this will get summed across all instances in a cluster

    json.writeEndObject();
}

From source file:com.msopentech.odatajclient.engine.data.json.DOMTreeUtilsV4.java

public static void writeSubtree(final ODataClient client, final JsonGenerator jgen, final Node content,
        final boolean propType) throws IOException {
    for (Node child : XMLUtils.getChildNodes(content, Node.ELEMENT_NODE)) {
        final String childName = XMLUtils.getSimpleName(child);

        final Node typeAttr = child.getAttributes().getNamedItem(ODataConstants.ATTR_M_TYPE);
        if (typeAttr != null && EdmSimpleType.isGeospatial(typeAttr.getTextContent())) {
            jgen.writeStringField(
                    propType ? ODataConstants.JSON_TYPE : childName + "@" + ODataConstants.JSON_TYPE,
                    typeAttr.getTextContent());

            jgen.writeObjectFieldStart(childName);
            GeospatialJSONHandler.serialize(jgen, (Element) child, typeAttr.getTextContent());
            jgen.writeEndObject();/*from   w w w.  j  av a  2s  . c  o m*/
        } else if (XMLUtils.hasOnlyTextChildNodes(child)) {
            if (child.hasChildNodes()) {
                final String out;
                if (typeAttr == null) {
                    out = child.getChildNodes().item(0).getNodeValue();
                } else {
                    if (typeAttr.getTextContent().startsWith("Edm.")) {
                        final EdmSimpleType type = EdmSimpleType.fromValue(typeAttr.getTextContent());
                        final ODataPrimitiveValue value = client.getPrimitiveValueBuilder().setType(type)
                                .setText(child.getChildNodes().item(0).getNodeValue()).build();
                        out = value.toString();

                        jgen.writeStringField(childName + "@" + ODataConstants.JSON_TYPE, type.toString());
                    } else {
                        // enum
                        out = child.getTextContent();
                        jgen.writeStringField(childName + "@" + ODataConstants.JSON_TYPE,
                                typeAttr.getTextContent());
                    }
                }
                jgen.writeStringField(childName, out);
            } else {
                if (child.getAttributes().getNamedItem(ODataConstants.ATTR_NULL) == null) {
                    if (typeAttr != null && EdmSimpleType.String.toString().equals(typeAttr.getTextContent())) {
                        jgen.writeStringField(childName + "@" + ODataConstants.JSON_TYPE,
                                typeAttr.getTextContent());
                        jgen.writeStringField(childName, StringUtils.EMPTY);
                    } else {
                        jgen.writeArrayFieldStart(childName);
                        jgen.writeEndArray();
                    }
                } else {
                    jgen.writeNullField(childName);
                }
            }
        } else {
            if (XMLUtils.hasElementsChildNode(child)) {
                jgen.writeArrayFieldStart(childName);

                for (Node nephew : XMLUtils.getChildNodes(child, Node.ELEMENT_NODE)) {
                    if (XMLUtils.hasOnlyTextChildNodes(nephew)) {
                        jgen.writeString(nephew.getChildNodes().item(0).getNodeValue());
                    } else {
                        jgen.writeStartObject();
                        DOMTreeUtils.writeSubtree(client, jgen, nephew);
                        jgen.writeEndObject();
                    }
                }

                jgen.writeEndArray();
            } else {
                jgen.writeObjectFieldStart(childName);
                if (typeAttr != null) {
                    jgen.writeStringField("@" + ODataConstants.JSON_TYPE, typeAttr.getTextContent());
                }

                DOMTreeUtils.writeSubtree(client, jgen, child);

                jgen.writeEndObject();
            }
        }
    }
}

From source file:com.cedarsoft.couchdb.io.CouchDocSerializer.java

private static <T> void serializeInlineAttachments(@Nonnull CouchDoc<T> doc, @Nonnull JsonGenerator generator)
        throws IOException {
    if (!doc.hasInlineAttachments()) {
        return;//from ww w .j a  v  a2s. c  o  m
    }

    generator.writeObjectFieldStart(PROPERTY_ATTACHMENTS);

    for (CouchDoc.Attachment attachment : doc.getAttachments()) {
        if (!attachment.isInline()) {
            throw new IllegalStateException("Cannot serialize non-inline attachments: " + attachment);
        }
        generator.writeObjectFieldStart(attachment.getId().asString());

        generator.writeStringField(PROPERTY_CONTENT_TYPE, attachment.getContentType().toString());
        generator.writeStringField(PROPERTY_DATA, new String(Base64.encode(attachment.getData())));

        generator.writeEndObject();
    }

    generator.writeEndObject();
}

From source file:com.msopentech.odatajclient.engine.data.json.DOMTreeUtilsV3.java

/**
 * Serializes DOM content as JSON.//from w w w.j  av a 2s. com
 *
 * @param client OData client.
 * @param jgen JSON generator.
 * @param content content.
 * @param propType whether to output type information in the way needed for property values or not.
 * @throws IOException in case of write error.
 */
public static void writeSubtree(final ODataClient client, final JsonGenerator jgen, final Node content,
        final boolean propType) throws IOException {

    for (Node child : XMLUtils.getChildNodes(content, Node.ELEMENT_NODE)) {
        final String childName = XMLUtils.getSimpleName(child);

        final Node typeAttr = child.getAttributes().getNamedItem(ODataConstants.ATTR_M_TYPE);
        if (typeAttr != null && EdmSimpleType.isGeospatial(typeAttr.getTextContent())) {
            jgen.writeStringField(
                    propType ? ODataConstants.JSON_TYPE : childName + "@" + ODataConstants.JSON_TYPE,
                    typeAttr.getTextContent());

            jgen.writeObjectFieldStart(childName);
            GeospatialJSONHandler.serialize(jgen, (Element) child, typeAttr.getTextContent());
            jgen.writeEndObject();
        } else if (XMLUtils.hasOnlyTextChildNodes(child)) {
            if (child.hasChildNodes()) {
                final String out;
                if (typeAttr == null) {
                    out = child.getChildNodes().item(0).getNodeValue();
                } else {
                    final EdmSimpleType type = EdmSimpleType.fromValue(typeAttr.getTextContent());
                    final ODataPrimitiveValue value = client.getPrimitiveValueBuilder().setType(type)
                            .setText(child.getChildNodes().item(0).getNodeValue()).build();
                    out = value.toString();

                    jgen.writeStringField(childName + "@" + ODataConstants.JSON_TYPE, type.toString());
                }
                jgen.writeStringField(childName, out);
            } else {
                if (child.getAttributes().getNamedItem(ODataConstants.ATTR_NULL) == null) {
                    if (typeAttr != null && EdmSimpleType.String.toString().equals(typeAttr.getTextContent())) {
                        jgen.writeStringField(childName + "@" + ODataConstants.JSON_TYPE,
                                typeAttr.getTextContent());
                        jgen.writeStringField(childName, StringUtils.EMPTY);
                    } else {
                        jgen.writeArrayFieldStart(childName);
                        jgen.writeEndArray();
                    }
                } else {
                    jgen.writeNullField(childName);
                }
            }
        } else {
            if (XMLUtils.hasElementsChildNode(child)) {
                jgen.writeArrayFieldStart(childName);

                for (Node nephew : XMLUtils.getChildNodes(child, Node.ELEMENT_NODE)) {
                    if (XMLUtils.hasOnlyTextChildNodes(nephew)) {
                        jgen.writeString(nephew.getChildNodes().item(0).getNodeValue());
                    } else {
                        jgen.writeStartObject();
                        DOMTreeUtils.writeSubtree(client, jgen, nephew);
                        jgen.writeEndObject();
                    }
                }

                jgen.writeEndArray();
            } else {
                jgen.writeObjectFieldStart(childName);
                if (typeAttr != null) {
                    jgen.writeStringField(ODataConstants.JSON_TYPE, typeAttr.getTextContent());
                }

                DOMTreeUtils.writeSubtree(client, jgen, child);

                jgen.writeEndObject();
            }
        }
    }
}

From source file:com.msopentech.odatajclient.engine.data.json.DOMTreeUtils.java

/**
 * Serializes DOM content as JSON.//  ww  w.  j ava 2 s  .c  om
 *
 * @param jgen JSON generator.
 * @param content content.
 * @param propType whether to output type information in the way needed for property values or not.
 * @throws IOException in case of write error.
 */
public static void writeSubtree(final JsonGenerator jgen, final Node content, final boolean propType)
        throws IOException {

    for (Node child : XMLUtils.getChildNodes(content, Node.ELEMENT_NODE)) {
        final String childName = XMLUtils.getSimpleName(child);

        final Node typeAttr = child.getAttributes().getNamedItem(ODataConstants.ATTR_M_TYPE);
        if (typeAttr != null && EdmSimpleType.isGeospatial(typeAttr.getTextContent())) {
            jgen.writeStringField(
                    propType ? ODataConstants.JSON_TYPE : childName + "@" + ODataConstants.JSON_TYPE,
                    typeAttr.getTextContent());

            jgen.writeObjectFieldStart(childName);
            GeospatialJSONHandler.serialize(jgen, (Element) child, typeAttr.getTextContent());
            jgen.writeEndObject();
        } else if (XMLUtils.hasOnlyTextChildNodes(child)) {
            if (child.hasChildNodes()) {
                final String out;
                if (typeAttr == null) {
                    out = child.getChildNodes().item(0).getNodeValue();
                } else {
                    final EdmSimpleType type = EdmSimpleType.fromValue(typeAttr.getTextContent());
                    final ODataPrimitiveValue value = new ODataPrimitiveValue.Builder().setType(type)
                            .setText(child.getChildNodes().item(0).getNodeValue()).build();
                    out = value.toString();

                    jgen.writeStringField(childName + "@" + ODataConstants.JSON_TYPE, type.toString());
                }
                jgen.writeStringField(childName, out);
            } else {
                if (child.getAttributes().getNamedItem(ODataConstants.ATTR_NULL) == null) {
                    if (typeAttr != null && EdmSimpleType.String.toString().equals(typeAttr.getTextContent())) {
                        jgen.writeStringField(childName + "@" + ODataConstants.JSON_TYPE,
                                typeAttr.getTextContent());
                        jgen.writeStringField(childName, StringUtils.EMPTY);
                    } else {
                        jgen.writeArrayFieldStart(childName);
                        jgen.writeEndArray();
                    }
                } else {
                    jgen.writeNullField(childName);
                }
            }
        } else {
            if (XMLUtils.hasElementsChildNode(child)) {
                jgen.writeArrayFieldStart(childName);

                for (Node nephew : XMLUtils.getChildNodes(child, Node.ELEMENT_NODE)) {
                    if (XMLUtils.hasOnlyTextChildNodes(nephew)) {
                        jgen.writeString(nephew.getChildNodes().item(0).getNodeValue());
                    } else {
                        jgen.writeStartObject();
                        writeSubtree(jgen, nephew);
                        jgen.writeEndObject();
                    }
                }

                jgen.writeEndArray();
            } else {
                jgen.writeObjectFieldStart(childName);
                if (typeAttr != null) {
                    jgen.writeStringField(ODataConstants.JSON_TYPE, typeAttr.getTextContent());
                }

                writeSubtree(jgen, child);

                jgen.writeEndObject();
            }
        }
    }
}

From source file:com.msopentech.odatajclient.engine.data.impl.JSONDOMTreeUtils.java

/**
 * Serializes DOM content as JSON.//from  w w w.  ja v a  2 s .  c  o  m
 *
 * @param client OData client.
 * @param jgen JSON generator.
 * @param content content.
 * @param propType whether to output type information in the way needed for property values or not.
 * @throws IOException in case of write error.
 */
public static void writeSubtree(final ODataClient client, final JsonGenerator jgen, final Node content,
        final boolean propType) throws IOException {

    for (Node child : XMLUtils.getChildNodes(content, Node.ELEMENT_NODE)) {
        final String childName = XMLUtils.getSimpleName(child);

        final Node typeAttr = child.getAttributes().getNamedItem(ODataConstants.ATTR_M_TYPE);
        if (typeAttr != null && EdmSimpleType.isGeospatial(typeAttr.getTextContent())) {
            jgen.writeStringField(
                    propType ? ODataConstants.JSON_TYPE : childName + "@" + ODataConstants.JSON_TYPE,
                    typeAttr.getTextContent());

            jgen.writeObjectFieldStart(childName);
            GeospatialJSONHandler.serialize(client, jgen, (Element) child, typeAttr.getTextContent());
            jgen.writeEndObject();
        } else if (XMLUtils.hasOnlyTextChildNodes(child)) {
            if (child.hasChildNodes()) {
                final String out;
                if (typeAttr == null) {
                    out = child.getChildNodes().item(0).getNodeValue();
                } else {
                    final EdmSimpleType type = EdmSimpleType.fromValue(typeAttr.getTextContent());
                    final ODataPrimitiveValue value = client.getPrimitiveValueBuilder().setType(type)
                            .setText(child.getChildNodes().item(0).getNodeValue()).build();
                    out = value.toString();

                    jgen.writeStringField(childName + "@" + ODataConstants.JSON_TYPE, type.toString());
                }
                jgen.writeStringField(childName, out);
            } else {
                if (child.getAttributes().getNamedItem(ODataConstants.ATTR_NULL) == null) {
                    if (typeAttr != null && EdmSimpleType.String.toString().equals(typeAttr.getTextContent())) {
                        jgen.writeStringField(childName + "@" + ODataConstants.JSON_TYPE,
                                typeAttr.getTextContent());
                        jgen.writeStringField(childName, StringUtils.EMPTY);
                    } else {
                        jgen.writeArrayFieldStart(childName);
                        jgen.writeEndArray();
                    }
                } else {
                    jgen.writeNullField(childName);
                }
            }
        } else {
            if (XMLUtils.hasElementsChildNode(child)) {
                jgen.writeArrayFieldStart(childName);

                for (Node nephew : XMLUtils.getChildNodes(child, Node.ELEMENT_NODE)) {
                    if (XMLUtils.hasOnlyTextChildNodes(nephew)) {
                        jgen.writeString(nephew.getChildNodes().item(0).getNodeValue());
                    } else {
                        jgen.writeStartObject();
                        writeSubtree(client, jgen, nephew);
                        jgen.writeEndObject();
                    }
                }

                jgen.writeEndArray();
            } else {
                jgen.writeObjectFieldStart(childName);
                if (typeAttr != null) {
                    jgen.writeStringField(ODataConstants.JSON_TYPE, typeAttr.getTextContent());
                }

                writeSubtree(client, jgen, child);

                jgen.writeEndObject();
            }
        }
    }
}

From source file:com.baasbox.configuration.PropertiesConfigurationHelper.java

/***
 *
 * Returns a json representation of the Enumerator
 * The Enumerator must implements the IProperties interface
 * @param en    the Enumerator to serialize. It must implements the IProperties interface
 * @return       the representation of the Enumerator 
 *//*from  w  ww. jav a  2 s . com*/
@SuppressWarnings("unchecked")
public static String dumpConfigurationAsJson(String section) {
    Class en = CONFIGURATION_SECTIONS.get(section);
    try {
        JsonFactory jfactory = new JsonFactory();
        StringWriter sw = new StringWriter();
        String enumDescription = "";
        JsonGenerator gen = jfactory.createJsonGenerator(sw);

        Method getEnumDescription = en.getMethod("getEnumDescription");
        if (getEnumDescription != null && getEnumDescription.getReturnType() == String.class
                && Modifier.isStatic(getEnumDescription.getModifiers()))
            enumDescription = (String) getEnumDescription.invoke(null);
        gen.writeStartObject(); //{
        gen.writeStringField("section", section); //    "configuration":"EnumName"
        gen.writeStringField("description", enumDescription); //   ,"description": "EnumDescription"
        gen.writeFieldName("sub sections"); //  ,"sections":
        gen.writeStartObject(); //      {
        String lastSection = "";
        EnumSet values = EnumSet.allOf(en);
        for (Object v : values) {
            String key = (String) (en.getMethod("getKey")).invoke(v);
            boolean isVisible = (Boolean) (en.getMethod("isVisible")).invoke(v);
            String valueAsString;
            if (isVisible)
                valueAsString = (String) (en.getMethod("getValueAsString")).invoke(v);
            else
                valueAsString = "--HIDDEN--";
            boolean isEditable = (Boolean) (en.getMethod("isEditable")).invoke(v);
            String valueDescription = (String) (en.getMethod("getValueDescription")).invoke(v);
            Class type = (Class) en.getMethod("getType").invoke(v);
            String subsection = key.substring(0, key.indexOf('.'));
            if (!lastSection.equals(subsection)) {
                if (gen.getOutputContext().inArray())
                    gen.writeEndArray();
                gen.writeFieldName(subsection); //         "sectionName":
                gen.writeStartArray(); //            [
                lastSection = subsection;
            }
            boolean isOverridden = (Boolean) (en.getMethod("isOverridden")).invoke(v);
            gen.writeStartObject(); //               {
            gen.writeStringField(key, valueAsString); //                     "key": "value"   
            gen.writeStringField("description", valueDescription); //                  ,"description":"description"
            gen.writeStringField("type", type.getSimpleName()); //                  ,"type":"type"
            gen.writeBooleanField("editable", isEditable); //                  ,"editable":"true|false"
            gen.writeBooleanField("visible", isVisible); //                  ,"visible":"true|false"
            gen.writeBooleanField("overridden", isOverridden); //                  ,"overridden":"true|false"
            gen.writeEndObject(); //               }
        }
        if (gen.getOutputContext().inArray())
            gen.writeEndArray(); //            ]
        gen.writeEndObject(); //      }
        gen.writeEndObject(); //}
        gen.close();
        return sw.toString();
    } catch (Exception e) {
        BaasBoxLogger.error("Cannot generate a json for " + en.getSimpleName()
                + " Enum. Is it an Enum that implements the IProperties interface?", e);
    }
    return "{}";
}