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:org.jbpm.designer.bpmn2.impl.Bpmn2JsonMarshaller.java

protected void marshallSubProcess(SubProcess subProcess, BPMNPlane plane, JsonGenerator generator,
        float xOffset, float yOffset, String preProcessingData, Definitions def,
        Map<String, Object> flowElementProperties) throws JsonGenerationException, IOException {
    Map<String, Object> properties = new LinkedHashMap<String, Object>(flowElementProperties);
    if (subProcess.getName() != null) {
        properties.put("name", unescapeXml(subProcess.getName()));
    } else {//from w w  w  .  j  a v a  2s .  c o m
        properties.put("name", "");
    }

    // overwrite name if elementname extension element is present
    String elementName = Utils.getMetaDataValue(subProcess.getExtensionValues(), "elementname");
    if (elementName != null) {
        properties.put("name", elementName);
    }

    if (subProcess.getDocumentation() != null && subProcess.getDocumentation().size() > 0) {
        properties.put("documentation", subProcess.getDocumentation().get(0).getText());
    }

    if (subProcess instanceof AdHocSubProcess) {
        AdHocSubProcess ahsp = (AdHocSubProcess) subProcess;
        if (ahsp.getOrdering().equals(AdHocOrdering.PARALLEL)) {
            properties.put("adhocordering", "Parallel");
        } else if (ahsp.getOrdering().equals(AdHocOrdering.SEQUENTIAL)) {
            properties.put("adhocordering", "Sequential");
        } else {
            // default to parallel
            properties.put("adhocordering", "Parallel");
        }
        if (ahsp.getCompletionCondition() != null) {
            try {
                FormalExpression completionExpression = (FormalExpression) ahsp.getCompletionCondition();
                if (completionExpression != null) {
                    properties.put("adhoccompletioncondition",
                            completionExpression.getBody().replaceAll("\n", "\\\\n"));
                    if (completionExpression.getLanguage() != null) {
                        String completionLanguage = getScriptLanguageFormat(completionExpression.getLanguage());
                        properties.put("script_language", completionLanguage);
                    }
                }
            } catch (Exception e) {
                _logger.info("Could not find adhoccompletioncondition for: " + ahsp);
            }
        }

        final String customActivationCondition = Utils.getMetaDataValue(ahsp.getExtensionValues(),
                "customActivationCondition");
        if (customActivationCondition != null && customActivationCondition.length() > 0) {
            properties.put("adhocactivationcondition", customActivationCondition);
        }
    }

    // custom async
    String customAsyncMetaData = Utils.getMetaDataValue(subProcess.getExtensionValues(), "customAsync");
    String customAsync = (customAsyncMetaData != null && customAsyncMetaData.length() > 0) ? customAsyncMetaData
            : "false";
    properties.put("isasync", customAsync);

    // custom SLA due date
    marshalCustomSLADueDateMetadata(subProcess, properties);

    // data inputs
    marshallDataInputSet(subProcess, properties);

    // data outputs
    marshallDataOutputSet(subProcess, properties);

    // assignments
    StringBuilder associationBuff = new StringBuilder();
    List<DataInputAssociation> inputAssociations = subProcess.getDataInputAssociations();
    List<DataOutputAssociation> outputAssociations = subProcess.getDataOutputAssociations();

    marshallDataInputAssociations(associationBuff, inputAssociations);
    marshallDataOutputAssociations(associationBuff, outputAssociations);

    String assignmentString = associationBuff.toString();
    if (assignmentString.endsWith(",")) {
        assignmentString = assignmentString.substring(0, assignmentString.length() - 1);
    }
    properties.put("assignments", assignmentString);

    // on-entry and on-exit actions
    marshallEntryExitActions(subProcess, properties);

    // loop characteristics
    boolean haveValidLoopCharacteristics = false;
    if (subProcess.getLoopCharacteristics() != null
            && subProcess.getLoopCharacteristics() instanceof MultiInstanceLoopCharacteristics) {
        haveValidLoopCharacteristics = true;
        properties.put("mitrigger", "true");
        MultiInstanceLoopCharacteristics taskmi = (MultiInstanceLoopCharacteristics) subProcess
                .getLoopCharacteristics();
        if (taskmi.getLoopDataInputRef() != null) {
            ItemAwareElement iedatainput = taskmi.getLoopDataInputRef();

            List<DataInputAssociation> taskInputAssociations = subProcess.getDataInputAssociations();
            for (DataInputAssociation dia : taskInputAssociations) {
                if (dia.getTargetRef().equals(iedatainput)) {
                    properties.put("multipleinstancecollectioninput", dia.getSourceRef().get(0).getId());
                    break;
                }
            }
        }
        if (taskmi.getLoopDataOutputRef() != null) {
            ItemAwareElement iedataoutput = taskmi.getLoopDataOutputRef();

            List<DataOutputAssociation> taskOutputAssociations = subProcess.getDataOutputAssociations();
            for (DataOutputAssociation dout : taskOutputAssociations) {
                if (dout.getSourceRef().get(0).equals(iedataoutput)) {
                    properties.put("multipleinstancecollectionoutput", dout.getTargetRef().getId());
                    break;
                }
            }
        }

        if (taskmi.getInputDataItem() != null) {
            List<DataInput> taskDataInputs = subProcess.getIoSpecification().getDataInputs();
            for (DataInput din : taskDataInputs) {

                if (din.getItemSubjectRef() == null) {
                    // for backward compatibility as the where only input supported
                    properties.put("multipleinstancedatainput", taskmi.getInputDataItem().getId());
                }
                if (din.getItemSubjectRef() != null && din.getItemSubjectRef().getId()
                        .equals(taskmi.getInputDataItem().getItemSubjectRef().getId())) {
                    properties.put("multipleinstancedatainput", din.getName());
                    break;
                }
            }
        }

        if (taskmi.getOutputDataItem() != null) {
            List<DataOutput> taskDataOutputs = subProcess.getIoSpecification().getDataOutputs();
            for (DataOutput dout : taskDataOutputs) {
                if (dout.getItemSubjectRef() == null) {
                    properties.put("multipleinstancedataoutput", taskmi.getOutputDataItem().getId());
                    break;
                }

                if (dout.getItemSubjectRef() != null && dout.getItemSubjectRef().getId()
                        .equals(taskmi.getOutputDataItem().getItemSubjectRef().getId())) {
                    properties.put("multipleinstancedataoutput", dout.getName());
                    break;
                }
            }
        }

        if (taskmi.getCompletionCondition() != null) {
            try {
                if (taskmi.getCompletionCondition() instanceof FormalExpression) {
                    properties.put("multipleinstancecompletioncondition",
                            ((FormalExpression) taskmi.getCompletionCondition()).getBody());
                }
            } catch (Exception e) {
                _logger.info("Could not find multipleinstancecompletioncondition for : " + taskmi);
            }
        }
    }

    // properties
    List<Property> processProperties = subProcess.getProperties();
    if (processProperties != null && processProperties.size() > 0) {
        String propVal = "";
        for (int i = 0; i < processProperties.size(); i++) {
            Property p = processProperties.get(i);

            String pKPI = Utils.getMetaDataValue(p.getExtensionValues(), "customKPI");

            propVal += p.getId();
            // check the structureRef value
            if (p.getItemSubjectRef() != null && p.getItemSubjectRef().getStructureRef() != null) {
                propVal += ":" + p.getItemSubjectRef().getStructureRef();
            }
            if (pKPI != null && pKPI.length() > 0) {
                propVal += ":" + pKPI;
            }
            if (i != processProperties.size() - 1) {
                propVal += ",";
            }
        }
        properties.put("vardefs", propVal);
    }

    // simulation properties
    setSimulationProperties(subProcess.getId(), properties);

    marshallProperties(properties, generator);
    generator.writeObjectFieldStart("stencil");
    if (subProcess instanceof AdHocSubProcess) {
        generator.writeObjectField("id", "AdHocSubprocess");
    } else {
        if (subProcess.isTriggeredByEvent()) {
            generator.writeObjectField("id", "EventSubprocess");
        } else {
            if (haveValidLoopCharacteristics) {
                generator.writeObjectField("id", "MultipleInstanceSubprocess");
            } else {
                generator.writeObjectField("id", "Subprocess");
            }
        }
    }
    generator.writeEndObject();
    generator.writeArrayFieldStart("childShapes");
    Bounds bounds = ((BPMNShape) findDiagramElement(plane, subProcess)).getBounds();
    for (FlowElement flowElement : subProcess.getFlowElements()) {
        if (coordianteManipulation) {
            marshallFlowElement(flowElement, plane, generator, bounds.getX(), bounds.getY(), preProcessingData,
                    def);
        } else {
            marshallFlowElement(flowElement, plane, generator, 0, 0, preProcessingData, def);
        }
    }
    for (Artifact artifact : subProcess.getArtifacts()) {
        if (coordianteManipulation) {
            marshallArtifact(artifact, plane, generator, bounds.getX(), bounds.getY(), preProcessingData, def);
        } else {
            marshallArtifact(artifact, plane, generator, 0, 0, preProcessingData, def);
        }
    }
    generator.writeEndArray();
    generator.writeArrayFieldStart("outgoing");
    for (BoundaryEvent boundaryEvent : subProcess.getBoundaryEventRefs()) {
        generator.writeStartObject();
        generator.writeObjectField("resourceId", boundaryEvent.getId());
        generator.writeEndObject();
    }
    for (SequenceFlow outgoing : subProcess.getOutgoing()) {
        generator.writeStartObject();
        generator.writeObjectField("resourceId", outgoing.getId());
        generator.writeEndObject();
    }
    Process process = (Process) plane.getBpmnElement();
    writeAssociations(process, subProcess.getId(), generator);
    // subprocess boundary events
    List<BoundaryEvent> boundaryEvents = new ArrayList<BoundaryEvent>();
    findBoundaryEvents(process, boundaryEvents);
    for (BoundaryEvent be : boundaryEvents) {
        if (be.getAttachedToRef().getId().equals(subProcess.getId())) {
            generator.writeStartObject();
            generator.writeObjectField("resourceId", be.getId());
            generator.writeEndObject();
        }
    }

    generator.writeEndArray();

    generator.writeObjectFieldStart("bounds");
    generator.writeObjectFieldStart("lowerRight");
    generator.writeObjectField("x", bounds.getX() + bounds.getWidth() - xOffset);
    generator.writeObjectField("y", bounds.getY() + bounds.getHeight() - yOffset);
    generator.writeEndObject();
    generator.writeObjectFieldStart("upperLeft");
    generator.writeObjectField("x", bounds.getX() - xOffset);
    generator.writeObjectField("y", bounds.getY() - yOffset);
    generator.writeEndObject();
    generator.writeEndObject();
}

From source file:org.jbpm.designer.bpmn2.impl.Bpmn2JsonMarshaller.java

protected void marshallSequenceFlow(SequenceFlow sequenceFlow, BPMNPlane plane, JsonGenerator generator,
        float xOffset, float yOffset) throws JsonGenerationException, IOException {
    // dont marshal "dangling" sequence flow..better to just omit than fail
    if (sequenceFlow.getSourceRef() == null || sequenceFlow.getTargetRef() == null) {
        return;//from  w  ww .  j a v a  2  s  .  co  m
    }

    Map<String, Object> properties = new LinkedHashMap<String, Object>();
    // check null for sequence flow name
    if (sequenceFlow.getName() != null && !"".equals(sequenceFlow.getName())) {
        properties.put("name", unescapeXml(sequenceFlow.getName()));
    } else {
        properties.put("name", "");
    }
    // overwrite name if elementname extension element is present
    String elementName = Utils.getMetaDataValue(sequenceFlow.getExtensionValues(), "elementname");
    if (elementName != null) {
        properties.put("name", elementName);
    }

    if (sequenceFlow.getDocumentation() != null && sequenceFlow.getDocumentation().size() > 0) {
        properties.put("documentation", sequenceFlow.getDocumentation().get(0).getText());
    }

    if (sequenceFlow.isIsImmediate()) {
        properties.put("isimmediate", "true");
    } else {
        properties.put("isimmediate", "false");
    }

    Expression conditionExpression = sequenceFlow.getConditionExpression();
    try {
        if (conditionExpression instanceof FormalExpression) {
            if (((FormalExpression) conditionExpression).getBody() != null) {
                properties.put("conditionexpression",
                        ((FormalExpression) conditionExpression).getBody().replaceAll("\n", "\\\\n"));
            }
            if (((FormalExpression) conditionExpression).getLanguage() != null) {
                String cd = ((FormalExpression) conditionExpression).getLanguage();
                String cdStr = getScriptLanguageFormat(cd, "mvel");

                properties.put("conditionexpressionlanguage", cdStr);
            }
        }
    } catch (Exception e) {
        _logger.info("Could not find conditionexpression for : " + conditionExpression);
    }

    boolean foundBgColor = false;
    boolean foundBrColor = false;
    boolean foundFontColor = false;
    boolean foundSelectable = false;
    Iterator<FeatureMap.Entry> iter = sequenceFlow.getAnyAttribute().iterator();
    while (iter.hasNext()) {
        FeatureMap.Entry entry = iter.next();
        if (entry.getEStructuralFeature().getName().equals("priority")) {
            String priorityStr = String.valueOf(entry.getValue());
            if (priorityStr != null) {
                try {
                    Integer priorityInt = Integer.parseInt(priorityStr);
                    if (priorityInt >= 1) {
                        properties.put("priority", entry.getValue());
                    } else {
                        _logger.error("Priority must be equal or greater than 1.");
                    }
                } catch (NumberFormatException e) {
                    _logger.error("Priority must be a number.");
                }
            }
        }
        if (entry.getEStructuralFeature().getName().equals("background-color")
                || entry.getEStructuralFeature().getName().equals("bgcolor")) {
            properties.put("bgcolor", entry.getValue());
            foundBgColor = true;
        }
        if (entry.getEStructuralFeature().getName().equals("border-color")
                || entry.getEStructuralFeature().getName().equals("bordercolor")) {
            properties.put("bordercolor", entry.getValue());
            foundBrColor = true;
        }
        if (entry.getEStructuralFeature().getName().equals("fontsize")) {
            properties.put("fontsize", entry.getValue());
            foundBrColor = true;
        }
        if (entry.getEStructuralFeature().getName().equals("color")
                || entry.getEStructuralFeature().getName().equals("fontcolor")) {
            properties.put("fontcolor", entry.getValue());
            foundFontColor = true;
        }
        if (entry.getEStructuralFeature().getName().equals("selectable")) {
            properties.put("isselectable", entry.getValue());
            foundSelectable = true;
        }
    }
    if (!foundBgColor) {
        properties.put("bgcolor", defaultSequenceflowColor);
    }

    if (!foundBrColor) {
        properties.put("bordercolor", defaultSequenceflowColor);
    }

    if (!foundFontColor) {
        properties.put("fontcolor", defaultSequenceflowColor);
    }

    if (!foundSelectable) {
        properties.put("isselectable", "true");
    }

    // simulation properties
    setSimulationProperties(sequenceFlow.getId(), properties);

    marshallProperties(properties, generator);
    generator.writeObjectFieldStart("stencil");
    generator.writeObjectField("id", "SequenceFlow");
    generator.writeEndObject();
    generator.writeArrayFieldStart("childShapes");
    generator.writeEndArray();

    generator.writeArrayFieldStart("outgoing");
    generator.writeStartObject();
    generator.writeObjectField("resourceId", sequenceFlow.getTargetRef().getId());
    generator.writeEndObject();
    generator.writeEndArray();

    Bounds sourceBounds = ((BPMNShape) findDiagramElement(plane, sequenceFlow.getSourceRef())).getBounds();
    Bounds targetBounds = ((BPMNShape) findDiagramElement(plane, sequenceFlow.getTargetRef())).getBounds();
    generator.writeArrayFieldStart("dockers");
    generator.writeStartObject();
    generator.writeObjectField("x", sourceBounds.getWidth() / 2);
    generator.writeObjectField("y", sourceBounds.getHeight() / 2);
    generator.writeEndObject();
    List<Point> waypoints = ((BPMNEdge) findDiagramElement(plane, sequenceFlow)).getWaypoint();
    for (int i = 1; i < waypoints.size() - 1; i++) {
        Point waypoint = waypoints.get(i);
        generator.writeStartObject();
        generator.writeObjectField("x", waypoint.getX());
        generator.writeObjectField("y", waypoint.getY());
        generator.writeEndObject();
    }
    generator.writeStartObject();
    generator.writeObjectField("x", targetBounds.getWidth() / 2);
    generator.writeObjectField("y", targetBounds.getHeight() / 2);
    generator.writeEndObject();
    generator.writeEndArray();
}

From source file:org.jbpm.designer.bpmn2.impl.Bpmn2JsonMarshaller.java

protected void marshallProperties(Map<String, Object> properties, JsonGenerator generator)
        throws JsonGenerationException, IOException {
    generator.writeObjectFieldStart("properties");
    for (Entry<String, Object> entry : properties.entrySet()) {
        generator.writeObjectField(entry.getKey(), String.valueOf(entry.getValue()));
    }/*w ww. j ava 2  s .  c  o m*/
    generator.writeEndObject();
}

From source file:org.jbpm.designer.bpmn2.impl.Bpmn2JsonMarshaller.java

protected void marshallAssociation(Association association, BPMNPlane plane, JsonGenerator generator,
        float xOffset, float yOffset, String preProcessingData, Definitions def)
        throws JsonGenerationException, IOException {
    Map<String, Object> properties = new LinkedHashMap<String, Object>();
    Iterator<FeatureMap.Entry> iter = association.getAnyAttribute().iterator();
    boolean foundBrColor = false;
    while (iter.hasNext()) {
        FeatureMap.Entry entry = iter.next();
        if (entry.getEStructuralFeature().getName().equals("type")) {
            properties.put("type", entry.getValue());
        }/*from  w  w  w .  j ava 2s.  c  o m*/
        if (entry.getEStructuralFeature().getName().equals("bordercolor")) {
            properties.put("bordercolor", entry.getValue());
            foundBrColor = true;
        }
    }
    if (!foundBrColor) {
        properties.put("bordercolor", defaultSequenceflowColor);
    }
    if (association.getDocumentation() != null && association.getDocumentation().size() > 0) {
        properties.put("documentation", association.getDocumentation().get(0).getText());
    }

    marshallProperties(properties, generator);
    generator.writeObjectFieldStart("stencil");
    if (association.getAssociationDirection().equals(AssociationDirection.ONE)) {
        generator.writeObjectField("id", "Association_Unidirectional");
    } else if (association.getAssociationDirection().equals(AssociationDirection.BOTH)) {
        generator.writeObjectField("id", "Association_Bidirectional");
    } else {
        generator.writeObjectField("id", "Association_Undirected");
    }
    generator.writeEndObject();
    generator.writeArrayFieldStart("childShapes");
    generator.writeEndArray();
    generator.writeArrayFieldStart("outgoing");
    generator.writeStartObject();
    generator.writeObjectField("resourceId", association.getTargetRef().getId());
    generator.writeEndObject();
    generator.writeEndArray();

    Bounds sourceBounds = ((BPMNShape) findDiagramElement(plane, association.getSourceRef())).getBounds();

    Bounds targetBounds = null;
    float tbx = 0;
    float tby = 0;
    if (findDiagramElement(plane, association.getTargetRef()) instanceof BPMNShape) {
        targetBounds = ((BPMNShape) findDiagramElement(plane, association.getTargetRef())).getBounds();
    } else if (findDiagramElement(plane, association.getTargetRef()) instanceof BPMNEdge) {
        // connect it to first waypoint on edge
        List<Point> waypoints = ((BPMNEdge) findDiagramElement(plane, association.getTargetRef()))
                .getWaypoint();
        if (waypoints != null && waypoints.size() > 0) {
            tbx = waypoints.get(0).getX();
            tby = waypoints.get(0).getY();
        }
    }
    generator.writeArrayFieldStart("dockers");
    generator.writeStartObject();
    generator.writeObjectField("x", sourceBounds.getWidth() / 2);
    generator.writeObjectField("y", sourceBounds.getHeight() / 2);
    generator.writeEndObject();
    List<Point> waypoints = ((BPMNEdge) findDiagramElement(plane, association)).getWaypoint();
    for (int i = 1; i < waypoints.size() - 1; i++) {
        Point waypoint = waypoints.get(i);
        generator.writeStartObject();
        generator.writeObjectField("x", waypoint.getX());
        generator.writeObjectField("y", waypoint.getY());
        generator.writeEndObject();
    }
    if (targetBounds != null) {
        generator.writeStartObject();
        // text annotations have to be treated specia
        if (association.getTargetRef() instanceof TextAnnotation) {
            generator.writeObjectField("x", 1);
            generator.writeObjectField("y", targetBounds.getHeight() / 2);
        } else {
            generator.writeObjectField("x", targetBounds.getWidth() / 2);
            generator.writeObjectField("y", targetBounds.getHeight() / 2);
        }
        generator.writeEndObject();
        generator.writeEndArray();
    } else {
        generator.writeStartObject();
        generator.writeObjectField("x", tbx);
        generator.writeObjectField("y", tby);
        generator.writeEndObject();
        generator.writeEndArray();
    }
}

From source file:org.jbpm.designer.bpmn2.impl.Bpmn2JsonMarshaller.java

protected void marshallGroup(Group group, BPMNPlane plane, JsonGenerator generator, float xOffset,
        float yOffset, String preProcessingData, Definitions def) throws JsonGenerationException, IOException {
    Map<String, Object> properties = new LinkedHashMap<>();
    if (group.getCategoryValueRef() != null && group.getCategoryValueRef().getValue() != null) {
        properties.put("name", unescapeXml(group.getCategoryValueRef().getValue()));
    }/*w w  w  .j  av  a2 s  . c  o  m*/
    Documentation doc = getDocumentation(group);
    if (doc != null) {
        properties.put("documentation", doc.getText());
    }

    marshallProperties(properties, generator);

    generator.writeObjectFieldStart("stencil");
    generator.writeObjectField("id", "Group");
    generator.writeEndObject();
    generator.writeArrayFieldStart("childShapes");
    generator.writeEndArray();

    generator.writeArrayFieldStart("outgoing");
    if (findOutgoingAssociation(plane, group) != null) {
        generator.writeStartObject();
        generator.writeObjectField("resourceId", findOutgoingAssociation(plane, group).getId());
        generator.writeEndObject();
    }
    generator.writeEndArray();

    Bounds bounds = ((BPMNShape) findDiagramElement(plane, group)).getBounds();
    generator.writeObjectFieldStart("bounds");
    generator.writeObjectFieldStart("lowerRight");
    generator.writeObjectField("x", bounds.getX() + bounds.getWidth() - xOffset);
    generator.writeObjectField("y", bounds.getY() + bounds.getHeight() - yOffset);
    generator.writeEndObject();
    generator.writeObjectFieldStart("upperLeft");
    generator.writeObjectField("x", bounds.getX() - xOffset);
    generator.writeObjectField("y", bounds.getY() - yOffset);
    generator.writeEndObject();
    generator.writeEndObject();
}

From source file:org.jbpm.designer.bpmn2.impl.Bpmn2JsonMarshaller.java

protected void marshallStencil(String stencilId, JsonGenerator generator)
        throws JsonGenerationException, IOException {
    generator.writeObjectFieldStart("stencil");
    generator.writeObjectField("id", stencilId);
    generator.writeEndObject();//from   w  w  w .j ava  2 s  .c om
}

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

@Scheduled(fixedRateString = "${hystrix.stream.queue.gatherRate:500}")
public void gatherMetrics() {
    try {/*from   w w  w .jav  a2  s. com*/
        // 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);
    }
}

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

/**
 * Get the structured log message format
 *
 * @param timeStamp timeStamp Instant/*  w w w .j av  a 2s  .  com*/
 * @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;
    }
}