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

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

Introduction

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

Prototype

@Override
public abstract void close() throws IOException;

Source Link

Document

Method called to close this generator, so that no more content can be written.

Usage

From source file:net.opentsdb.tsd.HttpJsonSerializer.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  w w .  j  a  va  2 s.co  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);
                        if (dp.isInteger()) {
                            json.writeNumber(dp.longValue());
                        } else {
                            json.writeNumber(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;
                        if (dp.isInteger()) {
                            json.writeNumberField(Long.toString(timestamp), dp.longValue());
                        } else {
                            json.writeNumberField(Long.toString(timestamp), 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:eu.project.ttc.models.index.JsonTermIndexIO.java

public static void save(Writer writer, TermIndex termIndex, JsonOptions options) throws IOException {
    JsonFactory jsonFactory = new JsonFactory(); // or, for data binding, org.codehaus.jackson.mapper.MappingJsonFactory 
    //      jsonFactory.configure(f, state)
    JsonGenerator jg = jsonFactory.createGenerator(writer); // or Stream, Reader
    jg.useDefaultPrettyPrinter();//from   w  ww  .ja v a  2s . c om

    jg.writeStartObject();

    jg.writeFieldName(METADATA);
    jg.writeStartObject();
    jg.writeFieldName(NAME);
    jg.writeString(termIndex.getName());
    jg.writeFieldName(LANG);
    jg.writeString(termIndex.getLang().getCode());
    if (termIndex.getCorpusId() != null) {
        jg.writeFieldName(CORPUS_ID);
        jg.writeString(termIndex.getCorpusId());
    }

    jg.writeFieldName(OCCURRENCE_STORAGE);
    if (options.isMongoDBOccStore()) {
        jg.writeString(OCCURRENCE_STORAGE_MONGODB);
        jg.writeFieldName(OCCURRENCE_MONGODB_STORE_URI);
        jg.writeString(options.getMongoDBOccStore());
    } else if (options.isEmbeddedOccurrences())
        jg.writeString(OCCURRENCE_STORAGE_EMBEDDED);
    else
        throw new IllegalStateException("Unknown storage mode");

    jg.writeFieldName(NB_WORD_ANNOTATIONS);
    jg.writeNumber(termIndex.getWordAnnotationsNum());
    jg.writeFieldName(NB_SPOTTED_TERMS);
    jg.writeNumber(termIndex.getSpottedTermsNum());

    jg.writeEndObject();

    jg.writeFieldName(INPUT_SOURCES);
    int idCnt = 0;
    Map<String, Integer> inputSources = Maps.newTreeMap();
    for (Document d : termIndex.getDocuments())
        if (!inputSources.containsKey(d.getUrl()))
            inputSources.put(d.getUrl(), ++idCnt);
    jg.writeStartObject();
    for (String uri : inputSources.keySet()) {
        jg.writeFieldName(inputSources.get(uri).toString());
        jg.writeString(uri);
    }
    jg.writeEndObject();

    jg.writeFieldName(WORDS);
    jg.writeStartArray();
    for (Word w : termIndex.getWords()) {
        jg.writeStartObject();
        jg.writeFieldName(LEMMA);
        jg.writeString(w.getLemma());
        jg.writeFieldName(STEM);
        jg.writeString(w.getStem());
        if (w.isCompound()) {
            jg.writeFieldName(COMPOUND_TYPE);
            jg.writeString(w.getCompoundType().name());
            jg.writeFieldName(COMPONENTS);
            jg.writeStartArray();
            for (Component c : w.getComponents()) {
                jg.writeStartObject();
                jg.writeFieldName(LEMMA);
                jg.writeString(c.getLemma());
                jg.writeFieldName(BEGIN);
                jg.writeNumber(c.getBegin());
                jg.writeFieldName(END);
                jg.writeNumber(c.getEnd());
                jg.writeEndObject();
            }
            jg.writeEndArray();
        }

        jg.writeEndObject();
    }
    jg.writeEndArray();

    Set<TermVariation> termVariations = Sets.newHashSet();

    jg.writeFieldName(TERMS);
    jg.writeStartArray();
    for (Term t : termIndex.getTerms()) {
        termVariations.addAll(t.getVariations());

        jg.writeStartObject();
        jg.writeFieldName(ID);
        jg.writeNumber(t.getId());
        jg.writeFieldName(RANK);
        jg.writeNumber(t.getRank());
        jg.writeFieldName(GROUPING_KEY);
        jg.writeString(t.getGroupingKey());
        jg.writeFieldName(WORDS);
        jg.writeStartArray();
        for (TermWord tw : t.getWords()) {
            jg.writeStartObject();
            jg.writeFieldName(SYN);
            jg.writeString(tw.getSyntacticLabel());
            jg.writeFieldName(LEMMA);
            jg.writeString(tw.getWord().getLemma());
            jg.writeEndObject();
        }
        jg.writeEndArray();

        jg.writeFieldName(FREQUENCY);
        jg.writeNumber(t.getFrequency());
        jg.writeFieldName(FREQ_NORM);
        jg.writeNumber(t.getFrequencyNorm());
        jg.writeFieldName(GENERAL_FREQ_NORM);
        jg.writeNumber(t.getGeneralFrequencyNorm());
        jg.writeFieldName(SPECIFICITY);
        jg.writeNumber(t.getSpecificity());
        jg.writeFieldName(SPOTTING_RULE);
        jg.writeString(t.getSpottingRule());

        if (options.withOccurrences() && options.isEmbeddedOccurrences()) {
            jg.writeFieldName(OCCURRENCES);
            jg.writeStartArray();
            for (TermOccurrence termOcc : t.getOccurrences()) {
                jg.writeStartObject();
                jg.writeFieldName(BEGIN);
                jg.writeNumber(termOcc.getBegin());
                jg.writeFieldName(END);
                jg.writeNumber(termOcc.getEnd());
                jg.writeFieldName(TEXT);
                jg.writeString(termOcc.getCoveredText());
                jg.writeFieldName(FILE);
                jg.writeNumber(inputSources.get(termOcc.getSourceDocument().getUrl()));
                jg.writeEndObject();
            }
            jg.writeEndArray();
        }

        if (options.isWithContexts() && t.isContextVectorComputed()) {
            jg.writeFieldName(CONTEXT);
            jg.writeStartObject();

            jg.writeFieldName(TOTAL_COOCCURRENCES);
            jg.writeNumber(t.getContextVector().getTotalCoccurrences());
            jg.writeFieldName(CO_OCCURRENCES);
            jg.writeStartArray();
            if (t.isContextVectorComputed()) {
                for (ContextVector.Entry contextEntry : t.getContextVector().getEntries()) {
                    jg.writeStartObject();
                    jg.writeFieldName(CO_TERM);
                    jg.writeString(contextEntry.getCoTerm().getGroupingKey());
                    jg.writeFieldName(NB_COCCS);
                    jg.writeNumber(contextEntry.getNbCooccs());
                    jg.writeFieldName(ASSOC_RATE);
                    jg.writeNumber(contextEntry.getAssocRate());
                    jg.writeEndObject();
                }
            }
            jg.writeEndArray();
            jg.writeEndObject();
        }

        jg.writeEndObject();
    }
    jg.writeEndArray();

    /* Variants */
    jg.writeFieldName(TERM_VARIATIONS);
    jg.writeStartArray();
    for (TermVariation v : termVariations) {
        jg.writeStartObject();
        jg.writeFieldName(BASE);
        jg.writeString(v.getBase().getGroupingKey());
        jg.writeFieldName(VARIANT);
        jg.writeString(v.getVariant().getGroupingKey());
        jg.writeFieldName(VARIANT_TYPE);
        jg.writeString(v.getVariationType().getShortName());
        jg.writeFieldName(INFO);
        jg.writeString(v.getInfo().toString());
        jg.writeFieldName(VARIANT_SCORE);
        jg.writeNumber(v.getScore());
        jg.writeEndObject();
    }
    jg.writeEndArray();

    jg.writeEndObject();
    jg.close();
}

From source file:org.springframework.cloud.netflix.hystrix.amqp.HystrixStreamTask.java

@Scheduled(fixedRateString = "${hystrix.stream.amqp.gatherRate:500}")
public void gatherMetrics() {
    try {//  w w  w .  jav  a 2 s  . com
        // command metrics
        Collection<HystrixCommandMetrics> instances = HystrixCommandMetrics.getInstances();
        if (!instances.isEmpty()) {
            log.trace("gathering metrics size: " + instances.size());
        }

        ServiceInstance localService = this.discoveryClient.getLocalServiceInstance();

        for (HystrixCommandMetrics commandMetrics : instances) {
            HystrixCommandKey key = commandMetrics.getCommandKey();
            HystrixCircuitBreaker circuitBreaker = HystrixCircuitBreaker.Factory.getInstance(key);

            StringWriter jsonString = new StringWriter();
            JsonGenerator json = this.jsonFactory.createGenerator(jsonString);

            json.writeStartObject();

            addServiceData(json, localService);
            json.writeObjectFieldStart("data");
            json.writeStringField("type", "HystrixCommand");
            String name = key.name();

            if (this.properties.isPrefixMetricName()) {
                name = localService.getServiceId() + "." + name;
            }

            json.writeStringField("name", name);
            json.writeStringField("group", commandMetrics.getCommandGroup().name());
            json.writeNumberField("currentTime", System.currentTimeMillis());

            // circuit breaker
            if (circuitBreaker == null) {
                // circuit breaker is disabled and thus never open
                json.writeBooleanField("isCircuitBreakerOpen", false);
            } else {
                json.writeBooleanField("isCircuitBreakerOpen", circuitBreaker.isOpen());
            }
            HystrixCommandMetrics.HealthCounts healthCounts = commandMetrics.getHealthCounts();
            json.writeNumberField("errorPercentage", healthCounts.getErrorPercentage());
            json.writeNumberField("errorCount", healthCounts.getErrorCount());
            json.writeNumberField("requestCount", healthCounts.getTotalRequests());

            // rolling counters
            json.writeNumberField("rollingCountCollapsedRequests",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.COLLAPSED));
            json.writeNumberField("rollingCountExceptionsThrown",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN));
            json.writeNumberField("rollingCountFailure",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.FAILURE));
            json.writeNumberField("rollingCountFallbackFailure",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE));
            json.writeNumberField("rollingCountFallbackRejection",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION));
            json.writeNumberField("rollingCountFallbackSuccess",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS));
            json.writeNumberField("rollingCountResponsesFromCache",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE));
            json.writeNumberField("rollingCountSemaphoreRejected",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED));
            json.writeNumberField("rollingCountShortCircuited",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED));
            json.writeNumberField("rollingCountSuccess",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS));
            json.writeNumberField("rollingCountThreadPoolRejected",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED));
            json.writeNumberField("rollingCountTimeout",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT));

            json.writeNumberField("currentConcurrentExecutionCount",
                    commandMetrics.getCurrentConcurrentExecutionCount());

            // latency percentiles
            json.writeNumberField("latencyExecute_mean", commandMetrics.getExecutionTimeMean());
            json.writeObjectFieldStart("latencyExecute");
            json.writeNumberField("0", commandMetrics.getExecutionTimePercentile(0));
            json.writeNumberField("25", commandMetrics.getExecutionTimePercentile(25));
            json.writeNumberField("50", commandMetrics.getExecutionTimePercentile(50));
            json.writeNumberField("75", commandMetrics.getExecutionTimePercentile(75));
            json.writeNumberField("90", commandMetrics.getExecutionTimePercentile(90));
            json.writeNumberField("95", commandMetrics.getExecutionTimePercentile(95));
            json.writeNumberField("99", commandMetrics.getExecutionTimePercentile(99));
            json.writeNumberField("99.5", commandMetrics.getExecutionTimePercentile(99.5));
            json.writeNumberField("100", commandMetrics.getExecutionTimePercentile(100));
            json.writeEndObject();
            //
            json.writeNumberField("latencyTotal_mean", commandMetrics.getTotalTimeMean());
            json.writeObjectFieldStart("latencyTotal");
            json.writeNumberField("0", commandMetrics.getTotalTimePercentile(0));
            json.writeNumberField("25", commandMetrics.getTotalTimePercentile(25));
            json.writeNumberField("50", commandMetrics.getTotalTimePercentile(50));
            json.writeNumberField("75", commandMetrics.getTotalTimePercentile(75));
            json.writeNumberField("90", commandMetrics.getTotalTimePercentile(90));
            json.writeNumberField("95", commandMetrics.getTotalTimePercentile(95));
            json.writeNumberField("99", commandMetrics.getTotalTimePercentile(99));
            json.writeNumberField("99.5", commandMetrics.getTotalTimePercentile(99.5));
            json.writeNumberField("100", commandMetrics.getTotalTimePercentile(100));
            json.writeEndObject();

            // property values for reporting what is actually seen by the command
            // rather than what was set somewhere
            HystrixCommandProperties commandProperties = commandMetrics.getProperties();

            json.writeNumberField("propertyValue_circuitBreakerRequestVolumeThreshold",
                    commandProperties.circuitBreakerRequestVolumeThreshold().get());
            json.writeNumberField("propertyValue_circuitBreakerSleepWindowInMilliseconds",
                    commandProperties.circuitBreakerSleepWindowInMilliseconds().get());
            json.writeNumberField("propertyValue_circuitBreakerErrorThresholdPercentage",
                    commandProperties.circuitBreakerErrorThresholdPercentage().get());
            json.writeBooleanField("propertyValue_circuitBreakerForceOpen",
                    commandProperties.circuitBreakerForceOpen().get());
            json.writeBooleanField("propertyValue_circuitBreakerForceClosed",
                    commandProperties.circuitBreakerForceClosed().get());
            json.writeBooleanField("propertyValue_circuitBreakerEnabled",
                    commandProperties.circuitBreakerEnabled().get());

            json.writeStringField("propertyValue_executionIsolationStrategy",
                    commandProperties.executionIsolationStrategy().get().name());
            json.writeNumberField("propertyValue_executionIsolationThreadTimeoutInMilliseconds",
                    commandProperties.executionIsolationThreadTimeoutInMilliseconds().get());
            json.writeBooleanField("propertyValue_executionIsolationThreadInterruptOnTimeout",
                    commandProperties.executionIsolationThreadInterruptOnTimeout().get());
            json.writeStringField("propertyValue_executionIsolationThreadPoolKeyOverride",
                    commandProperties.executionIsolationThreadPoolKeyOverride().get());
            json.writeNumberField("propertyValue_executionIsolationSemaphoreMaxConcurrentRequests",
                    commandProperties.executionIsolationSemaphoreMaxConcurrentRequests().get());
            json.writeNumberField("propertyValue_fallbackIsolationSemaphoreMaxConcurrentRequests",
                    commandProperties.fallbackIsolationSemaphoreMaxConcurrentRequests().get());

            // TODO
            /*
             * The following are commented out as these rarely change and are verbose
             * for streaming for something people don't change. We could perhaps allow
             * a property or request argument to include these.
             */

            // json.put("propertyValue_metricsRollingPercentileEnabled",
            // commandProperties.metricsRollingPercentileEnabled().get());
            // json.put("propertyValue_metricsRollingPercentileBucketSize",
            // commandProperties.metricsRollingPercentileBucketSize().get());
            // json.put("propertyValue_metricsRollingPercentileWindow",
            // commandProperties.metricsRollingPercentileWindowInMilliseconds().get());
            // json.put("propertyValue_metricsRollingPercentileWindowBuckets",
            // commandProperties.metricsRollingPercentileWindowBuckets().get());
            // json.put("propertyValue_metricsRollingStatisticalWindowBuckets",
            // commandProperties.metricsRollingStatisticalWindowBuckets().get());
            json.writeNumberField("propertyValue_metricsRollingStatisticalWindowInMilliseconds",
                    commandProperties.metricsRollingStatisticalWindowInMilliseconds().get());

            json.writeBooleanField("propertyValue_requestCacheEnabled",
                    commandProperties.requestCacheEnabled().get());
            json.writeBooleanField("propertyValue_requestLogEnabled",
                    commandProperties.requestLogEnabled().get());

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

            json.writeEndObject(); // end data attribute
            json.writeEndObject();
            json.close();

            // output
            this.jsonMetrics.add(jsonString.getBuffer().toString());
        }

        // thread pool metrics
        for (HystrixThreadPoolMetrics threadPoolMetrics : HystrixThreadPoolMetrics.getInstances()) {
            HystrixThreadPoolKey key = threadPoolMetrics.getThreadPoolKey();

            StringWriter jsonString = new StringWriter();
            JsonGenerator json = this.jsonFactory.createGenerator(jsonString);
            json.writeStartObject();

            addServiceData(json, localService);
            json.writeObjectFieldStart("data");

            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());
            json.writeNumberField("rollingCountThreadsExecuted",
                    threadPoolMetrics.getRollingCountThreadsExecuted());
            json.writeNumberField("rollingMaxActiveThreads", threadPoolMetrics.getRollingMaxActiveThreads());

            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(); // end of data object
            json.writeEndObject();
            json.close();
            // output to stream
            this.jsonMetrics.add(jsonString.getBuffer().toString());
        }
    } catch (Exception ex) {
        log.error("Error adding metrics to queue", ex);
    }
}

From source file:org.springframework.cloud.netflix.hystrix.stream.HystrixStreamTask.java

@Scheduled(fixedRateString = "${hystrix.stream.queue.gatherRate:500}")
public void gatherMetrics() {
    try {/*from  w  w  w .  jav  a 2s .  c om*/
        // command metrics
        Collection<HystrixCommandMetrics> instances = HystrixCommandMetrics.getInstances();
        if (!instances.isEmpty()) {
            log.trace("gathering metrics size: " + instances.size());
        }

        for (HystrixCommandMetrics commandMetrics : instances) {
            HystrixCommandKey key = commandMetrics.getCommandKey();
            HystrixCircuitBreaker circuitBreaker = HystrixCircuitBreaker.Factory.getInstance(key);

            StringWriter jsonString = new StringWriter();
            JsonGenerator json = this.jsonFactory.createGenerator(jsonString);

            json.writeStartObject();

            addServiceData(json, registration);
            json.writeObjectFieldStart("data");
            json.writeStringField("type", "HystrixCommand");
            String name = key.name();

            if (this.properties.isPrefixMetricName() && registration != null) {
                name = registration.getServiceId() + "." + name;
            }

            json.writeStringField("name", name);
            json.writeStringField("group", commandMetrics.getCommandGroup().name());
            json.writeNumberField("currentTime", System.currentTimeMillis());

            // circuit breaker
            if (circuitBreaker == null) {
                // circuit breaker is disabled and thus never open
                json.writeBooleanField("isCircuitBreakerOpen", false);
            } else {
                json.writeBooleanField("isCircuitBreakerOpen", circuitBreaker.isOpen());
            }
            HystrixCommandMetrics.HealthCounts healthCounts = commandMetrics.getHealthCounts();
            json.writeNumberField("errorPercentage", healthCounts.getErrorPercentage());
            json.writeNumberField("errorCount", healthCounts.getErrorCount());
            json.writeNumberField("requestCount", healthCounts.getTotalRequests());

            // rolling counters
            json.writeNumberField("rollingCountCollapsedRequests",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.COLLAPSED));
            json.writeNumberField("rollingCountExceptionsThrown",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.EXCEPTION_THROWN));
            json.writeNumberField("rollingCountFailure",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.FAILURE));
            json.writeNumberField("rollingCountFallbackFailure",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_FAILURE));
            json.writeNumberField("rollingCountFallbackRejection",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_REJECTION));
            json.writeNumberField("rollingCountFallbackSuccess",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.FALLBACK_SUCCESS));
            json.writeNumberField("rollingCountResponsesFromCache",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.RESPONSE_FROM_CACHE));
            json.writeNumberField("rollingCountSemaphoreRejected",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.SEMAPHORE_REJECTED));
            json.writeNumberField("rollingCountShortCircuited",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.SHORT_CIRCUITED));
            json.writeNumberField("rollingCountSuccess",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.SUCCESS));
            json.writeNumberField("rollingCountThreadPoolRejected",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.THREAD_POOL_REJECTED));
            json.writeNumberField("rollingCountTimeout",
                    commandMetrics.getRollingCount(HystrixRollingNumberEvent.TIMEOUT));

            json.writeNumberField("currentConcurrentExecutionCount",
                    commandMetrics.getCurrentConcurrentExecutionCount());

            // latency percentiles
            json.writeNumberField("latencyExecute_mean", commandMetrics.getExecutionTimeMean());
            json.writeObjectFieldStart("latencyExecute");
            json.writeNumberField("0", commandMetrics.getExecutionTimePercentile(0));
            json.writeNumberField("25", commandMetrics.getExecutionTimePercentile(25));
            json.writeNumberField("50", commandMetrics.getExecutionTimePercentile(50));
            json.writeNumberField("75", commandMetrics.getExecutionTimePercentile(75));
            json.writeNumberField("90", commandMetrics.getExecutionTimePercentile(90));
            json.writeNumberField("95", commandMetrics.getExecutionTimePercentile(95));
            json.writeNumberField("99", commandMetrics.getExecutionTimePercentile(99));
            json.writeNumberField("99.5", commandMetrics.getExecutionTimePercentile(99.5));
            json.writeNumberField("100", commandMetrics.getExecutionTimePercentile(100));
            json.writeEndObject();
            //
            json.writeNumberField("latencyTotal_mean", commandMetrics.getTotalTimeMean());
            json.writeObjectFieldStart("latencyTotal");
            json.writeNumberField("0", commandMetrics.getTotalTimePercentile(0));
            json.writeNumberField("25", commandMetrics.getTotalTimePercentile(25));
            json.writeNumberField("50", commandMetrics.getTotalTimePercentile(50));
            json.writeNumberField("75", commandMetrics.getTotalTimePercentile(75));
            json.writeNumberField("90", commandMetrics.getTotalTimePercentile(90));
            json.writeNumberField("95", commandMetrics.getTotalTimePercentile(95));
            json.writeNumberField("99", commandMetrics.getTotalTimePercentile(99));
            json.writeNumberField("99.5", commandMetrics.getTotalTimePercentile(99.5));
            json.writeNumberField("100", commandMetrics.getTotalTimePercentile(100));
            json.writeEndObject();

            // property values for reporting what is actually seen by the command
            // rather than what was set somewhere
            HystrixCommandProperties commandProperties = commandMetrics.getProperties();

            json.writeNumberField("propertyValue_circuitBreakerRequestVolumeThreshold",
                    commandProperties.circuitBreakerRequestVolumeThreshold().get());
            json.writeNumberField("propertyValue_circuitBreakerSleepWindowInMilliseconds",
                    commandProperties.circuitBreakerSleepWindowInMilliseconds().get());
            json.writeNumberField("propertyValue_circuitBreakerErrorThresholdPercentage",
                    commandProperties.circuitBreakerErrorThresholdPercentage().get());
            json.writeBooleanField("propertyValue_circuitBreakerForceOpen",
                    commandProperties.circuitBreakerForceOpen().get());
            json.writeBooleanField("propertyValue_circuitBreakerForceClosed",
                    commandProperties.circuitBreakerForceClosed().get());
            json.writeBooleanField("propertyValue_circuitBreakerEnabled",
                    commandProperties.circuitBreakerEnabled().get());

            json.writeStringField("propertyValue_executionIsolationStrategy",
                    commandProperties.executionIsolationStrategy().get().name());
            json.writeNumberField("propertyValue_executionIsolationThreadTimeoutInMilliseconds",
                    commandProperties.executionIsolationThreadTimeoutInMilliseconds().get());
            json.writeBooleanField("propertyValue_executionIsolationThreadInterruptOnTimeout",
                    commandProperties.executionIsolationThreadInterruptOnTimeout().get());
            json.writeStringField("propertyValue_executionIsolationThreadPoolKeyOverride",
                    commandProperties.executionIsolationThreadPoolKeyOverride().get());
            json.writeNumberField("propertyValue_executionIsolationSemaphoreMaxConcurrentRequests",
                    commandProperties.executionIsolationSemaphoreMaxConcurrentRequests().get());
            json.writeNumberField("propertyValue_fallbackIsolationSemaphoreMaxConcurrentRequests",
                    commandProperties.fallbackIsolationSemaphoreMaxConcurrentRequests().get());

            // TODO
            /*
             * The following are commented out as these rarely change and are verbose
             * for streaming for something people don't change. We could perhaps allow
             * a property or request argument to include these.
             */

            // json.put("propertyValue_metricsRollingPercentileEnabled",
            // commandProperties.metricsRollingPercentileEnabled().get());
            // json.put("propertyValue_metricsRollingPercentileBucketSize",
            // commandProperties.metricsRollingPercentileBucketSize().get());
            // json.put("propertyValue_metricsRollingPercentileWindow",
            // commandProperties.metricsRollingPercentileWindowInMilliseconds().get());
            // json.put("propertyValue_metricsRollingPercentileWindowBuckets",
            // commandProperties.metricsRollingPercentileWindowBuckets().get());
            // json.put("propertyValue_metricsRollingStatisticalWindowBuckets",
            // commandProperties.metricsRollingStatisticalWindowBuckets().get());
            json.writeNumberField("propertyValue_metricsRollingStatisticalWindowInMilliseconds",
                    commandProperties.metricsRollingStatisticalWindowInMilliseconds().get());

            json.writeBooleanField("propertyValue_requestCacheEnabled",
                    commandProperties.requestCacheEnabled().get());
            json.writeBooleanField("propertyValue_requestLogEnabled",
                    commandProperties.requestLogEnabled().get());

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

            json.writeEndObject(); // end data attribute
            json.writeEndObject();
            json.close();

            // output
            this.jsonMetrics.add(jsonString.getBuffer().toString());
        }

        // thread pool metrics
        for (HystrixThreadPoolMetrics threadPoolMetrics : HystrixThreadPoolMetrics.getInstances()) {
            HystrixThreadPoolKey key = threadPoolMetrics.getThreadPoolKey();

            StringWriter jsonString = new StringWriter();
            JsonGenerator json = this.jsonFactory.createGenerator(jsonString);
            json.writeStartObject();

            addServiceData(json, this.registration);
            json.writeObjectFieldStart("data");

            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());
            json.writeNumberField("rollingCountThreadsExecuted",
                    threadPoolMetrics.getRollingCountThreadsExecuted());
            json.writeNumberField("rollingMaxActiveThreads", threadPoolMetrics.getRollingMaxActiveThreads());

            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(); // end of data object
            json.writeEndObject();
            json.close();
            // output to stream
            this.jsonMetrics.add(jsonString.getBuffer().toString());
        }
    } catch (Exception ex) {
        log.error("Error adding metrics to queue", ex);
    }
}