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

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

Introduction

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

Prototype

public abstract void writeEndArray() throws IOException, JsonGenerationException;

Source Link

Document

Method for writing closing marker of a JSON Array value (character ']'; plus possible white space decoration if pretty-printing is enabled).

Usage

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

/**
 * Writes bean description recursively.//  www . ja  v  a  2  s. c om
 *
 * @param jgen
 *         to write to
 * @param currentVocab
 *         in context
 * @param valueType
 *         class of value
 * @param allRootParameters
 *         of the method that receives the request body
 * @param rootParameter
 *         the request body
 * @param currentCallValue
 *         the value at the current recursion level
 * @param propertyPath
 *         of the current recursion level
 * @throws IntrospectionException
 * @throws IOException
 */
private void recurseSupportedProperties(JsonGenerator jgen, String currentVocab, Class<?> valueType,
        ActionDescriptor allRootParameters, ActionInputParameter rootParameter, Object currentCallValue,
        String propertyPath) throws IntrospectionException, IOException {

    Map<String, ActionInputParameter> properties = new HashMap<String, ActionInputParameter>();

    // collect supported properties from ctor

    Constructor[] constructors = valueType.getConstructors();
    // find default ctor
    Constructor constructor = PropertyUtils.findDefaultCtor(constructors);
    // find ctor with JsonCreator ann
    if (constructor == null) {
        constructor = PropertyUtils.findJsonCreator(constructors, JsonCreator.class);
    }
    if (constructor == null) {
        // TODO this can be a generic collection, find a way to describe it
        LOG.warn("can't describe supported properties, no default constructor or JsonCreator found for type "
                + valueType.getName());
        return;
    }

    int parameterCount = constructor.getParameterTypes().length;
    if (parameterCount > 0) {
        Annotation[][] annotationsOnParameters = constructor.getParameterAnnotations();

        Class[] parameters = constructor.getParameterTypes();
        int paramIndex = 0;
        for (Annotation[] annotationsOnParameter : annotationsOnParameters) {
            for (Annotation annotation : annotationsOnParameter) {
                if (JsonProperty.class == annotation.annotationType()) {
                    JsonProperty jsonProperty = (JsonProperty) annotation;
                    // TODO use required attribute of JsonProperty
                    String paramName = jsonProperty.value();

                    Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue, paramName);

                    ActionInputParameter constructorParamInputParameter = new SpringActionInputParameter(
                            new MethodParameter(constructor, paramIndex), propertyValue);

                    // TODO collect ctor params, setter params and process
                    // TODO then handle single, collection and bean for both
                    properties.put(paramName, constructorParamInputParameter);
                    paramIndex++; // increase for each @JsonProperty
                }
            }
        }
        Assert.isTrue(parameters.length == paramIndex, "not all constructor arguments of @JsonCreator "
                + constructor.getName() + " are annotated with @JsonProperty");
    }

    // collect supported properties from setters

    // TODO support Option provider by other method args?
    final BeanInfo beanInfo = Introspector.getBeanInfo(valueType);
    final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    // TODO collection and map
    // TODO distinguish which properties should be printed as supported - now just setters
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        final Method writeMethod = propertyDescriptor.getWriteMethod();
        if (writeMethod == null) {
            continue;
        }
        // TODO: the property name must be a valid URI - need to check context for terms?
        String propertyName = getWritableExposedPropertyOrPropertyName(propertyDescriptor);

        Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue,
                propertyDescriptor.getName());

        MethodParameter methodParameter = new MethodParameter(propertyDescriptor.getWriteMethod(), 0);
        ActionInputParameter propertySetterInputParameter = new SpringActionInputParameter(methodParameter,
                propertyValue);

        properties.put(propertyName, propertySetterInputParameter);
    }

    // write all supported properties
    // TODO we are using the annotatedParameter.parameterName but should use the key of properties here:
    for (ActionInputParameter annotatedParameter : properties.values()) {
        String nextPropertyPathLevel = propertyPath.isEmpty() ? annotatedParameter.getParameterName()
                : propertyPath + '.' + annotatedParameter.getParameterName();
        if (DataType.isSingleValueType(annotatedParameter.getParameterType())) {

            final Object[] possiblePropertyValues = rootParameter.getPossibleValues(allRootParameters);

            if (rootParameter.isIncluded(nextPropertyPathLevel)
                    && !rootParameter.isExcluded(nextPropertyPathLevel)) {
                writeSupportedProperty(jgen, currentVocab, annotatedParameter,
                        annotatedParameter.getParameterName(), possiblePropertyValues);
            }
            // TODO collections?
            //                        } else if (DataType.isArrayOrCollection(parameterType)) {
            //                            Object[] callValues = rootParameter.getValues();
            //                            int items = callValues.length;
            //                            for (int i = 0; i < items; i++) {
            //                                Object value;
            //                                if (i < callValues.length) {
            //                                    value = callValues[i];
            //                                } else {
            //                                    value = null;
            //                                }
            //                                recurseSupportedProperties(jgen, currentVocab, rootParameter
            // .getParameterType(),
            //                                        allRootParameters, rootParameter, value);
            //                            }
        } else {
            jgen.writeStartObject();
            jgen.writeStringField("hydra:property", annotatedParameter.getParameterName());
            // TODO: is the property required -> for bean props we need the Access annotation to express that
            jgen.writeObjectFieldStart(getPropertyOrClassNameInVocab(currentVocab, "rangeIncludes",
                    LdContextFactory.HTTP_SCHEMA_ORG, "schema:"));
            Expose expose = AnnotationUtils.getAnnotation(annotatedParameter.getParameterType(), Expose.class);
            String subClass;
            if (expose != null) {
                subClass = expose.value();
            } else {
                subClass = annotatedParameter.getParameterType().getSimpleName();
            }
            jgen.writeStringField(getPropertyOrClassNameInVocab(currentVocab, "subClassOf",
                    "http://www.w3" + ".org/2000/01/rdf-schema#", "rdfs:"), subClass);

            jgen.writeArrayFieldStart("hydra:supportedProperty");

            Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue,
                    annotatedParameter.getParameterName());

            recurseSupportedProperties(jgen, currentVocab, annotatedParameter.getParameterType(),
                    allRootParameters, rootParameter, propertyValue, nextPropertyPathLevel);
            jgen.writeEndArray();

            jgen.writeEndObject();
            jgen.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;/* w w w.j  av a2s . c o 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 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 marshallDefinitions(Definitions def, JsonGenerator generator, String preProcessingData)
        throws JsonGenerationException, IOException {
    try {//  w  w w.jav  a 2s . com
        generator.writeStartObject();
        generator.writeObjectField("resourceId", def.getId());
        /**
         * "properties":{"name":"",
         * "documentation":"",
         * "auditing":"",
         * "monitoring":"",
         * "executable":"true",
         * "package":"com.sample",
         * "vardefs":"a,b,c,d",
         * "lanes" : "a,b,c",
         * "id":"",
         * "version":"",
         * "author":"",
         * "language":"",
         * "namespaces":"",
         * "targetnamespace":"",
         * "expressionlanguage":"",
         * "typelanguage":"",
         * "creationdate":"",
         * "modificationdate":""
         * }
         */
        Map<String, Object> props = new LinkedHashMap<String, Object>();
        props.put("namespaces", "");
        //props.put("targetnamespace", def.getTargetNamespace());
        props.put("targetnamespace", "http://www.omg.org/bpmn20");
        props.put("typelanguage", def.getTypeLanguage());
        props.put("name", unescapeXml(def.getName()));
        props.put("id", def.getId());
        props.put("expressionlanguage", def.getExpressionLanguage());
        props.put("exporter", StringUtils.isNotEmpty(def.getExporter()) ? def.getExporter() : "");
        props.put("exporterversion",
                StringUtils.isNotEmpty(def.getExporterVersion()) ? def.getExporterVersion() : "");

        // backwards compat for BZ 1048191
        if (def.getDocumentation() != null && def.getDocumentation().size() > 0) {
            props.put("documentation", def.getDocumentation().get(0).getText());
        }

        for (RootElement rootElement : def.getRootElements()) {
            if (rootElement instanceof Process) {
                // have to wait for process node to finish properties and stencil marshalling
                props.put("executable", ((Process) rootElement).isIsExecutable() + "");
                props.put("id", rootElement.getId());
                if (rootElement.getDocumentation() != null && rootElement.getDocumentation().size() > 0) {
                    props.put("documentation", rootElement.getDocumentation().get(0).getText());
                }
                Process pr = (Process) rootElement;
                if (pr.getName() != null && pr.getName().length() > 0) {
                    props.put("processn", unescapeXml(((Process) rootElement).getName()));
                }

                List<Property> processProperties = ((Process) rootElement).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 += ",";
                        }
                    }
                    props.put("vardefs", propVal);
                }

                // packageName and version and adHoc are jbpm-specific extension attribute
                Iterator<FeatureMap.Entry> iter = ((Process) rootElement).getAnyAttribute().iterator();
                while (iter.hasNext()) {
                    FeatureMap.Entry entry = iter.next();
                    if (entry.getEStructuralFeature().getName().equals("packageName")) {
                        props.put("package", entry.getValue());
                    }

                    if (entry.getEStructuralFeature().getName().equals("version")) {
                        props.put("version", entry.getValue());
                    }

                    if (entry.getEStructuralFeature().getName().equals("adHoc")) {
                        props.put("adhocprocess", entry.getValue());
                    }
                }

                // process imports, custom description and globals extension elements
                String allImports = "";
                if ((rootElement).getExtensionValues() != null
                        && (rootElement).getExtensionValues().size() > 0) {
                    String importsStr = "";
                    String globalsStr = "";

                    for (ExtensionAttributeValue extattrval : rootElement.getExtensionValues()) {
                        FeatureMap extensionElements = extattrval.getValue();

                        @SuppressWarnings("unchecked")
                        List<ImportType> importExtensions = (List<ImportType>) extensionElements
                                .get(DroolsPackage.Literals.DOCUMENT_ROOT__IMPORT, true);
                        @SuppressWarnings("unchecked")
                        List<GlobalType> globalExtensions = (List<GlobalType>) extensionElements
                                .get(DroolsPackage.Literals.DOCUMENT_ROOT__GLOBAL, true);

                        List<MetaDataType> metadataExtensions = (List<MetaDataType>) extensionElements
                                .get(DroolsPackage.Literals.DOCUMENT_ROOT__META_DATA, true);

                        for (ImportType importType : importExtensions) {
                            importsStr += importType.getName();
                            importsStr += "|default,";
                        }

                        for (GlobalType globalType : globalExtensions) {
                            globalsStr += (globalType.getIdentifier() + ":" + globalType.getType());
                            globalsStr += ",";
                        }

                        for (MetaDataType metaType : metadataExtensions) {
                            if (metaType.getName().equals("customDescription")) {
                                props.put("customdescription", metaType.getMetaValue());
                            } else if (metaType.getName().equals("customCaseIdPrefix")) {
                                props.put("customcaseidprefix", metaType.getMetaValue());
                            } else if (metaType.getName().equals("customCaseRoles")) {
                                props.put("customcaseroles", metaType.getMetaValue());
                            } else if (metaType.getName().equals("customSLADueDate")) {
                                props.put("customsladuedate", metaType.getMetaValue());
                            } else {
                                props.put(metaType.getName(), metaType.getMetaValue());
                            }
                        }
                    }
                    allImports += importsStr;
                    if (globalsStr.length() > 0) {
                        if (globalsStr.endsWith(",")) {
                            globalsStr = globalsStr.substring(0, globalsStr.length() - 1);
                        }
                        props.put("globals", globalsStr);
                    }
                }
                // definitions imports (wsdl)
                List<org.eclipse.bpmn2.Import> wsdlImports = def.getImports();
                if (wsdlImports != null) {
                    for (org.eclipse.bpmn2.Import imp : wsdlImports) {
                        allImports += imp.getLocation() + "|" + imp.getNamespace() + "|wsdl,";
                    }
                }
                if (allImports.endsWith(",")) {
                    allImports = allImports.substring(0, allImports.length() - 1);
                }
                props.put("imports", allImports);

                // simulation
                if (_simulationScenario != null && _simulationScenario.getScenarioParameters() != null) {
                    props.put("currency",
                            _simulationScenario.getScenarioParameters().getBaseCurrencyUnit() == null ? ""
                                    : _simulationScenario.getScenarioParameters().getBaseCurrencyUnit());
                    props.put("timeunit",
                            _simulationScenario.getScenarioParameters().getBaseTimeUnit().getName());
                }
                marshallProperties(props, generator);
                marshallStencil("BPMNDiagram", generator);
                linkSequenceFlows(((Process) rootElement).getFlowElements());
                marshallProcess((Process) rootElement, def, generator, preProcessingData);
            } else if (rootElement instanceof Interface) {
                // TODO
            } else if (rootElement instanceof ItemDefinition) {
                // TODO
            } else if (rootElement instanceof Resource) {
                // TODO
            } else if (rootElement instanceof Error) {
                // TODO
            } else if (rootElement instanceof Message) {
                // TODO
            } else if (rootElement instanceof Signal) {
                // TODO
            } else if (rootElement instanceof Escalation) {
                // TODO
            } else if (rootElement instanceof Collaboration) {

            } else {
                _logger.warn("Unknown root element " + rootElement + ". This element will not be parsed.");
            }
        }

        generator.writeObjectFieldStart("stencilset");
        generator.writeObjectField("url", this.profile.getStencilSetURL());
        generator.writeObjectField("namespace", this.profile.getStencilSetNamespaceURL());
        generator.writeEndObject();
        generator.writeArrayFieldStart("ssextensions");
        generator.writeObject(this.profile.getStencilSetExtensionURL());
        generator.writeEndArray();
        generator.writeEndObject();
    } finally {
        _diagramElements.clear();
    }
}