Search in sources :

Example 1 with DMNDI

use of org.kie.dmn.model.v1_2.dmndi.DMNDI in project kie-wb-common by kiegroup.

the class DMNMarshallerStandalone method marshall.

@Override
@SuppressWarnings("unchecked")
public String marshall(final Diagram<Graph, Metadata> diagram) {
    final Graph<?, Node<View, ?>> g = diagram.getGraph();
    final Map<String, org.kie.dmn.model.api.DRGElement> nodes = new HashMap<>();
    final Map<String, org.kie.dmn.model.api.TextAnnotation> textAnnotations = new HashMap<>();
    final Node<View<DMNDiagram>, ?> dmnDiagramRoot = (Node<View<DMNDiagram>, ?>) findDMNDiagramRoot(g);
    final Definitions definitionsStunnerPojo = ((DMNDiagram) DefinitionUtils.getElementDefinition(dmnDiagramRoot)).getDefinitions();
    cleanImportedItemDefinitions(definitionsStunnerPojo);
    final org.kie.dmn.model.api.Definitions definitions = DefinitionsConverter.dmnFromWB(definitionsStunnerPojo);
    if (definitions.getExtensionElements() == null) {
        if (definitions instanceof org.kie.dmn.model.v1_1.KieDMNModelInstrumentedBase) {
            definitions.setExtensionElements(new org.kie.dmn.model.v1_1.TDMNElement.TExtensionElements());
        } else if (definitions instanceof org.kie.dmn.model.v1_2.KieDMNModelInstrumentedBase) {
            definitions.setExtensionElements(new org.kie.dmn.model.v1_2.TDMNElement.TExtensionElements());
        } else {
            definitions.setExtensionElements(new org.kie.dmn.model.v1_2.TDMNElement.TExtensionElements());
        }
    }
    if (definitions.getDMNDI() == null) {
        definitions.setDMNDI(new DMNDI());
    }
    final org.kie.dmn.model.api.dmndi.DMNDiagram dmnDDDMNDiagram = new org.kie.dmn.model.v1_2.dmndi.DMNDiagram();
    definitions.getDMNDI().getDMNDiagram().add(dmnDDDMNDiagram);
    final List<DMNEdge> dmnEdges = new ArrayList<>();
    // Convert relative positioning to absolute
    for (Node<?, ?> node : g.nodes()) {
        PointUtils.convertToAbsoluteBounds(node);
    }
    // Setup callback for marshalling ComponentWidths
    if (dmnDDDMNDiagram.getExtension() == null) {
        dmnDDDMNDiagram.setExtension(new DiagramElement.Extension());
    }
    final ComponentsWidthsExtension componentsWidthsExtension = new ComponentsWidthsExtension();
    dmnDDDMNDiagram.getExtension().getAny().add(componentsWidthsExtension);
    final Consumer<ComponentWidths> componentWidthsConsumer = cw -> componentsWidthsExtension.getComponentsWidths().add(cw);
    // Iterate Graph processing nodes..
    for (Node<?, ?> node : g.nodes()) {
        if (node.getContent() instanceof View<?>) {
            final View<?> view = (View<?>) node.getContent();
            if (view.getDefinition() instanceof DRGElement) {
                final DRGElement drgElement = (org.kie.workbench.common.dmn.api.definition.model.DRGElement) view.getDefinition();
                if (!drgElement.isAllowOnlyVisualChange()) {
                    nodes.put(drgElement.getId().getValue(), stunnerToDMN(node, componentWidthsConsumer));
                }
                dmnDDDMNDiagram.getDMNDiagramElement().add(stunnerToDDExt(definitionsStunnerPojo, (View<? extends DMNElement>) view));
            } else if (view.getDefinition() instanceof TextAnnotation) {
                final TextAnnotation textAnnotation = (TextAnnotation) view.getDefinition();
                textAnnotations.put(textAnnotation.getId().getValue(), textAnnotationConverter.dmnFromNode((Node<View<TextAnnotation>, ?>) node, componentWidthsConsumer));
                dmnDDDMNDiagram.getDMNDiagramElement().add(stunnerToDDExt(definitionsStunnerPojo, (View<? extends DMNElement>) view));
                final List<org.kie.dmn.model.api.Association> associations = AssociationConverter.dmnFromWB((Node<View<TextAnnotation>, ?>) node);
                definitions.getArtifact().addAll(associations);
            }
            // DMNDI Edge management.
            final List<Edge<?, ?>> inEdges = (List<Edge<?, ?>>) node.getInEdges();
            for (Edge<?, ?> e : inEdges) {
                if (e.getContent() instanceof ViewConnector) {
                    final ViewConnector connectionContent = (ViewConnector) e.getContent();
                    DiscreteConnection sourceConnection = (DiscreteConnection) connectionContent.getSourceConnection().orElse(null);
                    DiscreteConnection targetConnection = (DiscreteConnection) connectionContent.getTargetConnection().orElse(null);
                    if (sourceConnection != null && targetConnection != null) {
                        Point2D sourcePoint = sourceConnection.getLocation();
                        Point2D targetPoint = targetConnection.getLocation();
                        final Node<?, ?> sourceNode = e.getSourceNode();
                        final View<?> sourceView = (View<?>) sourceNode.getContent();
                        double xSource = xOfBound(upperLeftBound(sourceView));
                        double ySource = yOfBound(upperLeftBound(sourceView));
                        double xTarget = xOfBound(upperLeftBound(view));
                        double yTarget = yOfBound(upperLeftBound(view));
                        if (sourcePoint == null) {
                            // If the "connection source/target location is null" assume it's the centre of the shape.
                            if (sourceView.getDefinition() instanceof DMNViewDefinition) {
                                DMNViewDefinition dmnViewDefinition = (DMNViewDefinition) sourceView.getDefinition();
                                xSource += dmnViewDefinition.getDimensionsSet().getWidth().getValue() / 2;
                                ySource += dmnViewDefinition.getDimensionsSet().getHeight().getValue() / 2;
                            }
                            sourcePoint = Point2D.create(xSource, ySource);
                        } else {
                            // If it is non-null it is relative to the source/target shape location.
                            sourcePoint = Point2D.create(xSource + sourcePoint.getX(), ySource + sourcePoint.getY());
                        }
                        if (targetPoint == null) {
                            // If the "connection source/target location is null" assume it's the centre of the shape.
                            if (view.getDefinition() instanceof DMNViewDefinition) {
                                DMNViewDefinition dmnViewDefinition = (DMNViewDefinition) view.getDefinition();
                                xTarget += dmnViewDefinition.getDimensionsSet().getWidth().getValue() / 2;
                                yTarget += dmnViewDefinition.getDimensionsSet().getHeight().getValue() / 2;
                            }
                            targetPoint = Point2D.create(xTarget, yTarget);
                        } else {
                            // If it is non-null it is relative to the source/target shape location.
                            targetPoint = Point2D.create(xTarget + targetPoint.getX(), yTarget + targetPoint.getY());
                        }
                        final DMNEdge dmnEdge = new org.kie.dmn.model.v1_2.dmndi.DMNEdge();
                        // DMNDI edge elementRef is uuid of Stunner edge,
                        // with the only exception when edge contains as content a DMN Association (Association is an edge)
                        String uuid = e.getUUID();
                        if (e.getContent() instanceof View<?>) {
                            final View<?> edgeView = (View<?>) e.getContent();
                            if (edgeView.getDefinition() instanceof Association) {
                                uuid = ((Association) edgeView.getDefinition()).getId().getValue();
                            }
                        }
                        String autoConnectionId = "";
                        if (sourceConnection.isAuto()) {
                            autoConnectionId += AUTO_SOURCE_CONNECTION;
                        }
                        if (targetConnection.isAuto()) {
                            autoConnectionId += AUTO_TARGET_CONNECTION;
                        }
                        dmnEdge.setId("dmnedge-" + uuid + autoConnectionId);
                        dmnEdge.setDmnElementRef(new QName(uuid));
                        dmnEdge.getWaypoint().add(PointUtils.point2dToDMNDIPoint(sourcePoint));
                        for (ControlPoint cp : connectionContent.getControlPoints()) {
                            dmnEdge.getWaypoint().add(PointUtils.point2dToDMNDIPoint(cp.getLocation()));
                        }
                        dmnEdge.getWaypoint().add(PointUtils.point2dToDMNDIPoint(targetPoint));
                        dmnEdges.add(dmnEdge);
                    }
                }
            }
        }
    }
    nodes.values().forEach(n -> {
        n.setParent(definitions);
        definitions.getDrgElement().add(n);
    });
    textAnnotations.values().forEach(definitions.getArtifact()::add);
    // add DMNEdge last.
    dmnDDDMNDiagram.getDMNDiagramElement().addAll(dmnEdges);
    return marshaller.marshal(definitions);
}
Also used : Edge(org.kie.workbench.common.stunner.core.graph.Edge) PointUtils.yOfBound(org.kie.workbench.common.dmn.backend.definition.v1_1.dd.PointUtils.yOfBound) PointUtils.xOfBound(org.kie.workbench.common.dmn.backend.definition.v1_1.dd.PointUtils.xOfBound) DoubleConsumer(java.util.function.DoubleConsumer) Bounds(org.kie.dmn.model.api.dmndi.Bounds) Map(java.util.Map) NamedElement(org.kie.workbench.common.dmn.api.definition.model.NamedElement) FactoryManager(org.kie.workbench.common.stunner.core.api.FactoryManager) Diagram(org.kie.workbench.common.stunner.core.diagram.Diagram) HasComponentWidths(org.kie.workbench.common.dmn.api.definition.HasComponentWidths) Height(org.kie.workbench.common.dmn.api.property.dimensions.Height) Point2D(org.kie.workbench.common.stunner.core.graph.content.view.Point2D) BusinessKnowledgeModel(org.kie.workbench.common.dmn.api.definition.model.BusinessKnowledgeModel) Set(java.util.Set) BusinessKnowledgeModelConverter(org.kie.workbench.common.dmn.backend.definition.v1_1.BusinessKnowledgeModelConverter) Child(org.kie.workbench.common.stunner.core.graph.content.relationship.Child) ItemDefinition(org.kie.workbench.common.dmn.api.definition.model.ItemDefinition) PointUtils.heightOfShape(org.kie.workbench.common.dmn.backend.definition.v1_1.dd.PointUtils.heightOfShape) Stream(java.util.stream.Stream) PointUtils(org.kie.workbench.common.dmn.backend.definition.v1_1.dd.PointUtils) QName(javax.xml.namespace.QName) PointUtils.widthOfShape(org.kie.workbench.common.dmn.backend.definition.v1_1.dd.PointUtils.widthOfShape) DMNMarshaller(org.kie.dmn.api.marshalling.DMNMarshaller) PointUtils.yOfShape(org.kie.workbench.common.dmn.backend.definition.v1_1.dd.PointUtils.yOfShape) DMNDefinitionSet(org.kie.workbench.common.dmn.api.DMNDefinitionSet) DMNStyle(org.kie.dmn.model.api.dmndi.DMNStyle) Point(org.kie.dmn.model.api.dmndi.Point) Connection(org.kie.workbench.common.stunner.core.graph.content.view.Connection) Color(org.kie.dmn.model.api.dmndi.Color) ItemDefinitionPropertyConverter(org.kie.workbench.common.dmn.backend.definition.v1_1.ItemDefinitionPropertyConverter) DiagramMetadataMarshaller(org.kie.workbench.common.stunner.core.definition.service.DiagramMetadataMarshaller) ArrayList(java.util.ArrayList) FontSetPropertyConverter(org.kie.workbench.common.dmn.backend.definition.v1_1.dd.FontSetPropertyConverter) Id(org.kie.workbench.common.dmn.api.property.dmn.Id) PointUtils.upperLeftBound(org.kie.workbench.common.dmn.backend.definition.v1_1.dd.PointUtils.upperLeftBound) BiConsumer(java.util.function.BiConsumer) StreamSupport(java.util.stream.StreamSupport) BindableAdapterUtils(org.kie.workbench.common.stunner.core.definition.adapter.binding.BindableAdapterUtils) IOException(java.io.IOException) InputData(org.kie.workbench.common.dmn.api.definition.model.InputData) InputStreamReader(java.io.InputStreamReader) InputDataConverter(org.kie.workbench.common.dmn.backend.definition.v1_1.InputDataConverter) Association(org.kie.workbench.common.dmn.api.definition.model.Association) DecisionService(org.kie.workbench.common.dmn.api.definition.model.DecisionService) KnowledgeSourceConverter(org.kie.workbench.common.dmn.backend.definition.v1_1.KnowledgeSourceConverter) Graph(org.kie.workbench.common.stunner.core.graph.Graph) MagnetConnection(org.kie.workbench.common.stunner.core.graph.content.view.MagnetConnection) TextAnnotation(org.kie.workbench.common.dmn.api.definition.model.TextAnnotation) Definitions(org.kie.workbench.common.dmn.api.definition.model.Definitions) DecisionConverter(org.kie.workbench.common.dmn.backend.definition.v1_1.DecisionConverter) DefinitionUtils(org.kie.workbench.common.stunner.core.util.DefinitionUtils) DMNDecisionServiceDividerLine(org.kie.dmn.model.api.dmndi.DMNDecisionServiceDividerLine) DMNEdge(org.kie.dmn.model.api.dmndi.DMNEdge) UUID(org.kie.workbench.common.stunner.core.util.UUID) BorderColour(org.kie.workbench.common.dmn.api.property.styling.BorderColour) EdgeImpl(org.kie.workbench.common.stunner.core.graph.impl.EdgeImpl) TextAnnotationConverter(org.kie.workbench.common.dmn.backend.definition.v1_1.TextAnnotationConverter) DMNElement(org.kie.workbench.common.dmn.api.definition.model.DMNElement) Collectors.toMap(java.util.stream.Collectors.toMap) PointUtils.lowerRightBound(org.kie.workbench.common.dmn.backend.definition.v1_1.dd.PointUtils.lowerRightBound) InformationRequirement(org.kie.workbench.common.dmn.api.definition.model.InformationRequirement) DiagramElement(org.kie.dmn.model.v1_2.dmndi.DiagramElement) Collections.emptyList(java.util.Collections.emptyList) DiagramMarshaller(org.kie.workbench.common.stunner.core.definition.service.DiagramMarshaller) Import(org.kie.dmn.model.api.Import) DMNDiagram(org.kie.workbench.common.dmn.api.definition.model.DMNDiagram) Collectors(java.util.stream.Collectors) Metadata(org.kie.workbench.common.stunner.core.diagram.Metadata) Objects(java.util.Objects) DRGElement(org.kie.workbench.common.dmn.api.definition.model.DRGElement) List(java.util.List) DMNShape(org.kie.dmn.model.api.dmndi.DMNShape) ComponentWidths(org.kie.workbench.common.dmn.backend.definition.v1_1.dd.ComponentWidths) BgColour(org.kie.workbench.common.dmn.api.property.styling.BgColour) DMNDI(org.kie.dmn.model.v1_2.dmndi.DMNDI) Entry(java.util.Map.Entry) Optional(java.util.Optional) ApplicationScoped(javax.enterprise.context.ApplicationScoped) Node(org.kie.workbench.common.stunner.core.graph.Node) PointUtils.xOfShape(org.kie.workbench.common.dmn.backend.definition.v1_1.dd.PointUtils.xOfShape) PMMLDocumentMetadata(org.kie.workbench.common.dmn.api.editors.included.PMMLDocumentMetadata) Width(org.kie.workbench.common.dmn.api.property.dimensions.Width) ControlPoint(org.kie.workbench.common.stunner.core.graph.content.view.ControlPoint) RectangleDimensionsSet(org.kie.workbench.common.dmn.api.property.dimensions.RectangleDimensionsSet) DefinitionsConverter(org.kie.workbench.common.dmn.backend.definition.v1_1.DefinitionsConverter) HashMap(java.util.HashMap) View(org.kie.workbench.common.stunner.core.graph.content.view.View) ColorUtils(org.kie.workbench.common.dmn.backend.definition.v1_1.dd.ColorUtils) HashSet(java.util.HashSet) Inject(javax.inject.Inject) ComponentsWidthsExtension(org.kie.workbench.common.dmn.backend.definition.v1_1.dd.ComponentsWidthsExtension) Bound(org.kie.workbench.common.stunner.core.graph.content.Bound) BindableAdapterUtils.getDefinitionId(org.kie.workbench.common.stunner.core.definition.adapter.binding.BindableAdapterUtils.getDefinitionId) KnowledgeRequirement(org.kie.workbench.common.dmn.api.definition.model.KnowledgeRequirement) Description(org.kie.workbench.common.dmn.api.property.dmn.Description) DMNViewDefinition(org.kie.workbench.common.dmn.api.definition.DMNViewDefinition) SimpleEntry(java.util.AbstractMap.SimpleEntry) DecisionServiceDividerLineY(org.kie.workbench.common.dmn.api.property.dmn.DecisionServiceDividerLineY) StylingSet(org.kie.workbench.common.dmn.api.property.styling.StylingSet) XMLEncoderDiagramMetadataMarshaller(org.kie.workbench.common.stunner.core.backend.service.XMLEncoderDiagramMetadataMarshaller) AssociationConverter(org.kie.workbench.common.dmn.backend.definition.v1_1.AssociationConverter) DMNMarshallerImportsHelperStandalone(org.kie.workbench.common.dmn.backend.common.DMNMarshallerImportsHelperStandalone) DecisionServiceConverter(org.kie.workbench.common.dmn.backend.definition.v1_1.DecisionServiceConverter) ViewConnector(org.kie.workbench.common.stunner.core.graph.content.view.ViewConnector) AuthorityRequirement(org.kie.workbench.common.dmn.api.definition.model.AuthorityRequirement) Consumer(java.util.function.Consumer) DMNModelInstrumentedBase(org.kie.workbench.common.dmn.api.definition.model.DMNModelInstrumentedBase) KnowledgeSource(org.kie.workbench.common.dmn.api.definition.model.KnowledgeSource) Decision(org.kie.workbench.common.dmn.api.definition.model.Decision) DiscreteConnection(org.kie.workbench.common.stunner.core.graph.content.view.DiscreteConnection) InputStream(java.io.InputStream) HashMap(java.util.HashMap) Node(org.kie.workbench.common.stunner.core.graph.Node) ArrayList(java.util.ArrayList) Point2D(org.kie.workbench.common.stunner.core.graph.content.view.Point2D) DMNElement(org.kie.workbench.common.dmn.api.definition.model.DMNElement) ArrayList(java.util.ArrayList) Collections.emptyList(java.util.Collections.emptyList) List(java.util.List) DMNDiagram(org.kie.workbench.common.dmn.api.definition.model.DMNDiagram) ViewConnector(org.kie.workbench.common.stunner.core.graph.content.view.ViewConnector) DMNEdge(org.kie.dmn.model.api.dmndi.DMNEdge) DRGElement(org.kie.workbench.common.dmn.api.definition.model.DRGElement) DiscreteConnection(org.kie.workbench.common.stunner.core.graph.content.view.DiscreteConnection) DMNViewDefinition(org.kie.workbench.common.dmn.api.definition.DMNViewDefinition) DMNDI(org.kie.dmn.model.v1_2.dmndi.DMNDI) DiagramElement(org.kie.dmn.model.v1_2.dmndi.DiagramElement) Association(org.kie.workbench.common.dmn.api.definition.model.Association) TextAnnotation(org.kie.workbench.common.dmn.api.definition.model.TextAnnotation) QName(javax.xml.namespace.QName) Definitions(org.kie.workbench.common.dmn.api.definition.model.Definitions) ControlPoint(org.kie.workbench.common.stunner.core.graph.content.view.ControlPoint) View(org.kie.workbench.common.stunner.core.graph.content.view.View) HasComponentWidths(org.kie.workbench.common.dmn.api.definition.HasComponentWidths) ComponentWidths(org.kie.workbench.common.dmn.backend.definition.v1_1.dd.ComponentWidths) ComponentsWidthsExtension(org.kie.workbench.common.dmn.backend.definition.v1_1.dd.ComponentsWidthsExtension) Edge(org.kie.workbench.common.stunner.core.graph.Edge) DMNEdge(org.kie.dmn.model.api.dmndi.DMNEdge)

Example 2 with DMNDI

use of org.kie.dmn.model.v1_2.dmndi.DMNDI in project drools by kiegroup.

the class XStreamMarshaller method newXStream.

private XStream newXStream() {
    XStream xStream = XStreamUtils.createNonTrustingXStream(staxDriver, Definitions.class.getClassLoader(), DMNXStream::from);
    xStream.addPermission(new TypeHierarchyPermission(QName.class));
    xStream.addPermission(new TypeHierarchyPermission(KieDMNModelInstrumentedBase.class));
    xStream.alias("artifact", TArtifact.class);
    xStream.alias("definitions", TDefinitions.class);
    xStream.alias("inputData", TInputData.class);
    xStream.alias("decision", TDecision.class);
    xStream.alias("variable", TInformationItem.class);
    xStream.alias("informationRequirement", TInformationRequirement.class);
    xStream.alias("requiredInput", TDMNElementReference.class);
    xStream.alias("literalExpression", TLiteralExpression.class);
    xStream.alias("DMNElement", TDMNElement.class);
    xStream.alias("allowedValues", TUnaryTests.class);
    xStream.alias("artifact", TArtifact.class);
    xStream.alias("association", TAssociation.class);
    xStream.alias("authorityRequirement", TAuthorityRequirement.class);
    xStream.alias("binding", TBinding.class);
    xStream.alias("businessContextElement", TBusinessContextElement.class);
    xStream.alias("businessKnowledgeModel", TBusinessKnowledgeModel.class);
    xStream.alias("column", TInformationItem.class);
    xStream.alias("context", TContext.class);
    xStream.alias("contextEntry", TContextEntry.class);
    xStream.alias("decision", TDecision.class);
    xStream.alias("decisionMade", TDMNElementReference.class);
    xStream.alias("decisionMaker", TDMNElementReference.class);
    xStream.alias("decisionOwned", TDMNElementReference.class);
    xStream.alias("decisionOwner", TDMNElementReference.class);
    xStream.alias("decisionService", TDecisionService.class);
    xStream.alias("decisionTable", TDecisionTable.class);
    xStream.alias("defaultOutputEntry", TLiteralExpression.class);
    xStream.alias("definitions", TDefinitions.class);
    xStream.alias("drgElement", TDMNElementReference.class);
    xStream.alias("elementCollection", TElementCollection.class);
    xStream.alias("encapsulatedDecision", TDMNElementReference.class);
    xStream.alias("encapsulatedLogic", TFunctionDefinition.class);
    xStream.alias("expression", TExpression.class);
    xStream.alias("formalParameter", TInformationItem.class);
    xStream.alias("functionDefinition", TFunctionDefinition.class);
    xStream.alias("impactedPerformanceIndicator", TDMNElementReference.class);
    xStream.alias("impactingDecision", TDMNElementReference.class);
    xStream.alias("import", TImport.class);
    xStream.alias("import", TImport.class);
    // TODO where?
    xStream.alias("importedElement", String.class);
    xStream.alias("importedValues", TImportedValues.class);
    xStream.alias("informationItem", TInformationItem.class);
    xStream.alias("informationRequirement", TInformationRequirement.class);
    xStream.alias("input", TInputClause.class);
    xStream.alias("inputData", TInputData.class);
    xStream.alias("inputDecision", TDMNElementReference.class);
    xStream.alias("inputEntry", TUnaryTests.class);
    xStream.alias("inputExpression", TLiteralExpression.class);
    xStream.alias("inputValues", TUnaryTests.class);
    xStream.alias("invocation", TInvocation.class);
    xStream.alias("itemComponent", TItemDefinition.class);
    xStream.alias("itemDefinition", TItemDefinition.class);
    xStream.alias("knowledgeRequirement", TKnowledgeRequirement.class);
    xStream.alias("knowledgeSource", TKnowledgeSource.class);
    xStream.alias("literalExpression", TLiteralExpression.class);
    xStream.alias("namedElement", TNamedElement.class);
    xStream.alias("organizationUnit", TOrganizationUnit.class);
    xStream.alias("output", TOutputClause.class);
    xStream.alias("outputDecision", TDMNElementReference.class);
    xStream.alias("outputEntry", TLiteralExpression.class);
    xStream.alias("outputValues", TUnaryTests.class);
    xStream.alias("owner", TDMNElementReference.class);
    xStream.alias("parameter", TInformationItem.class);
    xStream.alias("performanceIndicator", TPerformanceIndicator.class);
    xStream.alias("relation", TRelation.class);
    xStream.alias("requiredAuthority", TDMNElementReference.class);
    xStream.alias("requiredDecision", TDMNElementReference.class);
    xStream.alias("requiredInput", TDMNElementReference.class);
    xStream.alias("requiredKnowledge", TDMNElementReference.class);
    xStream.alias("rule", TDecisionRule.class);
    xStream.alias("sourceRef", TDMNElementReference.class);
    xStream.alias("supportedObjective", TDMNElementReference.class);
    xStream.alias("targetRef", TDMNElementReference.class);
    xStream.alias("textAnnotation", TTextAnnotation.class);
    // TODO where?
    xStream.alias("type", String.class);
    xStream.alias("typeRef", QName.class);
    xStream.alias("usingProcess", TDMNElementReference.class);
    xStream.alias("usingTask", TDMNElementReference.class);
    xStream.alias("variable", TInformationItem.class);
    xStream.alias("row", org.kie.dmn.model.v1_2.TList.class);
    xStream.alias("list", org.kie.dmn.model.v1_2.TList.class);
    xStream.alias("extensionElements", TDMNElement.TExtensionElements.class);
    // Manually imported TEXT = String
    xStream.alias(LiteralExpressionConverter.TEXT, String.class);
    // unnecessary 'text' key repetition:        xStream.alias( TextAnnotationConverter.TEXT, String.class );
    // unnecessary 'text' key repetition:        xStream.alias( UnaryTestsConverter.TEXT, String.class );
    xStream.alias(DecisionConverter.QUESTION, String.class);
    xStream.alias(DecisionConverter.ALLOWED_ANSWERS, String.class);
    xStream.alias(DMNElementConverter.DESCRIPTION, String.class);
    // unnecessary 'text' key repetition:      xStream.alias("text", xsd:string.class );
    // unnecessary 'text' key repetition:      xStream.alias("text", xsd:string.class );
    // unnecessary 'text' key repetition:      xStream.alias("text", xsd:string.class );
    // xStream.alias("question", xsd:string.class );
    // xStream.alias("allowedAnswers", xsd:string.class );
    // xStream.alias("description", xsd:string.class );
    // DMN v1.2:
    // Note, to comply with NS for XStream need also to adjust entries inside DMNModelInstrumentedBaseConverter
    xStream.alias("annotation", TRuleAnnotationClause.class);
    xStream.alias("annotationEntry", TRuleAnnotation.class);
    xStream.registerConverter(new RuleAnnotationClauseConverter(xStream));
    xStream.registerConverter(new RuleAnnotationConverter(xStream));
    xStream.alias("DMNDI", DMNDI.class);
    xStream.registerConverter(new DMNDIConverter(xStream));
    xStream.alias("DMNDiagram", DMNDiagram.class);
    xStream.registerConverter(new DMNDiagramConverter(xStream));
    xStream.alias("DMNStyle", DMNStyle.class);
    xStream.registerConverter(new DMNStyleConverter(xStream));
    xStream.alias("Size", Dimension.class);
    xStream.registerConverter(new DimensionConverter(xStream));
    xStream.alias("DMNShape", DMNShape.class);
    xStream.registerConverter(new DMNShapeConverter(xStream));
    xStream.alias("FillColor", Color.class);
    xStream.alias("StrokeColor", Color.class);
    xStream.alias("FontColor", Color.class);
    xStream.registerConverter(new ColorConverter(xStream));
    xStream.alias("Bounds", Bounds.class);
    xStream.registerConverter(new BoundsConverter(xStream));
    xStream.alias("DMNLabel", DMNLabel.class);
    xStream.registerConverter(new DMNLabelConverter(xStream));
    xStream.alias("DMNEdge", DMNEdge.class);
    xStream.registerConverter(new DMNEdgeConverter(xStream));
    xStream.alias("DMNDecisionServiceDividerLine", DMNDecisionServiceDividerLine.class);
    xStream.registerConverter(new DMNDecisionServiceDividerLineConverter(xStream));
    xStream.alias("waypoint", Point.class);
    xStream.registerConverter(new PointConverter(xStream));
    xStream.alias("extension", DiagramElement.Extension.class);
    xStream.alias(DMNLabelConverter.TEXT, String.class);
    xStream.registerConverter(new AssociationConverter(xStream));
    xStream.registerConverter(new AuthorityRequirementConverter(xStream));
    xStream.registerConverter(new BindingConverter(xStream));
    xStream.registerConverter(new BusinessKnowledgeModelConverter(xStream));
    xStream.registerConverter(new ContextConverter(xStream));
    xStream.registerConverter(new ContextEntryConverter(xStream));
    xStream.registerConverter(new DecisionConverter(xStream));
    xStream.registerConverter(new DecisionRuleConverter(xStream));
    xStream.registerConverter(new DecisionServiceConverter(xStream));
    xStream.registerConverter(new DecisionTableConverter(xStream));
    xStream.registerConverter(new DefinitionsConverter(xStream));
    xStream.registerConverter(new DMNElementReferenceConverter(xStream));
    xStream.registerConverter(new FunctionDefinitionConverter(xStream));
    xStream.registerConverter(new ImportConverter(xStream));
    xStream.registerConverter(new ImportedValuesConverter(xStream));
    xStream.registerConverter(new InformationItemConverter(xStream));
    xStream.registerConverter(new InformationRequirementConverter(xStream));
    xStream.registerConverter(new InputClauseConverter(xStream));
    xStream.registerConverter(new InputDataConverter(xStream));
    xStream.registerConverter(new InvocationConverter(xStream));
    xStream.registerConverter(new ItemDefinitionConverter(xStream));
    xStream.registerConverter(new KnowledgeRequirementConverter(xStream));
    xStream.registerConverter(new KnowledgeSourceConverter(xStream));
    xStream.registerConverter(new LiteralExpressionConverter(xStream));
    xStream.registerConverter(new OrganizationUnitConverter(xStream));
    xStream.registerConverter(new OutputClauseConverter(xStream));
    xStream.registerConverter(new PerformanceIndicatorConverter(xStream));
    xStream.registerConverter(new RelationConverter(xStream));
    xStream.registerConverter(new TextAnnotationConverter(xStream));
    xStream.registerConverter(new UnaryTestsConverter(xStream));
    xStream.registerConverter(new QNameConverter());
    xStream.registerConverter(new DMNListConverter(xStream));
    xStream.registerConverter(new ElementCollectionConverter(xStream));
    xStream.registerConverter(new ExtensionElementsConverter(xStream, extensionRegisters));
    xStream.registerConverter(new DiagramElementExtensionConverter(xStream, extensionRegisters));
    xStream.ignoreUnknownElements();
    for (DMNExtensionRegister extensionRegister : extensionRegisters) {
        extensionRegister.registerExtensionConverters(xStream);
    }
    return xStream;
}
Also used : KieDMNModelInstrumentedBase(org.kie.dmn.model.v1_2.KieDMNModelInstrumentedBase) XStream(com.thoughtworks.xstream.XStream) DMNXStream(org.kie.dmn.backend.marshalling.v1x.DMNXStream) DMNExtensionRegister(org.kie.dmn.api.marshalling.DMNExtensionRegister) DiagramElement(org.kie.dmn.model.v1_2.dmndi.DiagramElement) DMNXStream(org.kie.dmn.backend.marshalling.v1x.DMNXStream) TypeHierarchyPermission(com.thoughtworks.xstream.security.TypeHierarchyPermission) QName(javax.xml.namespace.QName) TDefinitions(org.kie.dmn.model.v1_2.TDefinitions) Definitions(org.kie.dmn.model.api.Definitions) TDMNElement(org.kie.dmn.model.v1_2.TDMNElement)

Example 3 with DMNDI

use of org.kie.dmn.model.v1_2.dmndi.DMNDI in project drools by kiegroup.

the class DefinitionsConverter method assignChildElement.

@Override
protected void assignChildElement(Object parent, String nodeName, Object child) {
    Definitions def = (Definitions) parent;
    if (IMPORT.equals(nodeName)) {
        def.getImport().add((Import) child);
    } else if (ITEM_DEFINITION.equals(nodeName)) {
        def.getItemDefinition().add((ItemDefinition) child);
    } else if (child instanceof DRGElement) {
        def.getDrgElement().add((DRGElement) child);
    } else if (child instanceof Artifact) {
        def.getArtifact().add((Artifact) child);
    } else if (ELEMENT_COLLECTION.equals(nodeName)) {
        def.getElementCollection().add((ElementCollection) child);
    } else if (child instanceof BusinessContextElement) {
        def.getBusinessContextElement().add((BusinessContextElement) child);
    } else if (child instanceof DMNDI) {
        DMNDI dmndi = (DMNDI) child;
        dmndi.normalize();
        def.setDMNDI(dmndi);
    } else {
        super.assignChildElement(def, nodeName, child);
    }
}
Also used : TDefinitions(org.kie.dmn.model.v1_2.TDefinitions) Definitions(org.kie.dmn.model.api.Definitions) ItemDefinition(org.kie.dmn.model.api.ItemDefinition) DMNDI(org.kie.dmn.model.api.dmndi.DMNDI) BusinessContextElement(org.kie.dmn.model.api.BusinessContextElement) Artifact(org.kie.dmn.model.api.Artifact) DRGElement(org.kie.dmn.model.api.DRGElement)

Example 4 with DMNDI

use of org.kie.dmn.model.v1_2.dmndi.DMNDI in project drools by kiegroup.

the class UnmarshalMarshalTest method testRoundTrip.

public void testRoundTrip(String subdir, String xmlfile, DMNMarshaller marshaller, Source schemaSource) throws Exception {
    File baseOutputDir = new File("target/test-xmlunit/");
    File testClassesBaseDir = new File("target/test-classes/");
    File inputXMLFile = new File(testClassesBaseDir, subdir + xmlfile);
    FileInputStream fis = new FileInputStream(inputXMLFile);
    Definitions unmarshal = marshaller.unmarshal(new InputStreamReader(fis));
    Validator v = Validator.forLanguage(Languages.W3C_XML_SCHEMA_NS_URI);
    v.setSchemaSource(schemaSource);
    ValidationResult validateInputResult = v.validateInstance(new StreamSource(inputXMLFile));
    if (!validateInputResult.isValid()) {
        for (ValidationProblem p : validateInputResult.getProblems()) {
            LOG.error("{}", p);
        }
    }
    assertTrue(validateInputResult.isValid());
    final File subdirFile = new File(baseOutputDir, subdir);
    if (!subdirFile.mkdirs()) {
        LOG.warn("mkdirs() failed for File: ", subdirFile.getAbsolutePath());
    }
    FileOutputStream sourceFos = new FileOutputStream(new File(baseOutputDir, subdir + "a." + xmlfile));
    Files.copy(new File(testClassesBaseDir, subdir + xmlfile).toPath(), sourceFos);
    sourceFos.flush();
    sourceFos.close();
    LOG.debug("{}", marshaller.marshal(unmarshal));
    File outputXMLFile = new File(baseOutputDir, subdir + "b." + xmlfile);
    try (FileWriter targetFos = new FileWriter(outputXMLFile)) {
        marshaller.marshal(unmarshal, targetFos);
    }
    // Should also validate output XML:
    ValidationResult validateOutputResult = v.validateInstance(new StreamSource(outputXMLFile));
    if (!validateOutputResult.isValid()) {
        for (ValidationProblem p : validateOutputResult.getProblems()) {
            LOG.error("{}", p);
        }
    }
    assertTrue(validateOutputResult.isValid());
    LOG.debug("\n---\nDefault XMLUnit comparison:");
    Source control = Input.fromFile(inputXMLFile).build();
    Source test = Input.fromFile(outputXMLFile).build();
    Diff allDiffsSimilarAndDifferent = DiffBuilder.compare(control).withTest(test).build();
    allDiffsSimilarAndDifferent.getDifferences().forEach(m -> LOG.debug("{}", m));
    LOG.info("XMLUnit comparison with customized similarity for defaults:");
    // in the following a manual DifferenceEvaluator is needed until XMLUnit is configured for properly parsing the XSD linked inside the XML,
    // in order to detect the optional+defaultvalue attributes of xml element which might be implicit in source-test, and explicit in test-serialized.
    /*
         * $ grep -Eo "<xsd:attribute name=\\\"([^\\\"]*)\\\" type=\\\"([^\\\"]*)\\\" use=\\\"optional\\\" default=\\\"([^\\\"])*\\\"" dmn.xsd 
<xsd:attribute name="expressionLanguage" type="xsd:anyURI" use="optional" default="http://www.omg.org/spec/FEEL/20140401"
<xsd:attribute name="typeLanguage" type="xsd:anyURI" use="optional" default="http://www.omg.org/spec/FEEL/20140401"
<xsd:attribute name="isCollection" type="xsd:boolean" use="optional" default="false"
<xsd:attribute name="hitPolicy" type="tHitPolicy" use="optional" default="UNIQUE"
<xsd:attribute name="preferredOrientation" type="tDecisionTableOrientation" use="optional" default="Rule-as-Row"
DMNv1.2:
<xsd:attribute name="kind" type="tFunctionKind" default="FEEL"/>
<xsd:attribute name="textFormat" type="xsd:string" default="text/plain"/>
<xsd:attribute name="associationDirection" type="tAssociationDirection" default="None"/>
DMNDIv1.2:
<xsd:attribute name="isCollapsed" type="xsd:boolean" use="optional" default="false"/>
         */
    Set<QName> attrWhichCanDefault = new HashSet<QName>();
    attrWhichCanDefault.addAll(Arrays.asList(new QName[] { new QName("expressionLanguage"), new QName("typeLanguage"), new QName("isCollection"), new QName("hitPolicy"), new QName("preferredOrientation"), new QName("kind"), new QName("textFormat"), new QName("associationDirection"), new QName("isCollapsed") }));
    Set<String> nodeHavingDefaultableAttr = new HashSet<>();
    nodeHavingDefaultableAttr.addAll(Arrays.asList(new String[] { "definitions", "decisionTable", "itemDefinition", "itemComponent", "encapsulatedLogic", "textAnnotation", "association", "DMNShape" }));
    Diff checkSimilar = DiffBuilder.compare(control).withTest(test).withDifferenceEvaluator(DifferenceEvaluators.chain(DifferenceEvaluators.Default, ((comparison, outcome) -> {
        if (outcome == ComparisonResult.DIFFERENT && comparison.getType() == ComparisonType.ELEMENT_NUM_ATTRIBUTES) {
            if (comparison.getControlDetails().getTarget().getNodeName().equals(comparison.getTestDetails().getTarget().getNodeName()) && nodeHavingDefaultableAttr.contains(safeStripDMNPRefix(comparison.getControlDetails().getTarget()))) {
                return ComparisonResult.SIMILAR;
            }
        }
        // DMNDI/DMNDiagram#documentation is actually deserialized escaped with newlines as &#10; by the XML JDK infra.
        if (outcome == ComparisonResult.DIFFERENT && comparison.getType() == ComparisonType.ATTR_VALUE) {
            if (comparison.getControlDetails().getTarget().getNodeName().equals(comparison.getTestDetails().getTarget().getNodeName()) && comparison.getControlDetails().getTarget().getNodeType() == Node.ATTRIBUTE_NODE && comparison.getControlDetails().getTarget().getLocalName().equals("documentation")) {
                return ComparisonResult.SIMILAR;
            }
        }
        if (outcome == ComparisonResult.DIFFERENT && comparison.getType() == ComparisonType.ATTR_NAME_LOOKUP) {
            boolean testIsDefaulableAttribute = false;
            QName whichDefaultableAttr = null;
            if (comparison.getControlDetails().getValue() == null && attrWhichCanDefault.contains(comparison.getTestDetails().getValue())) {
                for (QName a : attrWhichCanDefault) {
                    boolean check = comparison.getTestDetails().getXPath().endsWith("@" + a);
                    if (check) {
                        testIsDefaulableAttribute = true;
                        whichDefaultableAttr = a;
                        continue;
                    }
                }
            }
            if (testIsDefaulableAttribute) {
                if (comparison.getTestDetails().getXPath().equals(comparison.getControlDetails().getXPath() + "/@" + whichDefaultableAttr)) {
                    // TODO missing to check the explicited option attribute has value set to the actual default value.
                    return ComparisonResult.SIMILAR;
                }
            }
        }
        return outcome;
    }))).ignoreWhitespace().checkForSimilar().build();
    checkSimilar.getDifferences().forEach(m -> LOG.error("{}", m));
    if (!checkSimilar.getDifferences().iterator().hasNext()) {
        LOG.info("[ EMPTY - no diffs using customized similarity ]");
    }
    assertFalse("XML are NOT similar: " + checkSimilar.toString(), checkSimilar.hasDifferences());
}
Also used : Arrays(java.util.Arrays) DMNStyle(org.kie.dmn.model.api.dmndi.DMNStyle) Diff(org.xmlunit.diff.Diff) StreamSource(javax.xml.transform.stream.StreamSource) ValidationResult(org.xmlunit.validation.ValidationResult) LoggerFactory(org.slf4j.LoggerFactory) ComparisonResult(org.xmlunit.diff.ComparisonResult) Source(javax.xml.transform.Source) Definitions(org.kie.dmn.model.api.Definitions) HashSet(java.util.HashSet) DMNMarshallerFactory(org.kie.dmn.backend.marshalling.v1x.DMNMarshallerFactory) Node(org.w3c.dom.Node) MyTestRegister(org.kie.dmn.backend.marshalling.v1_2.extensions.MyTestRegister) Logger(org.slf4j.Logger) Files(java.nio.file.Files) DiffBuilder(org.xmlunit.builder.DiffBuilder) DifferenceEvaluators(org.xmlunit.diff.DifferenceEvaluators) FileWriter(java.io.FileWriter) FileOutputStream(java.io.FileOutputStream) Set(java.util.Set) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) FileInputStream(java.io.FileInputStream) Input(org.xmlunit.builder.Input) KieDMNModelInstrumentedBase(org.kie.dmn.model.v1_2.KieDMNModelInstrumentedBase) InputStreamReader(java.io.InputStreamReader) File(java.io.File) Languages(org.xmlunit.validation.Languages) DMNShape(org.kie.dmn.model.api.dmndi.DMNShape) ValidationProblem(org.xmlunit.validation.ValidationProblem) Assert.assertFalse(org.junit.Assert.assertFalse) QName(javax.xml.namespace.QName) ComparisonType(org.xmlunit.diff.ComparisonType) Validator(org.xmlunit.validation.Validator) DMNMarshaller(org.kie.dmn.api.marshalling.DMNMarshaller) Assert.assertEquals(org.junit.Assert.assertEquals) InputStreamReader(java.io.InputStreamReader) Diff(org.xmlunit.diff.Diff) QName(javax.xml.namespace.QName) Definitions(org.kie.dmn.model.api.Definitions) StreamSource(javax.xml.transform.stream.StreamSource) FileWriter(java.io.FileWriter) ValidationProblem(org.xmlunit.validation.ValidationProblem) ValidationResult(org.xmlunit.validation.ValidationResult) FileInputStream(java.io.FileInputStream) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) FileOutputStream(java.io.FileOutputStream) File(java.io.File) Validator(org.xmlunit.validation.Validator) HashSet(java.util.HashSet)

Example 5 with DMNDI

use of org.kie.dmn.model.v1_2.dmndi.DMNDI in project drools by kiegroup.

the class DefinitionsConverter method writeChildren.

@Override
protected void writeChildren(HierarchicalStreamWriter writer, MarshallingContext context, Object parent) {
    super.writeChildren(writer, context, parent);
    Definitions def = (Definitions) parent;
    for (Import i : def.getImport()) {
        writeChildrenNode(writer, context, i, IMPORT);
    }
    for (ItemDefinition id : def.getItemDefinition()) {
        writeChildrenNode(writer, context, id, ITEM_DEFINITION);
    }
    for (DRGElement e : def.getDrgElement()) {
        String nodeName = DRG_ELEMENT;
        if (e instanceof BusinessKnowledgeModel) {
            nodeName = "businessKnowledgeModel";
        } else if (e instanceof Decision) {
            nodeName = "decision";
        } else if (e instanceof InputData) {
            nodeName = "inputData";
        } else if (e instanceof KnowledgeSource) {
            nodeName = "knowledgeSource";
        } else if (e instanceof DecisionService) {
            nodeName = "decisionService";
        }
        writeChildrenNode(writer, context, e, nodeName);
    }
    for (Artifact a : def.getArtifact()) {
        String nodeName = ARTIFACT;
        if (a instanceof Association) {
            nodeName = "association";
        } else if (a instanceof TextAnnotation) {
            nodeName = "textAnnotation";
        }
        writeChildrenNode(writer, context, a, nodeName);
    }
    for (ElementCollection ec : def.getElementCollection()) {
        writeChildrenNode(writer, context, ec, ELEMENT_COLLECTION);
    }
    for (BusinessContextElement bce : def.getBusinessContextElement()) {
        String nodeName = BUSINESS_CONTEXT_ELEMENT;
        if (bce instanceof OrganizationUnit) {
            nodeName = "organizationUnit";
        } else if (bce instanceof PerformanceIndicator) {
            nodeName = "performanceIndicator";
        }
        writeChildrenNode(writer, context, bce, nodeName);
    }
    if (def.getDMNDI() != null) {
        writeChildrenNode(writer, context, def.getDMNDI(), "DMNDI");
    }
}
Also used : Import(org.kie.dmn.model.api.Import) PerformanceIndicator(org.kie.dmn.model.api.PerformanceIndicator) TDefinitions(org.kie.dmn.model.v1_2.TDefinitions) Definitions(org.kie.dmn.model.api.Definitions) ItemDefinition(org.kie.dmn.model.api.ItemDefinition) BusinessContextElement(org.kie.dmn.model.api.BusinessContextElement) Decision(org.kie.dmn.model.api.Decision) Artifact(org.kie.dmn.model.api.Artifact) DecisionService(org.kie.dmn.model.api.DecisionService) Association(org.kie.dmn.model.api.Association) KnowledgeSource(org.kie.dmn.model.api.KnowledgeSource) OrganizationUnit(org.kie.dmn.model.api.OrganizationUnit) BusinessKnowledgeModel(org.kie.dmn.model.api.BusinessKnowledgeModel) ElementCollection(org.kie.dmn.model.api.ElementCollection) InputData(org.kie.dmn.model.api.InputData) TextAnnotation(org.kie.dmn.model.api.TextAnnotation) DRGElement(org.kie.dmn.model.api.DRGElement)

Aggregations

QName (javax.xml.namespace.QName)5 Definitions (org.kie.dmn.model.api.Definitions)5 TDefinitions (org.kie.dmn.model.v1_2.TDefinitions)4 InputStreamReader (java.io.InputStreamReader)3 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2 ArrayList (java.util.ArrayList)2 Arrays (java.util.Arrays)2 Collections.emptyList (java.util.Collections.emptyList)2 HashMap (java.util.HashMap)2 HashSet (java.util.HashSet)2 List (java.util.List)2 Map (java.util.Map)2 Optional (java.util.Optional)2 Set (java.util.Set)2 BiConsumer (java.util.function.BiConsumer)2 Consumer (java.util.function.Consumer)2 Collectors (java.util.stream.Collectors)2 Stream (java.util.stream.Stream)2 StreamSupport (java.util.stream.StreamSupport)2