Search in sources :

Example 71 with Definitions

use of org.kie.dmn.model.v1_1.Definitions in project drools by kiegroup.

the class XStreamMarshaller method unmarshal.

@Override
public Definitions unmarshal(Reader isr) {
    try {
        XStream xStream = newXStream();
        Definitions def = (Definitions) xStream.fromXML(isr);
        return def;
    } catch (Exception e) {
        logger.error("Error unmarshalling DMN model from reader.", e);
    }
    return null;
}
Also used : XStream(com.thoughtworks.xstream.XStream) DMNXStream(org.kie.dmn.backend.marshalling.v1x.DMNXStream) TDefinitions(org.kie.dmn.model.v1_1.TDefinitions) Definitions(org.kie.dmn.model.api.Definitions) XMLStreamException(javax.xml.stream.XMLStreamException)

Example 72 with Definitions

use of org.kie.dmn.model.v1_1.Definitions 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";
        }
        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);
    }
}
Also used : Import(org.kie.dmn.model.api.Import) PerformanceIndicator(org.kie.dmn.model.api.PerformanceIndicator) TDefinitions(org.kie.dmn.model.v1_1.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) 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)

Example 73 with Definitions

use of org.kie.dmn.model.v1_1.Definitions in project drools by kiegroup.

the class UnmarshalMarshalTest method testRoundTrip.

public void testRoundTrip(String subdir, String xmlfile, DMNMarshaller marshaller) 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(new StreamSource(this.getClass().getResource("/DMN11.xsd").getFile()));
    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"

         */
    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") }));
    Set<String> nodeHavingDefaultableAttr = new HashSet<>();
    nodeHavingDefaultableAttr.addAll(Arrays.asList(new String[] { "definitions", "decisionTable", "itemDefinition", "itemComponent" }));
    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;
            }
        }
        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) 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) MyTestRegister(org.kie.dmn.backend.marshalling.v1_1.extensions.MyTestRegister) Definitions(org.kie.dmn.model.api.Definitions) HashSet(java.util.HashSet) DMNMarshallerFactory(org.kie.dmn.backend.marshalling.v1x.DMNMarshallerFactory) Node(org.w3c.dom.Node) Assert.fail(org.junit.Assert.fail) KieDMNModelInstrumentedBase(org.kie.dmn.model.v1_1.KieDMNModelInstrumentedBase) 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) InputStreamReader(java.io.InputStreamReader) File(java.io.File) Languages(org.xmlunit.validation.Languages) ValidationProblem(org.xmlunit.validation.ValidationProblem) Ignore(org.junit.Ignore) Assert.assertFalse(org.junit.Assert.assertFalse) DecisionServicesExtensionRegister(org.kie.dmn.backend.marshalling.v1_1.xstream.extensions.DecisionServicesExtensionRegister) QName(javax.xml.namespace.QName) ComparisonType(org.xmlunit.diff.ComparisonType) Validator(org.xmlunit.validation.Validator) DMNMarshaller(org.kie.dmn.api.marshalling.DMNMarshaller) 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 74 with Definitions

use of org.kie.dmn.model.v1_1.Definitions in project kie-wb-common by kiegroup.

the class BPMNAnalyzer method read.

public BPMNProcess read(InputStream inputStream) {
    Definitions definitions = BPMN2Utils.getDefinitions(inputStream);
    Optional<Process> processOptional = findProcess(definitions);
    if (!processOptional.isPresent()) {
        throw new RuntimeException("Cannot find Process on definitions");
    }
    Process process = processOptional.get();
    BusinessProcessFormModel formModel = new BusinessProcessFormModel(process.getId(), process.getName(), new ArrayList<>());
    BPMNProcess bpmmProcess = new BPMNProcess(formModel);
    readContainerUserTasks(process, bpmmProcess::addTaskFormModel);
    return bpmmProcess;
}
Also used : Definitions(org.eclipse.bpmn2.Definitions) Process(org.eclipse.bpmn2.Process) BusinessProcessFormModel(org.kie.workbench.common.forms.jbpm.model.authoring.process.BusinessProcessFormModel)

Example 75 with Definitions

use of org.kie.dmn.model.v1_1.Definitions in project kie-wb-common by kiegroup.

the class DefinitionsConverterTest method JBPM_7526_shouldSetExporter.

@Test
public void JBPM_7526_shouldSetExporter() {
    GraphNodeStoreImpl nodeStore = new GraphNodeStoreImpl();
    NodeImpl x = new NodeImpl("x");
    BPMNDiagramImpl diag = new BPMNDiagramImpl();
    diag.setDiagramSet(new DiagramSet(new Name("x"), new Documentation("doc"), new Id("x"), new Package("org.jbpm"), new ProcessType(), new Version("1.0"), new AdHoc(false), new ProcessInstanceDescription("descr"), new Imports(), new Executable(true), new SLADueDate("")));
    x.setContent(new ViewImpl<>(diag, Bounds.create()));
    nodeStore.add(x);
    ConverterFactory f = new ConverterFactory(new DefinitionsBuildingContext(new GraphImpl("x", nodeStore)), new PropertyWriterFactory());
    DefinitionsConverter definitionsConverter = new DefinitionsConverter(f, new PropertyWriterFactory());
    Definitions definitions = definitionsConverter.toDefinitions();
    assertThat(definitions.getExporter()).isNotBlank();
    assertThat(definitions.getExporterVersion()).isNotBlank();
}
Also used : NodeImpl(org.kie.workbench.common.stunner.core.graph.impl.NodeImpl) Documentation(org.kie.workbench.common.stunner.bpmn.definition.property.general.Documentation) Definitions(org.eclipse.bpmn2.Definitions) ProcessInstanceDescription(org.kie.workbench.common.stunner.bpmn.definition.property.diagram.ProcessInstanceDescription) Imports(org.kie.workbench.common.stunner.bpmn.definition.property.diagram.imports.Imports) PropertyWriterFactory(org.kie.workbench.common.stunner.bpmn.backend.converters.fromstunner.properties.PropertyWriterFactory) Name(org.kie.workbench.common.stunner.bpmn.definition.property.general.Name) GraphNodeStoreImpl(org.kie.workbench.common.stunner.core.graph.store.GraphNodeStoreImpl) SLADueDate(org.kie.workbench.common.stunner.bpmn.definition.property.general.SLADueDate) ProcessType(org.kie.workbench.common.stunner.bpmn.definition.property.diagram.ProcessType) Version(org.kie.workbench.common.stunner.bpmn.definition.property.diagram.Version) DiagramSet(org.kie.workbench.common.stunner.bpmn.definition.property.diagram.DiagramSet) GraphImpl(org.kie.workbench.common.stunner.core.graph.impl.GraphImpl) BPMNDiagramImpl(org.kie.workbench.common.stunner.bpmn.definition.BPMNDiagramImpl) Id(org.kie.workbench.common.stunner.bpmn.definition.property.diagram.Id) Package(org.kie.workbench.common.stunner.bpmn.definition.property.diagram.Package) AdHoc(org.kie.workbench.common.stunner.bpmn.definition.property.diagram.AdHoc) Executable(org.kie.workbench.common.stunner.bpmn.definition.property.diagram.Executable) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)43 Definitions (org.eclipse.bpmn2.Definitions)42 Definitions (org.kie.dmn.model.api.Definitions)32 TDefinitions (org.kie.dmn.model.v1_1.TDefinitions)31 DecisionNodeImpl (org.kie.dmn.core.ast.DecisionNodeImpl)28 DMNModelImpl (org.kie.dmn.core.impl.DMNModelImpl)28 List (java.util.List)27 DMNResult (org.kie.dmn.api.core.DMNResult)27 DMNRuntime (org.kie.dmn.api.core.DMNRuntime)27 ArrayList (java.util.ArrayList)23 HashMap (java.util.HashMap)23 Collectors (java.util.stream.Collectors)22 DMNModel (org.kie.dmn.api.core.DMNModel)22 Map (java.util.Map)21 Logger (org.slf4j.Logger)21 LoggerFactory (org.slf4j.LoggerFactory)21 Arrays (java.util.Arrays)20 CoreMatchers.containsString (org.hamcrest.CoreMatchers.containsString)20 Collection (java.util.Collection)19 Collections (java.util.Collections)19