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:net.opentsdb.meta.UIDMeta.java

/**
 * Formats the JSON output for writing to storage. It drops objects we don't
 * need or want to store (such as the UIDMeta objects or the total dps) to
 * save space. It also serializes in order so that we can make a proper CAS
 * call. Otherwise the POJO serializer may place the fields in any order
 * and CAS calls would fail all the time.
 * @return A byte array to write to storage
 *///  w ww.  j  a  va 2s .  c o  m
private byte[] getStorageJSON() {
    // 256 bytes is a good starting value, assumes default info
    final ByteArrayOutputStream output = new ByteArrayOutputStream(256);
    try {
        final JsonGenerator json = JSON.getFactory().createGenerator(output);
        json.writeStartObject();
        json.writeStringField("type", type.toString());
        json.writeStringField("displayName", display_name);
        json.writeStringField("description", description);
        json.writeStringField("notes", notes);
        json.writeNumberField("created", created);
        if (custom == null) {
            json.writeNullField("custom");
        } else {
            json.writeObjectFieldStart("custom");
            for (Map.Entry<String, String> entry : custom.entrySet()) {
                json.writeStringField(entry.getKey(), entry.getValue());
            }
            json.writeEndObject();
        }

        json.writeEndObject();
        json.close();
        return output.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException("Unable to serialize UIDMeta", e);
    }
}

From source file:com.arpnetworking.logback.jackson.RedactionFilter.java

/**
 * {@inheritDoc}//from w w w  . j a  va 2  s .  c om
 */
@Override
public void serializeAsField(final Object pojo, final JsonGenerator jgen, final SerializerProvider prov,
        final PropertyWriter writer) throws Exception {
    if (writer instanceof BeanPropertyWriter) {
        final BeanPropertyWriter beanPropertyWriter = (BeanPropertyWriter) writer;
        if (beanPropertyWriter.getAnnotation(LogRedact.class) == null) {
            super.serializeAsField(pojo, jgen, prov, writer);
        } else {
            if (_allowNull && beanPropertyWriter.get(pojo) == null) {
                super.serializeAsField(pojo, jgen, prov, writer);
            } else {
                jgen.writeStringField(beanPropertyWriter.getSerializedName().getValue(), REDACTION_STRING);
            }
        }
    } else {
        super.serializeAsField(pojo, jgen, prov, writer);
    }
}

From source file:com.greplin.gec.GecLogbackAppender.java

/**
 * Writes a formatted exception to the given writer.
 *
 * @param message   the log message/*from  w ww. j  a  v a 2 s  .  c  om*/
 * @param throwableProxy the exception
 * @param level     the error level
 * @param out       the destination
 * @throws IOException if there are IO errors in the destination
 */
private void writeFormattedException(final String message, final IThrowableProxy throwableProxy,
        final Level level, final Writer out) throws IOException {
    JsonGenerator generator = new JsonFactory().createJsonGenerator(out);

    IThrowableProxy rootThrowable = throwableProxy;
    while (this.passthroughExceptions.contains(rootThrowable.getClassName())
            && rootThrowable.getCause() != null) {
        rootThrowable = rootThrowable.getCause();
    }

    generator.writeStartObject();
    generator.writeStringField("project", this.project);
    generator.writeStringField("environment", this.environment);
    generator.writeStringField("serverName", this.serverName);
    // FIXME this was 'throwable'
    generator.writeStringField("backtrace", getStackTrace(rootThrowable));
    generator.writeStringField("message", rootThrowable.getMessage());
    generator.writeStringField("logMessage", message);
    generator.writeStringField("type", rootThrowable.getClassName());
    if (level != Level.ERROR) {
        generator.writeStringField("errorLevel", level.toString());
    }
    writeContext(generator);
    generator.writeEndObject();
    generator.close();
}

From source file:io.mesosphere.mesos.frameworks.cassandra.scheduler.api.NodeController.java

/**
 * Submit intent to replace the already terminated node specified using the path parameter `node`.
 * The `node` parameter can be either the IP address, the hostname or the executor ID.
 * The request must be submitted using HTTP method `POST`.
 *//*from   www.  ja va2  s.  co m*/
@POST
@Path("/{node}/replace")
public Response nodeReplace(@PathParam("node") final String node) {
    final CassandraFrameworkProtos.CassandraNode cassandraNode = cluster.findNode(node);

    if (cassandraNode == null) {
        return JaxRsUtils.buildStreamingResponse(factory, Response.Status.NOT_FOUND,
                new StreamingJsonResponse() {
                    @Override
                    public void write(final JsonGenerator json) throws IOException {
                        json.writeBooleanField("success", false);
                        json.writeStringField("reason", "No such node");
                    }
                });
    }

    try {
        cluster.replaceNode(node);
    } catch (final ReplaceNodePreconditionFailed replaceNodePreconditionFailed) {
        return JaxRsUtils.buildStreamingResponse(factory, Response.Status.BAD_REQUEST,
                new StreamingJsonResponse() {
                    @Override
                    public void write(final JsonGenerator json) throws IOException {
                        json.writeStringField("ipToReplace", cassandraNode.getIp());
                        json.writeBooleanField("success", false);
                        json.writeStringField("reason", "No such node");
                    }
                });
    }

    return JaxRsUtils.buildStreamingResponse(factory, new StreamingJsonResponse() {
        @Override
        public void write(final JsonGenerator json) throws IOException {
            json.writeStringField("ipToReplace", cassandraNode.getIp());
            json.writeBooleanField("success", true);
            json.writeStringField("hostname", cassandraNode.getHostname());
            json.writeStringField("targetRunState", cassandraNode.getTargetRunState().name());
        }
    });
}

From source file:com.baidubce.services.bmr.BmrClient.java

/**
 * Create a cluster with the specified options.
 *
 * @param request The request containing all options for creating a BMR cluster.
 * @return The response containing the ID of the newly created cluster.
 *///from www  .j a v a2 s .co m
public CreateClusterResponse createCluster(CreateClusterRequest request) {
    checkNotNull(request, "request should not be null.");
    checkStringNotEmpty(request.getImageType(), "The imageType should not be null or empty string.");
    checkStringNotEmpty(request.getImageVersion(), "The imageVersion should not be null or empty string.");
    checkNotNull(request.getInstanceGroups(), "The instanceGroups should not be null.");

    StringWriter writer = new StringWriter();
    try {
        JsonGenerator jsonGenerator = JsonUtils.jsonGeneratorOf(writer);
        jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField("imageType", request.getImageType());
        jsonGenerator.writeStringField("imageVersion", request.getImageVersion());
        jsonGenerator.writeArrayFieldStart("instanceGroups");
        for (InstanceGroupConfig instanceGroup : request.getInstanceGroups()) {
            jsonGenerator.writeStartObject();
            if (instanceGroup.getName() != null) {
                jsonGenerator.writeStringField("name", instanceGroup.getName());
            }
            jsonGenerator.writeStringField("type", instanceGroup.getType());
            jsonGenerator.writeStringField("instanceType", instanceGroup.getInstanceType());
            jsonGenerator.writeNumberField("instanceCount", instanceGroup.getInstanceCount());
            jsonGenerator.writeEndObject();
        }
        jsonGenerator.writeEndArray();
        if (request.getName() != null) {
            jsonGenerator.writeStringField("name", request.getName());
        }
        if (request.getLogUri() != null) {
            jsonGenerator.writeStringField("logUri", request.getLogUri());
        }
        jsonGenerator.writeBooleanField("autoTerminate", request.getAutoTerminate());

        if (request.getApplications() != null) {
            jsonGenerator.writeArrayFieldStart("applications");
            for (ApplicationConfig application : request.getApplications()) {
                jsonGenerator.writeStartObject();
                jsonGenerator.writeStringField("name", application.getName());
                jsonGenerator.writeStringField("version", application.getVersion());
                if (application.getProperties() != null) {
                    jsonGenerator.writeObjectFieldStart("properties");
                    for (Map.Entry<String, Object> entry : application.getProperties().entrySet()) {
                        jsonGenerator.writeObjectField(entry.getKey(), entry.getValue());
                    }
                    jsonGenerator.writeEndObject();
                }
                jsonGenerator.writeEndObject();
            }
            jsonGenerator.writeEndArray();
        }

        if (request.getSteps() != null) {
            jsonGenerator.writeArrayFieldStart("steps");
            for (StepConfig step : request.getSteps()) {
                jsonGenerator.writeStartObject();
                if (step.getName() != null) {
                    jsonGenerator.writeStringField("name", step.getName());
                }
                jsonGenerator.writeStringField("type", step.getType());
                jsonGenerator.writeStringField("actionOnFailure", step.getActionOnFailure());
                jsonGenerator.writeObjectFieldStart("properties");
                for (Map.Entry<String, String> entry : step.getProperties().entrySet()) {
                    jsonGenerator.writeStringField(entry.getKey(), entry.getValue());
                }
                jsonGenerator.writeEndObject();
                jsonGenerator.writeEndObject();
            }
            jsonGenerator.writeEndArray();
        }

        jsonGenerator.writeEndObject();
        jsonGenerator.close();
    } catch (IOException e) {
        throw new BceClientException("Fail to generate json", e);
    }

    byte[] json = null;
    try {
        json = writer.toString().getBytes(DEFAULT_ENCODING);
    } catch (UnsupportedEncodingException e) {
        throw new BceClientException("Fail to get UTF-8 bytes", e);
    }

    InternalRequest internalRequest = this.createRequest(request, HttpMethodName.POST, CLUSTER);
    internalRequest.addHeader(Headers.CONTENT_LENGTH, String.valueOf(json.length));
    internalRequest.addHeader(Headers.CONTENT_TYPE, "application/json");
    internalRequest.setContent(RestartableInputStream.wrap(json));

    if (request.getClientToken() != null) {
        internalRequest.addParameter("clientToken", request.getClientToken());
    }

    return this.invokeHttpClient(internalRequest, CreateClusterResponse.class);
}

From source file:org.canova.api.conf.Configuration.java

/**
 *  Writes out all the parameters and their properties (final and resource) to
 *  the given {@link Writer}//from  w ww.  j av a2  s .c  o m
 *  The format of the output would be
 *  { "properties" : [ {key1,value1,key1.isFinal,key1.resource}, {key2,value2,
 *  key2.isFinal,key2.resource}... ] }
 *  It does not output the parameters of the configuration object which is
 *  loaded from an input stream.
 * @param out the Writer to write to
 * @throws IOException
 */
public static void dumpConfiguration(Configuration conf, Writer out) throws IOException {
    Configuration config = new Configuration(conf, true);
    config.reloadConfiguration();
    JsonFactory dumpFactory = new JsonFactory();
    JsonGenerator dumpGenerator = dumpFactory.createGenerator(out);
    dumpGenerator.writeStartObject();
    dumpGenerator.writeFieldName("properties");
    dumpGenerator.writeStartArray();
    dumpGenerator.flush();
    for (Map.Entry<Object, Object> item : config.getProps().entrySet()) {
        dumpGenerator.writeStartObject();
        dumpGenerator.writeStringField("key", (String) item.getKey());
        dumpGenerator.writeStringField("value", config.get((String) item.getKey()));
        dumpGenerator.writeBooleanField("isFinal", config.finalParameters.contains(item.getKey()));
        dumpGenerator.writeStringField("resource", config.updatingResource.get(item.getKey()));
        dumpGenerator.writeEndObject();
    }
    dumpGenerator.writeEndArray();
    dumpGenerator.writeEndObject();
    dumpGenerator.flush();
}

From source file:com.palominolabs.crm.sf.rest.HttpApiClient.java

@Nonnull
private String getSObjectFieldsAsJson(@Nonnull SObject sObject) throws IOException {
    StringWriter writer = new StringWriter();
    JsonGenerator jsonGenerator = this.objectMapper.getFactory().createGenerator(writer);

    jsonGenerator.writeStartObject();//w w w .j  a  va2  s .c  o m

    for (Map.Entry<String, String> entry : sObject.getAllFields().entrySet()) {
        if (entry.getValue() == null) {
            jsonGenerator.writeNullField(entry.getKey());
        } else {
            jsonGenerator.writeStringField(entry.getKey(), entry.getValue());
        }
    }

    jsonGenerator.writeEndObject();
    jsonGenerator.close();

    writer.close();

    return writer.toString();
}

From source file:com.googlecode.jmxtrans.model.output.LibratoWriter2.java

@Override
public void write(@Nonnull Writer writer, @Nonnull Server server, @Nonnull Query query,
        @Nonnull Iterable<Result> results) throws IOException {
    Closer closer = Closer.create();/*from  w w  w  . j a  v  a  2 s .c  o  m*/
    try {
        JsonGenerator g = closer.register(jsonFactory.createGenerator(writer));
        g.writeStartObject();
        g.writeArrayFieldStart("counters");
        g.writeEndArray();

        String source = getSource(server);

        g.writeArrayFieldStart("gauges");
        for (Result result : results) {
            Map<String, Object> resultValues = result.getValues();
            for (Map.Entry<String, Object> values : resultValues.entrySet()) {
                if (isNumeric(values.getValue())) {
                    g.writeStartObject();
                    g.writeStringField("name", KeyUtils.getKeyString(query, result, values, typeNames));
                    if (source != null && !source.isEmpty()) {
                        g.writeStringField("source", source);
                    }
                    g.writeNumberField("measure_time", SECONDS.convert(result.getEpoch(), MILLISECONDS));
                    Object value = values.getValue();
                    if (value instanceof Integer) {
                        g.writeNumberField("value", (Integer) value);
                    } else if (value instanceof Long) {
                        g.writeNumberField("value", (Long) value);
                    } else if (value instanceof Float) {
                        g.writeNumberField("value", (Float) value);
                    } else if (value instanceof Double) {
                        g.writeNumberField("value", (Double) value);
                    }
                    g.writeEndObject();
                }
            }
        }
        g.writeEndArray();
        g.writeEndObject();
        g.flush();
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}

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

private void writeHydraVariableMapping(JsonGenerator jgen, @Nullable ActionDescriptor actionDescriptor,
        Collection<String> variableNames) throws IOException {
    for (String requestParamName : variableNames) {
        jgen.writeStartObject();/*  w  w  w. ja va2  s  . c o  m*/
        jgen.writeStringField("@type", "hydra:IriTemplateMapping");
        jgen.writeStringField("hydra:variable", requestParamName);
        if (actionDescriptor != null) {
            jgen.writeBooleanField("hydra:required",
                    actionDescriptor.getActionInputParameter(requestParamName).isRequired());
            jgen.writeStringField("hydra:property",
                    getExposedPropertyOrParamName(actionDescriptor.getActionInputParameter(requestParamName)));
        }
        jgen.writeEndObject();
    }
}

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

@Scheduled(fixedRateString = "${hystrix.stream.amqp.gatherRate:500}")
public void gatherMetrics() {
    try {//from   w  w w .j  a v 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);
    }
}