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

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

Introduction

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

Prototype

public final void writeBooleanField(String fieldName, boolean value)
        throws IOException, JsonGenerationException 

Source Link

Document

Convenience method for outputting a field entry ("member") that has a boolean value.

Usage

From source file:org.neo4j.ontology.server.unmanaged.AnnotationResource.java

private void writeJsonNodeObjectifiedObject(JsonGenerator jg, Node term, Label annotationLabel,
        List<Long> dataSetsId) throws IOException {
    jg.writeStartObject(); // {
    jg.writeStringField("uri", term.getProperty("uri").toString()); // uri: "http://www.w3.org/2002/07/owl#Thing"
    jg.writeStringField("ontId", term.getProperty("name").toString()); // ontId: "OWL:Thing"
    jg.writeStringField("label", term.getProperty("rdfs:label", term.getProperty("name")).toString()); // ontId: "OWL:Thing"
    jg.writeFieldName("dataSets"); // dataSets:
    jg.writeStartObject(); // {
    for (Long dataSetId : dataSetsId) {
        jg.writeBooleanField(dataSetId.toString(), true); // 123
    }/*from   ww  w. java2 s. com*/
    jg.writeEndObject(); // }
    writeJsonNodeObjectifiedObjectParents(jg, term, annotationLabel);
    jg.writeEndObject(); // }
}

From source file:org.apache.olingo.commons.core.serialization.JsonPropertySerializer.java

protected void doContainerSerialize(final ResWrap<Property> container, final JsonGenerator jgen)
        throws IOException, EdmPrimitiveTypeException {

    final Property property = container.getPayload();

    jgen.writeStartObject();/*  w  w  w  .  ja  v  a2s .c o m*/

    if (serverMode && container.getContextURL() != null) {
        jgen.writeStringField(version.compareTo(ODataServiceVersion.V40) >= 0 ? Constants.JSON_CONTEXT
                : Constants.JSON_METADATA, container.getContextURL().toASCIIString());
    }

    if (StringUtils.isNotBlank(property.getType())) {
        jgen.writeStringField(version.getJsonName(ODataServiceVersion.JsonKey.TYPE),
                new EdmTypeInfo.Builder().setTypeExpression(property.getType()).build().external(version));
    }

    for (Annotation annotation : property.getAnnotations()) {
        valuable(jgen, annotation, "@" + annotation.getTerm());
    }

    if (property.isNull()) {
        jgen.writeBooleanField(Constants.JSON_NULL, true);
    } else if (property.isPrimitive()) {
        final EdmTypeInfo typeInfo = property.getType() == null ? null
                : new EdmTypeInfo.Builder().setTypeExpression(property.getType()).build();

        jgen.writeFieldName(Constants.VALUE);
        primitiveValue(jgen, typeInfo, property.asPrimitive());
    } else if (property.isEnum()) {
        jgen.writeStringField(Constants.VALUE, property.asEnum().toString());
    } else if (property.isGeospatial() || property.isCollection()) {
        valuable(jgen, property, Constants.VALUE);
    } else if (property.isLinkedComplex()) {
        for (Property cproperty : property.asLinkedComplex().getValue()) {
            valuable(jgen, cproperty, cproperty.getName());
        }
    } else if (property.isComplex()) {
        for (Property cproperty : property.asComplex()) {
            valuable(jgen, cproperty, cproperty.getName());
        }
    }

    jgen.writeEndObject();
}

From source file:com.ntsync.shared.RawContact.java

private static void writeAddress(StringBuilder hashValue, JsonGenerator g, List<RawAddressData> list)
        throws IOException {
    if (list != null) {
        g.writeArrayFieldStart(ContactConstants.STRUCTUREDPOSTAL);
        for (RawAddressData listItem : list) {
            g.writeStartObject();//from www.j  a v a  2s  .  co  m
            g.writeStringField(ContactConstants.TYPE, String.valueOf(listItem.getType().getVal()));
            writeField(g, ContactConstants.LABEL, listItem.getLabel());

            writeField(g, ContactConstants.STREET, listItem.getStreet());
            writeField(g, ContactConstants.POBOX, listItem.getPobox());
            writeField(g, ContactConstants.POSTCODE, listItem.getPostcode());
            writeField(g, ContactConstants.COUNTRY, listItem.getCountry());
            writeField(g, ContactConstants.CITY, listItem.getCity());
            writeField(g, ContactConstants.REGION, listItem.getRegion());
            writeField(g, ContactConstants.NEIGHBORHOOD, listItem.getNeighborhood());

            if (listItem.isSuperPrimary()) {
                g.writeBooleanField(ContactConstants.SUPERPRIMARY, true);
            }
            if (listItem.isPrimary()) {
                g.writeBooleanField(ContactConstants.PRIMARY, true);
            }
            g.writeEndObject();

            hashValue.append(listItem.getStreet());
            hashValue.append(':');
            hashValue.append(listItem.getType().getVal());
        }
        g.writeEndArray();
    }
}

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

private Response nodeUpdateSeed(final String node, final boolean seed) {
    final CassandraFrameworkProtos.CassandraNode cassandraNode = cluster.findNode(node);
    if (cassandraNode == null) {
        return Response.status(404).build();
    }/* w  w  w. jav a 2  s .c  om*/

    try {
        final boolean seedChanged = cluster.setNodeSeed(cassandraNode, seed);

        return JaxRsUtils.buildStreamingResponse(factory, new StreamingJsonResponse() {
            @Override
            public void write(final JsonGenerator json) throws IOException {
                json.writeStringField("ip", cassandraNode.getIp());
                json.writeStringField("hostname", cassandraNode.getHostname());
                if (!cassandraNode.hasCassandraNodeExecutor()) {
                    json.writeNullField("executorId");
                } else {
                    json.writeStringField("executorId",
                            cassandraNode.getCassandraNodeExecutor().getExecutorId());
                }
                json.writeBooleanField("oldSeedState", cassandraNode.getSeed());

                if (seedChanged) {
                    json.writeBooleanField("success", true);
                    json.writeBooleanField("seedState", seed);
                } else {
                    json.writeBooleanField("success", false);
                    json.writeBooleanField("seedState", cassandraNode.getSeed());
                }

            }
        });
    } catch (final SeedChangeException e) {
        return JaxRsUtils.buildStreamingResponse(factory, Response.Status.BAD_REQUEST,
                new StreamingJsonResponse() {
                    @Override
                    public void write(final JsonGenerator json) throws IOException {
                        json.writeStringField("ip", cassandraNode.getIp());
                        json.writeStringField("hostname", cassandraNode.getHostname());
                        if (!cassandraNode.hasCassandraNodeExecutor()) {
                            json.writeNullField("executorId");
                        } else {
                            json.writeStringField("executorId",
                                    cassandraNode.getCassandraNodeExecutor().getExecutorId());
                        }
                        json.writeBooleanField("oldSeedState", cassandraNode.getSeed());

                        json.writeBooleanField("success", false);
                        json.writeStringField("error", e.getMessage());
                    }
                });
    }

}

From source file:org.wso2.carbon.apimgt.tracing.TracingReporter.java

/**
 * Get the structured log message format
 *
 * @param timeStamp timeStamp Instant/* w ww . ja v  a 2  s. c o m*/
 * @param span      opentracing SpanData
 * @return structured log message format String
 * */
private String toStructuredMessage(Instant timeStamp, SpanData span) {
    try {
        StringWriter writer = new StringWriter();
        JsonGenerator generator = this.jsonFactory.createGenerator(writer);
        generator.writeStartObject();
        generator.writeNumberField(TracingConstants.LATENCY,
                Duration.between(span.startAt, timeStamp).toMillis());
        generator.writeStringField(TracingConstants.OPERATION_NAME, span.operationName);
        generator.writeObjectFieldStart(TracingConstants.TAGS);
        Iterator itr = span.tags.entrySet().iterator();

        Map.Entry map;
        Object value;
        while (itr.hasNext()) {
            map = (Map.Entry) itr.next();
            value = map.getValue();
            if (value instanceof String) {
                generator.writeStringField((String) map.getKey(), (String) value);
            } else if (value instanceof Number) {
                generator.writeNumberField((String) map.getKey(), ((Number) value).doubleValue());
            } else if (value instanceof Boolean) {
                generator.writeBooleanField((String) map.getKey(), (Boolean) value);
            }
        }
        generator.writeEndObject();
        generator.close();
        writer.close();
        return writer.toString();
    } catch (IOException e) {
        log.error("Error in structured message", e);
        return null;
    }
}

From source file:pl.selvin.android.syncframework.content.TableInfo.java

public void GetChanges(SQLiteDatabase db, JsonGenerator gen, ArrayList<TableInfo> notifyTableInfo)
        throws IOException {
    String[] cols = new String[columns.length + 3];
    int i = 0;/*from  www. j a v  a2s.c om*/
    for (; i < columns.length; i++)
        cols[i] = columns[i].name;
    cols[i] = _.uri;
    cols[i + 1] = _.tempId;
    cols[i + 2] = _.isDeleted;
    Cursor c = db.query(name, cols, _.isDirtyP, new String[] { "1" }, null, null, null);
    //to fix startPos  > actual rows for large cursors db operations should be done after cursor is closed ...
    final ArrayList<OperationHolder> operations = new ArrayList<OperationHolder>();
    if (c.moveToFirst()) {
        if (!notifyTableInfo.contains(this))
            notifyTableInfo.add(this);
        do {

            gen.writeStartObject();
            gen.writeObjectFieldStart(_.__metadata);
            gen.writeBooleanField(_.isDirty, true);
            gen.writeStringField(_.type, scope_name);
            //Log.d("before", scope_name + ":" + c.getLong(i + 3));
            String uri = c.getString(i);
            //Log.d("after", scope_name + ":" + c.getLong(i + 3));
            if (uri == null) {
                gen.writeStringField(_.tempId, c.getString(i + 1));
            } else {
                gen.writeStringField(_.uri, uri);
                final ContentValues update = new ContentValues(1);
                update.put(_.isDirty, 0);
                operations.add(new OperationHolder(name, OperationHolder.UPDATE, update, uri));
            }
            boolean isDeleted = c.getInt(i + 2) == 1;
            if (isDeleted) {
                gen.writeBooleanField(_.isDeleted, true);
                gen.writeEndObject();// meta
                operations.add(new OperationHolder(name, OperationHolder.DELETE, null, uri));
            } else {
                gen.writeEndObject();// meta
                for (i = 0; i < columns.length; i++) {
                    if (columns[i].nullable && c.isNull(i)) {
                        gen.writeNullField(columns[i].name);
                    } else {
                        switch (columns[i].type) {
                        case ColumnType.BLOB:
                            gen.writeBinaryField(columns[i].name, c.getBlob(i));
                            break;
                        case ColumnType.BOOLEAN:
                            gen.writeBooleanField(columns[i].name, c.getLong(i) == 1);
                            break;
                        case ColumnType.INTEGER:
                            gen.writeNumberField(columns[i].name, c.getLong(i));
                            break;
                        case ColumnType.DATETIME:
                            try {
                                gen.writeStringField(columns[i].name,
                                        String.format(msdate, sdf.parse(c.getString(i)).getTime()));
                            } catch (Exception e) {
                                if (BuildConfig.DEBUG) {
                                    Log.e("ListSync", e.getLocalizedMessage());
                                }
                            }
                            break;
                        case ColumnType.NUMERIC:
                            gen.writeNumberField(columns[i].name, c.getDouble(i));
                            break;
                        default:
                            gen.writeStringField(columns[i].name, c.getString(i));
                            break;
                        }
                    }
                }
            }
            gen.writeEndObject(); // end of row
        } while (c.moveToNext());
    }
    c.close();
    for (OperationHolder operation : operations)
        operation.execute(db);
}

From source file:tds.student.web.controls.dummy.GlobalJavascriptWriter.java

public void writeBrowserInfo() throws JsonGenerationException, IOException {
    StringWriter sw = new StringWriter();
    JsonFactory jsonFactory = new JsonFactory();
    JsonGenerator jsonWriter = jsonFactory.createGenerator(sw);

    jsonWriter.writeStartObject();// {

    // browser info
    BrowserParser browser = new BrowserParser();
    jsonWriter.writeStringField("userAgent", browser.getUserAgent());
    jsonWriter.writeStringField("osLabel", browser.getOSFullName());
    jsonWriter.writeStringField("osName", String.valueOf(browser.getOsName()));
    jsonWriter.writeNumberField("osVersion", browser.getVersion());
    jsonWriter.writeStringField("architecture", browser.getHardwareArchitecture());
    jsonWriter.writeStringField("name", browser.getName());
    jsonWriter.writeNumberField("version", browser.getVersion());
    jsonWriter.writeBooleanField("isSecure", browser.isSecureBrowser());

    String label;//from  w w w .j a v a 2 s .c  om
    if (browser.isSecureBrowser())
        label = String.format("Secure v%s", "" + browser.getVersion());
    else
        label = String.format("%s v%s", browser.getName(), "" + browser.getVersion());
    jsonWriter.writeStringField("label", label);

    jsonWriter.writeEndObject(); // }
    jsonWriter.close();
    // TODO shiva: do we need to do sw.getBuffer () below.
    _writer.write(String.format("TDS.BrowserInfo = %s; ", sw.getBuffer().toString()));
    _writer.write("\n\r");
}

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

@Scheduled(fixedRateString = "${hystrix.stream.amqp.gatherRate:500}")
public void gatherMetrics() {
    try {//from   w ww  . ja  v  a2s.c o  m
        // 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  . j  ava  2 s. co  m
        // 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);
    }
}