Search in sources :

Example 16 with ItemDefinition

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

the class ItemDefinitionConverter method writeAttributes.

@Override
protected void writeAttributes(HierarchicalStreamWriter writer, Object parent) {
    super.writeAttributes(writer, parent);
    ItemDefinition id = (ItemDefinition) parent;
    if (id.getTypeLanguage() != null)
        writer.addAttribute(TYPE_LANGUAGE, id.getTypeLanguage());
    writer.addAttribute(IS_COLLECTION, Boolean.valueOf(id.isIsCollection()).toString());
}
Also used : ItemDefinition(org.kie.dmn.model.v1_1.ItemDefinition)

Example 17 with ItemDefinition

use of org.kie.dmn.model.v1_1.ItemDefinition 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("/dmn.xsd").getFile()));
    ValidationResult validateInputResult = v.validateInstance(new StreamSource(inputXMLFile));
    if (!validateInputResult.isValid()) {
        for (ValidationProblem p : validateInputResult.getProblems()) {
            System.err.println(p);
        }
    }
    assertTrue(validateInputResult.isValid());
    final File subdirFile = new File(baseOutputDir, subdir);
    if (!subdirFile.mkdirs()) {
        logger.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();
    System.out.println(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()) {
            System.err.println(p);
        }
    }
    assertTrue(validateOutputResult.isValid());
    System.out.println("\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(System.out::println);
    System.out.println("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(System.err::println);
    if (!checkSimilar.getDifferences().iterator().hasNext()) {
        System.out.println("[ 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) DMNMarshaller(org.kie.dmn.api.marshalling.v1_1.DMNMarshaller) ComparisonResult(org.xmlunit.diff.ComparisonResult) Source(javax.xml.transform.Source) MyTestRegister(org.kie.dmn.backend.marshalling.v1_1.extensions.MyTestRegister) HashSet(java.util.HashSet) Node(org.w3c.dom.Node) Assert.fail(org.junit.Assert.fail) Logger(org.slf4j.Logger) DMNModelInstrumentedBase(org.kie.dmn.model.v1_1.DMNModelInstrumentedBase) 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) Definitions(org.kie.dmn.model.v1_1.Definitions) 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) InputStreamReader(java.io.InputStreamReader) Diff(org.xmlunit.diff.Diff) QName(javax.xml.namespace.QName) Definitions(org.kie.dmn.model.v1_1.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 18 with ItemDefinition

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

the class DMNCompilerImpl method processItemDefinitions.

private void processItemDefinitions(DMNCompilerContext ctx, DMNFEELHelper feel, DMNModelImpl model, Definitions dmndefs) {
    Definitions.normalize(dmndefs);
    List<ItemDefinition> ordered = new ItemDefinitionDependenciesSorter(model.getNamespace()).sort(dmndefs.getItemDefinition());
    for (ItemDefinition id : ordered) {
        ItemDefNodeImpl idn = new ItemDefNodeImpl(id);
        DMNType type = buildTypeDef(ctx, feel, model, idn, id, true);
        idn.setType(type);
        model.addItemDefinition(idn);
    }
}
Also used : ItemDefinition(org.kie.dmn.model.v1_1.ItemDefinition) ItemDefNodeImpl(org.kie.dmn.core.ast.ItemDefNodeImpl) DMNType(org.kie.dmn.api.core.DMNType)

Example 19 with ItemDefinition

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

the class ItemDefinitionDependenciesGeneratedTest method addDepsToItemDefinition.

private static void addDepsToItemDefinition(final ItemDefinition itemDefinition, final List<ItemDefinition> dependencies, final int numberOfDeps, final Set<String> usedNames) {
    int addedDepsCount = 0;
    for (ItemDefinition dependency : dependencies) {
        if (!usedNames.contains(dependency.getName())) {
            createAndAddDependency(itemDefinition, dependency);
            usedNames.add(dependency.getName());
            addedDepsCount++;
            if (addedDepsCount == numberOfDeps) {
                return;
            }
        }
    }
}
Also used : ItemDefinition(org.kie.dmn.model.v1_1.ItemDefinition)

Example 20 with ItemDefinition

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

the class ItemDefinitionDependenciesGeneratedTest method createItemDefinitionWithDeps.

private static ItemDefinition createItemDefinitionWithDeps(final ItemDefinition itemDefinitionTemplate, final List<ItemDefinition> dependencies, final int maxNumberOfDepsPerItemDefinition, final Set<String> usedNames) {
    // New ItemDefinition is created, so the original one stays untouched.
    final ItemDefinition it = new ItemDefinition();
    it.setName(itemDefinitionTemplate.getName());
    final List<ItemDefinition> possibleDependencies = dependencies.stream().filter(item -> !item.getName().equals(it.getName())).collect(Collectors.toList());
    addDepsToItemDefinition(it, possibleDependencies, maxNumberOfDepsPerItemDefinition, usedNames);
    return it;
}
Also used : Logger(org.slf4j.Logger) Collection(java.util.Collection) RunWith(org.junit.runner.RunWith) LoggerFactory(org.slf4j.LoggerFactory) Set(java.util.Set) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) ItemDefinition(org.kie.dmn.model.v1_1.ItemDefinition) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) List(java.util.List) QName(javax.xml.namespace.QName) Parameterized(org.junit.runners.Parameterized) ItemDefinition(org.kie.dmn.model.v1_1.ItemDefinition)

Aggregations

ItemDefinition (org.kie.dmn.model.v1_1.ItemDefinition)22 Test (org.junit.Test)10 QName (javax.xml.namespace.QName)7 ArrayList (java.util.ArrayList)6 Collection (java.util.Collection)3 HashSet (java.util.HashSet)3 List (java.util.List)3 Set (java.util.Set)3 Collectors (java.util.stream.Collectors)3 Assert.assertTrue (org.junit.Assert.assertTrue)3 Logger (org.slf4j.Logger)3 LoggerFactory (org.slf4j.LoggerFactory)3 RunWith (org.junit.runner.RunWith)2 Parameterized (org.junit.runners.Parameterized)2 DMNType (org.kie.dmn.api.core.DMNType)2 Definitions (org.kie.dmn.model.v1_1.Definitions)2 XStream (com.thoughtworks.xstream.XStream)1 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 FileOutputStream (java.io.FileOutputStream)1