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

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

Introduction

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

Prototype

public final void writeObjectFieldStart(String fieldName) throws IOException, JsonGenerationException 

Source Link

Document

Convenience method for outputting a field entry ("member") (that will contain a JSON Object value), and the START_OBJECT marker.

Usage

From source file:de.escalon.hypermedia.hydra.serialize.JacksonHydraSerializer.java

private void serializeContext(Object bean, JsonGenerator jgen, SerializerProvider serializerProvider,
        Deque<String> deque) throws IOException {
    try {//from w  w  w .j  a  v a 2  s  . c o  m
        // TODO use serializerProvider.getAttributes to hold a stack of contexts
        // and check if we need to write a context for the current bean at all
        // If it is in the same vocab: no context
        // If the terms are already defined in the context: no context

        SerializationConfig config = serializerProvider.getConfig();
        final Class<?> mixInClass = config.findMixInClassFor(bean.getClass());

        String vocab = getVocab(bean, mixInClass);
        Map<String, Object> terms = getTerms(bean, mixInClass);

        final String currentVocab = deque.peek();

        deque.push(vocab);
        boolean mustWriteContext;
        if (currentVocab == null || !vocab.equals(currentVocab)) {
            mustWriteContext = true;
        } else {
            // only write if bean has terms
            if (terms.isEmpty()) {
                mustWriteContext = false;
            } else {
                // TODO actually, need not repeat vocab in context if same
                mustWriteContext = true;
            }
        }

        if (mustWriteContext) {
            // begin context
            // default context: schema.org vocab or vocab package annotation
            jgen.writeObjectFieldStart("@context");
            // TODO do not repeat vocab if already defined in current context
            if (currentVocab == null || !vocab.equals(currentVocab)) {
                jgen.writeStringField(AT_VOCAB, vocab);
            }

            for (Map.Entry<String, Object> termEntry : terms.entrySet()) {
                if (termEntry.getValue() instanceof String) {
                    jgen.writeStringField(termEntry.getKey(), termEntry.getValue().toString());
                } else {
                    jgen.writeObjectField(termEntry.getKey(), termEntry.getValue());
                }
            }

            jgen.writeEndObject();
        }

        // end context

        // TODO build the context from @Vocab and @Term and @Expose and write it as local or external context with
        // TODO jsonld extension (using apt?)
        // TODO also allow manually created jsonld contexts
        // TODO how to define a context containing several context objects? @context is then an array of
        // TODO external context strings pointing to json-ld, and json objects containing terms
        // TODO another option: create custom vocabulary without reference to public vocabs
        // TODO support additionalType from goodrelations
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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

@Override
public void serialize(List<Link> links, JsonGenerator jgen, SerializerProvider serializerProvider)
        throws IOException {

    try {//from ww w  .ja  v a2s .  c o m
        Collection<Link> simpleLinks = new ArrayList<Link>();
        Collection<Affordance> affordances = new ArrayList<Affordance>();
        Collection<Link> templatedLinks = new ArrayList<Link>();
        Collection<Affordance> templatedAffordances = new ArrayList<Affordance>();
        for (Link link : links) {
            if (link instanceof Affordance) {
                final Affordance affordance = (Affordance) link;
                final List<ActionDescriptor> actionDescriptors = affordance.getActionDescriptors();
                if (!actionDescriptors.isEmpty()) {
                    if (affordance.isTemplated()) {
                        templatedAffordances.add(affordance);
                    } else {
                        affordances.add(affordance);
                    }
                } else {
                    if (affordance.isTemplated()) {
                        templatedLinks.add(affordance);
                    } else {
                        simpleLinks.add(affordance);
                    }
                }
            } else if (link.isTemplated()) {
                templatedLinks.add(link);
            } else {
                simpleLinks.add(link);
            }
        }

        for (Affordance templatedAffordance : templatedAffordances) {
            jgen.writeObjectFieldStart(templatedAffordance.getRel());

            jgen.writeStringField("@type", "hydra:IriTemplate");
            jgen.writeStringField("hydra:template", templatedAffordance.getHref());
            final List<ActionDescriptor> actionDescriptors = templatedAffordance.getActionDescriptors();
            ActionDescriptor actionDescriptor = actionDescriptors.get(0);
            jgen.writeArrayFieldStart("hydra:mapping");
            writeHydraVariableMapping(jgen, actionDescriptor, actionDescriptor.getPathVariableNames());
            writeHydraVariableMapping(jgen, actionDescriptor, actionDescriptor.getRequestParamNames());
            jgen.writeEndArray();

            jgen.writeEndObject();
        }
        for (Link templatedLink : templatedLinks) {
            // we only have the template, no access to method params
            jgen.writeObjectFieldStart(templatedLink.getRel());

            jgen.writeStringField("@type", "hydra:IriTemplate");
            jgen.writeStringField("hydra:template", templatedLink.getHref());

            jgen.writeArrayFieldStart("hydra:mapping");
            writeHydraVariableMapping(jgen, null, templatedLink.getVariableNames());
            jgen.writeEndArray();

            jgen.writeEndObject();
        }

        Deque<String> vocabStack = (Deque<String>) serializerProvider
                .getAttribute(JacksonHydraSerializer.KEY_LD_CONTEXT);
        String currentVocab = vocabStack != null ? vocabStack.peek() : null;

        for (Affordance affordance : affordances) {
            final String rel = affordance.getRel();
            List<ActionDescriptor> actionDescriptors = affordance.getActionDescriptors();
            if (!actionDescriptors.isEmpty()) {
                if (!Link.REL_SELF.equals(rel)) {
                    jgen.writeObjectFieldStart(rel); // begin rel
                }
                jgen.writeStringField(JacksonHydraSerializer.AT_ID, affordance.getHref());
                jgen.writeArrayFieldStart("hydra:operation");
            }

            for (ActionDescriptor actionDescriptor : actionDescriptors) {
                jgen.writeStartObject(); // begin a hydra:Operation

                final String semanticActionType = actionDescriptor.getSemanticActionType();
                if (semanticActionType != null) {
                    jgen.writeStringField("@type", semanticActionType);
                }
                jgen.writeStringField("hydra:method", actionDescriptor.getHttpMethod().name());

                final ActionInputParameter requestBodyInputParameter = actionDescriptor.getRequestBody();
                if (requestBodyInputParameter != null) {

                    jgen.writeObjectFieldStart("hydra:expects"); // begin hydra:expects

                    final Class<?> clazz = requestBodyInputParameter.getNestedParameterType();
                    final Expose classExpose = clazz.getAnnotation(Expose.class);
                    final String typeName;
                    if (classExpose != null) {
                        typeName = classExpose.value();
                    } else {
                        typeName = requestBodyInputParameter.getNestedParameterType().getSimpleName();
                    }
                    jgen.writeStringField("@type", typeName);

                    jgen.writeArrayFieldStart("hydra:supportedProperty"); // begin hydra:supportedProperty
                    // TODO check need for actionDescriptor and requestBodyInputParameter here:
                    recurseSupportedProperties(jgen, currentVocab, clazz, actionDescriptor,
                            requestBodyInputParameter, requestBodyInputParameter.getCallValue());
                    jgen.writeEndArray(); // end hydra:supportedProperty

                    jgen.writeEndObject(); // end hydra:expects
                }

                jgen.writeEndObject(); // end hydra:Operation
            }

            if (!actionDescriptors.isEmpty()) {
                jgen.writeEndArray(); // end hydra:operation

                if (!Link.REL_SELF.equals(rel)) {
                    jgen.writeEndObject(); // end rel
                }
            }
        }

        for (Link simpleLink : simpleLinks) {
            final String rel = simpleLink.getRel();
            if (Link.REL_SELF.equals(rel)) {
                jgen.writeStringField("@id", simpleLink.getHref());
            } else {
                String linkAttributeName = IanaRels.isIanaRel(rel) ? IANA_REL_PREFIX + rel : rel;
                jgen.writeObjectFieldStart(linkAttributeName);
                jgen.writeStringField("@id", simpleLink.getHref());
                jgen.writeEndObject();
            }
        }
    } catch (IntrospectionException e) {
        throw new RuntimeException(e);
    }
}

From source file:de.escalon.hypermedia.spring.hydra.PagedResourcesSerializer.java

@Override
public void serialize(PagedResources pagedResources, JsonGenerator jgen, SerializerProvider serializerProvider)
        throws IOException {

    final SerializationConfig config = serializerProvider.getConfig();
    JavaType javaType = config.constructType(pagedResources.getClass());

    JsonSerializer<Object> serializer = BeanSerializerFactory.instance.createSerializer(serializerProvider,
            javaType);/*  w  ww  .  j a v  a  2s .  co m*/

    // replicate pretty much everything from JacksonHydraSerializer
    // since we must reorganize the internals of pagedResources to get a hydra collection
    // with partial page view, we have to serialize pagedResources with an
    // unwrapping serializer
    Deque<LdContext> contextStack = (Deque<LdContext>) serializerProvider.getAttribute(KEY_LD_CONTEXT);
    if (contextStack == null) {
        contextStack = new ArrayDeque<LdContext>();
        serializerProvider.setAttribute(KEY_LD_CONTEXT, contextStack);
    }

    // TODO: filter next/previous/first/last from link list - maybe create new PagedResources without them?
    List<Link> links = pagedResources.getLinks();
    List<Link> filteredLinks = new ArrayList<Link>();
    for (Link link : links) {
        String rel = link.getRel();
        if (navigationRels.contains(rel)) {
            continue;
        } else {
            filteredLinks.add(link);
        }
    }

    PagedResources toRender = new PagedResources(pagedResources.getContent(), pagedResources.getMetadata(),
            filteredLinks);

    jgen.writeStartObject();

    serializeContext(toRender, jgen, serializerProvider, contextStack);

    jgen.writeStringField(JsonLdKeywords.AT_TYPE, "hydra:Collection");

    // serialize with PagedResourcesMixin
    serializer.unwrappingSerializer(NameTransformer.NOP).serialize(toRender, jgen, serializerProvider);

    PagedResources.PageMetadata metadata = pagedResources.getMetadata();
    jgen.writeNumberField("hydra:totalItems", metadata.getTotalElements());

    // begin hydra:view
    jgen.writeObjectFieldStart("hydra:view");
    jgen.writeStringField(JsonLdKeywords.AT_TYPE, "hydra:PartialCollectionView");
    writeRelLink(pagedResources, jgen, Link.REL_NEXT);
    writeRelLink(pagedResources, jgen, "previous");
    // must also translate prev to its synonym previous
    writeRelLink(pagedResources, jgen, Link.REL_PREVIOUS, "previous");
    writeRelLink(pagedResources, jgen, Link.REL_FIRST);
    writeRelLink(pagedResources, jgen, Link.REL_LAST);
    jgen.writeEndObject();
    // end hydra:view

    jgen.writeEndObject();

    contextStack = (Deque<LdContext>) serializerProvider.getAttribute(KEY_LD_CONTEXT);
    if (!contextStack.isEmpty()) {
        contextStack.pop();
    }

}

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 w  w  w  .java2  s .  c o 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:de.escalon.hypermedia.spring.de.escalon.hypermedia.spring.jackson.LinkListSerializer.java

private void recurseSupportedProperties(JsonGenerator jgen, String currentVocab, Class<?> beanType,
        ActionDescriptor actionDescriptor, ActionInputParameter actionInputParameter, Object currentCallValue)
        throws IntrospectionException, IOException {
    // TODO support Option provider by other method args?
    final BeanInfo beanInfo = Introspector.getBeanInfo(beanType);
    final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    // TODO collection and map

    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        final Method writeMethod = propertyDescriptor.getWriteMethod();
        if (writeMethod == null) {
            continue;
        }//from  w ww.  j  a  v a  2  s  .  com
        final Class<?> propertyType = propertyDescriptor.getPropertyType();
        // TODO: the property name must be a valid URI - need to check context for terms?
        String propertyName = getWritableExposedPropertyOrPropertyName(propertyDescriptor);
        if (DataType.isScalar(propertyType)) {

            final Property property = new Property(beanType, propertyDescriptor.getReadMethod(),
                    propertyDescriptor.getWriteMethod(), propertyDescriptor.getName());

            Object propertyValue = getPropertyValue(currentCallValue, propertyDescriptor);

            ActionInputParameter propertySetterInputParameter = new ActionInputParameter(
                    new MethodParameter(propertyDescriptor.getWriteMethod(), 0), propertyValue);
            final Object[] possiblePropertyValues = actionInputParameter.getPossibleValues(property,
                    actionDescriptor);

            writeSupportedProperty(jgen, currentVocab, propertySetterInputParameter, propertyName, property,
                    possiblePropertyValues);
        } else {
            jgen.writeStartObject();
            jgen.writeStringField("hydra:property", propertyName);
            // TODO: is the property required -> for bean props we need the Access annotation to express that
            jgen.writeObjectFieldStart(getPropertyOrClassNameInVocab(currentVocab, "rangeIncludes",
                    JacksonHydraSerializer.HTTP_SCHEMA_ORG, "schema:"));
            Expose expose = AnnotationUtils.getAnnotation(propertyType, Expose.class);
            String subClass;
            if (expose != null) {
                subClass = expose.value();
            } else {
                subClass = propertyType.getSimpleName();
            }
            jgen.writeStringField(getPropertyOrClassNameInVocab(currentVocab, "subClassOf",
                    "http://www.w3.org/2000/01/rdf-schema#", "rdfs:"), subClass);

            jgen.writeArrayFieldStart("hydra:supportedProperty");

            Object propertyValue = getPropertyValue(currentCallValue, propertyDescriptor);

            recurseSupportedProperties(jgen, currentVocab, propertyType, actionDescriptor, actionInputParameter,
                    propertyValue);
            jgen.writeEndArray();

            jgen.writeEndObject();
            jgen.writeEndObject();
        }
    }
}

From source file:org.n52.tamis.core.json.serialize.processes.execute.ExtendedExecuteHttpPostBodySerializer.java

@Override
public void serialize(Execute_HttpPostBody executeBody_short, JsonGenerator jsonGenerator,
        SerializerProvider serProvider) throws IOException, JsonProcessingException {

    logger.info("Start serialization of execute HTTP POST input body \"{}\"", executeBody_short);

    /*//ww w . java  2s.  c o m
     * the structure of the target JSON body looks like:
     * 
     * {
    "Execute": {
      "Identifier": "org.n52.tamis.algorithm.interpolation",
      "Input": [
    {
        "Input": [
            {
                "Reference": {
                    "_href": "http://fluggs.wupperverband.de/sos2/service?service=SOS&request=GetObservation&version=2.0.0&offering=Zeitreihen_2m_Tiefe&observedProperty=Grundwasserstand&responseFormat=http%3A//www.opengis.net/om/2.0",
                    "_mimeType": "application/om+xml; version=2.0",
                    "_schema": "http://schemas.opengis.net/om/2.0/observation.xsd"
                },
                "_id": "gw1"
            },
            {
                "Reference": {
                    "_href": "http://fluggs.wupperverband.de/sos2/service?service=SOS&request=GetObservation&version=2.0.0&offering=Zeitreihen_2m_Tiefe&observedProperty=Sohlenwasserdruck&responseFormat=http%3A//www.opengis.net/om/2.0",
                    "_mimeType": "application/om+xml; version=2.0",
                    "_schema": "http://schemas.opengis.net/om/2.0/observation.xsd"
                },
                "_id": "swd1"
            }
        ],
        "_id": "input-variables"
    },
    {
        "Data": {
            "_mimeType": "text/xml",
            "_schema": "http://schemas.opengis.net/gml/3.2.1/base/feature.xsd",
            "__text": "<wfs:FeatureCollection xmlns:testbed11="http://opengeospatial.org"
    xmlns:wfs="http://www.opengis.net/wfs" xmlns:gml="http://www.opengis.net/gml"
    xmlns:ogc="http://www.opengis.net/ogc" xmlns:ows="http://www.opengis.net/ows"
    xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:wml2="http://www.opengis.net/waterml/2.0" xmlns:sf="http://www.opengis.net/sampling/2.0"
    xmlns:sams="http://www.opengis.net/samplingSpatial/2.0"
    numberOfFeatures="1" timeStamp="2016-02-15T16:24:55.640Z"
    xsi:schemaLocation="http://www.opengis.net/wfs http://geoprocessing.demo.52north.org:8080/geoserver/schemas/wfs/1.1.0/wfs.xsd">
    <gml:featureMembers>
       <wml2:MonitoringPoint gml:id="xyz.1">
          <gml:identifier codeSpace="http://www.opengis.net/def/nil/OGC/0/unknown">xyz</gml:identifier>
          <gml:name codeSpace="http://www.opengis.net/def/nil/OGC/0/unknown">xyz</gml:name>
          <sf:sampledFeature xlink:href="urn:ogc:def:nil:OGC:unknown" />
          <sams:shape>
             <ns:Point xmlns:ns="http://www.opengis.net/gml/3.2"
                ns:id="point_xyz">
                <ns:pos srsName="http://www.opengis.net/def/crs/EPSG/0/31466">5668202.8356 2595842.8958</ns:pos>
             </ns:Point>
          </sams:shape>
       </wml2:MonitoringPoint>
    </gml:featureMembers>
       </wfs:FeatureCollection>"
        },
        "_id": "target-variable-point"
    }
      ],
      "output": {
    "_mimeType": "application/om+xml; version=2.0",
    "_schema": "http://schemas.opengis.net/om/2.0/observation.xsd",
    "_id": "estimated-values",
    "_transmission": "value"
      }, 
      "_service": "WPS",
      "_version": "2.0.0"}
    }
     */

    jsonGenerator.writeStartObject();

    jsonGenerator.writeObjectFieldStart("Execute");

    jsonGenerator.writeStringField("Identifier", executeBody_short.getProcessId());

    jsonGenerator.writeArrayFieldStart("Input");

    List<ExecuteInput> inputs = executeBody_short.getInputs();

    for (ExecuteInput executeInput : inputs) {
        jsonGenerator.writeObject(executeInput);
    }

    jsonGenerator.writeEndArray();

    /**
     * TODO is it really correct, that "output" starts with a small "o"?
     */
    jsonGenerator.writeArrayFieldStart("output");

    List<ExecuteOutput> outputs = executeBody_short.getOutputs();

    for (ExecuteOutput executeOutput : outputs) {
        jsonGenerator.writeObject(executeOutput);
    }

    jsonGenerator.writeEndArray();

    jsonGenerator.writeStringField("_service", Execute_HttpPostBody.service);

    jsonGenerator.writeStringField("_version", executeBody_short.getVersion());

    jsonGenerator.writeEndObject();

    jsonGenerator.writeEndObject();

    logger.info("Serialization of execute HTTP POST input body ended.");
}

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

private static void writeCommandMetrics(final HystrixCommandMetrics commandMetrics, JsonGenerator json)
        throws IOException {
    HystrixCommandKey key = commandMetrics.getCommandKey();
    HystrixCircuitBreaker circuitBreaker = HystrixCircuitBreaker.Factory.getInstance(key);

    json.writeStartObject();/*from  ww w  . ja v a  2 s  .co m*/
    json.writeStringField("type", "HystrixCommand");
    json.writeStringField("name", key.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
    safelyWriteNumberField(json, "rollingCountBadRequests", new Func0<Long>() {
        @Override
        public Long call() {
            return commandMetrics.getRollingCount(HystrixEventType.BAD_REQUEST);
        }
    });
    safelyWriteNumberField(json, "rollingCountCollapsedRequests", new Func0<Long>() {
        @Override
        public Long call() {
            return commandMetrics.getRollingCount(HystrixEventType.COLLAPSED);
        }
    });
    safelyWriteNumberField(json, "rollingCountEmit", new Func0<Long>() {
        @Override
        public Long call() {
            return commandMetrics.getRollingCount(HystrixEventType.EMIT);
        }
    });
    safelyWriteNumberField(json, "rollingCountExceptionsThrown", new Func0<Long>() {
        @Override
        public Long call() {
            return commandMetrics.getRollingCount(HystrixEventType.EXCEPTION_THROWN);
        }
    });
    safelyWriteNumberField(json, "rollingCountFailure", new Func0<Long>() {
        @Override
        public Long call() {
            return commandMetrics.getRollingCount(HystrixEventType.FAILURE);
        }
    });
    safelyWriteNumberField(json, "rollingCountFallbackEmit", new Func0<Long>() {
        @Override
        public Long call() {
            return commandMetrics.getRollingCount(HystrixEventType.FALLBACK_EMIT);
        }
    });
    safelyWriteNumberField(json, "rollingCountFallbackFailure", new Func0<Long>() {
        @Override
        public Long call() {
            return commandMetrics.getRollingCount(HystrixEventType.FALLBACK_FAILURE);
        }
    });
    safelyWriteNumberField(json, "rollingCountFallbackMissing", new Func0<Long>() {
        @Override
        public Long call() {
            return commandMetrics.getRollingCount(HystrixEventType.FALLBACK_MISSING);
        }
    });
    safelyWriteNumberField(json, "rollingCountFallbackRejection", new Func0<Long>() {
        @Override
        public Long call() {
            return commandMetrics.getRollingCount(HystrixEventType.FALLBACK_REJECTION);
        }
    });
    safelyWriteNumberField(json, "rollingCountFallbackSuccess", new Func0<Long>() {
        @Override
        public Long call() {
            return commandMetrics.getRollingCount(HystrixEventType.FALLBACK_SUCCESS);
        }
    });
    safelyWriteNumberField(json, "rollingCountResponsesFromCache", new Func0<Long>() {
        @Override
        public Long call() {
            return commandMetrics.getRollingCount(HystrixEventType.RESPONSE_FROM_CACHE);
        }
    });
    safelyWriteNumberField(json, "rollingCountSemaphoreRejected", new Func0<Long>() {
        @Override
        public Long call() {
            return commandMetrics.getRollingCount(HystrixEventType.SEMAPHORE_REJECTED);
        }
    });
    safelyWriteNumberField(json, "rollingCountShortCircuited", new Func0<Long>() {
        @Override
        public Long call() {
            return commandMetrics.getRollingCount(HystrixEventType.SHORT_CIRCUITED);
        }
    });
    safelyWriteNumberField(json, "rollingCountSuccess", new Func0<Long>() {
        @Override
        public Long call() {
            return commandMetrics.getRollingCount(HystrixEventType.SUCCESS);
        }
    });
    safelyWriteNumberField(json, "rollingCountThreadPoolRejected", new Func0<Long>() {
        @Override
        public Long call() {
            return commandMetrics.getRollingCount(HystrixEventType.THREAD_POOL_REJECTED);
        }
    });
    safelyWriteNumberField(json, "rollingCountTimeout", new Func0<Long>() {
        @Override
        public Long call() {
            return commandMetrics.getRollingCount(HystrixEventType.TIMEOUT);
        }
    });

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

    // 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.executionTimeoutInMilliseconds().get());
    json.writeNumberField("propertyValue_executionTimeoutInMilliseconds",
            commandProperties.executionTimeoutInMilliseconds().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());

    /*
     * 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.writeStringField("threadPool", commandMetrics.getThreadPoolKey().name());

    json.writeEndObject();
}

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

@Override
public void serialize(List<Link> links, JsonGenerator jgen, SerializerProvider serializerProvider)
        throws IOException {

    try {/*  www. j  a  v  a 2  s  .c o  m*/
        Collection<Link> simpleLinks = new ArrayList<Link>();
        Collection<Affordance> affordances = new ArrayList<Affordance>();
        Collection<Link> templatedLinks = new ArrayList<Link>();
        Collection<Affordance> collectionAffordances = new ArrayList<Affordance>();
        Link selfRel = null;
        for (Link link : links) {
            if (link instanceof Affordance) {
                final Affordance affordance = (Affordance) link;
                final List<ActionDescriptor> actionDescriptors = affordance.getActionDescriptors();
                if (!actionDescriptors.isEmpty()) {
                    // TODO: consider to use Link href for template even if it is not compatible
                    if (affordance.getUriTemplateComponents().hasVariables()) {
                        // TODO resolve rel against context
                        if ("hydra:search".equals(affordance.getRel())
                                || Cardinality.SINGLE == affordance.getCardinality()) {
                            templatedLinks.add(affordance);
                        } else {
                            collectionAffordances.add(affordance);
                        }
                    } else {
                        // if all required variables are satisfied, the url can be used as identifier
                        // by stripping optional variables
                        if (!affordance.isSelfRel() && Cardinality.COLLECTION == affordance.getCardinality()) {
                            collectionAffordances.add(affordance);
                        } else {
                            affordances.add(affordance);
                        }
                    }
                } else {
                    if (affordance.isTemplated()) {
                        templatedLinks.add(affordance);
                    } else {
                        simpleLinks.add(affordance);
                    }
                }
            } else if (link.isTemplated()) {
                templatedLinks.add(link);
            } else {
                simpleLinks.add(link);
            }
            if ("self".equals(link.getRel())) {
                selfRel = link;
            }
        }

        for (Link templatedLink : templatedLinks) {
            // templated affordance might turn out to have all variables satisfied or
            // only optional unsatisfied variables
            ActionDescriptor actionDescriptorForHttpGet = getActionDescriptorForHttpGet(templatedLink);
            // TODO handle rev here
            String rel = templatedLink.getRel();
            writeIriTemplate(rel, templatedLink.getHref(), templatedLink.getVariableNames(),
                    actionDescriptorForHttpGet, jgen);
        }
        @SuppressWarnings("unchecked")
        Deque<LdContext> contextStack = (Deque<LdContext>) serializerProvider
                .getAttribute(JacksonHydraSerializer.KEY_LD_CONTEXT);
        String currentVocab = (contextStack != null && !contextStack.isEmpty()) ? contextStack.peek().vocab
                : null;

        // related collections
        if (!collectionAffordances.isEmpty()) {

            jgen.writeArrayFieldStart("hydra:collection");

            for (Affordance collectionAffordance : collectionAffordances) {
                jgen.writeStartObject();
                jgen.writeStringField(JsonLdKeywords.AT_TYPE, "hydra:Collection");
                PartialUriTemplateComponents templateComponents = collectionAffordance
                        .getUriTemplateComponents();
                if (!collectionAffordance.isBaseUriTemplated()
                        && !collectionAffordance.hasUnsatisfiedRequiredVariables()) {
                    String collectionUri = templateComponents.getBaseUri() + templateComponents.getQueryHead();
                    jgen.writeStringField(JsonLdKeywords.AT_ID, collectionUri);
                }
                if (templateComponents.hasVariables()) {
                    ActionDescriptor actionDescriptorForHttpGet = getActionDescriptorForHttpGet(
                            collectionAffordance);
                    writeIriTemplate("hydra:search", templateComponents.toString(),
                            templateComponents.getVariableNames(), actionDescriptorForHttpGet, jgen);
                }
                jgen.writeObjectFieldStart("hydra:manages");
                // do we have a collection holder which is not owner of the affordance?
                TypedResource collectionHolder = collectionAffordance.getCollectionHolder();
                if (collectionAffordance.getRev() != null) {
                    jgen.writeStringField("hydra:property", collectionAffordance.getRev());
                    if (collectionHolder != null) {
                        // can't use writeObjectField, it won't inherit the context stack
                        writeCollectionHolder("hydra:object", collectionHolder, jgen);
                    } else if (selfRel != null) {
                        jgen.writeStringField("hydra:object", selfRel.getHref());
                    }
                } else if (collectionAffordance.getRel() != null) {
                    jgen.writeStringField("hydra:property", collectionAffordance.getRel());
                    if (collectionHolder != null) {
                        // can't use writeObjectField, it won't inherit the context stack
                        writeCollectionHolder("hydra:subject", collectionHolder, jgen);
                    } else if (selfRel != null) {
                        jgen.writeStringField("hydra:subject", selfRel.getHref());
                    }
                }
                jgen.writeEndObject(); // end manages

                List<ActionDescriptor> actionDescriptors = collectionAffordance.getActionDescriptors();
                if (!actionDescriptors.isEmpty()) {
                    jgen.writeArrayFieldStart("hydra:operation");
                }
                writeActionDescriptors(jgen, currentVocab, actionDescriptors);
                if (!actionDescriptors.isEmpty()) {
                    jgen.writeEndArray(); // end hydra:operation
                }

                jgen.writeEndObject(); // end collection
            }
            jgen.writeEndArray();
        }

        for (Affordance affordance : affordances) {
            final String rel = affordance.getRel();
            List<ActionDescriptor> actionDescriptors = affordance.getActionDescriptors();

            if (!actionDescriptors.isEmpty()) {
                if (!Link.REL_SELF.equals(rel)) {
                    jgen.writeObjectFieldStart(rel); // begin rel
                }
                jgen.writeStringField(JsonLdKeywords.AT_ID, affordance.getHref());
                jgen.writeArrayFieldStart("hydra:operation");
            }

            writeActionDescriptors(jgen, currentVocab, actionDescriptors);

            if (!actionDescriptors.isEmpty()) {
                jgen.writeEndArray(); // end hydra:operation

                if (!Link.REL_SELF.equals(rel)) {
                    jgen.writeEndObject(); // end rel
                }
            }
        }

        for (Link simpleLink : simpleLinks) {
            final String rel = simpleLink.getRel();
            if (Link.REL_SELF.equals(rel)) {
                jgen.writeStringField("@id", simpleLink.getHref());
            } else {
                String linkAttributeName = IanaRels.isIanaRel(rel) ? IANA_REL_PREFIX + rel : rel;
                jgen.writeObjectFieldStart(linkAttributeName);
                jgen.writeStringField("@id", simpleLink.getHref());
                jgen.writeEndObject();
            }
        }
    } catch (IntrospectionException e) {
        throw new RuntimeException(e);
    }
}