Search in sources :

Example 76 with Definitions

use of org.kie.dmn.model.api.Definitions 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) 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) KieDMNModelInstrumentedBase(org.kie.dmn.model.v1_4.KieDMNModelInstrumentedBase) HashSet(java.util.HashSet) TrisoExtensionRegister(org.kie.dmn.backend.marshalling.v1_3.extensions.TrisoExtensionRegister) DMNMarshallerFactory(org.kie.dmn.backend.marshalling.v1x.DMNMarshallerFactory) Node(org.w3c.dom.Node) 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) 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) 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 77 with Definitions

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

the class DMNAssemblerService method addResourcesAfterRules.

@Override
public void addResourcesAfterRules(Object kbuilder, Collection<ResourceWithConfiguration> resources, ResourceType type) throws Exception {
    EvalHelper.clearGenericAccessorCache();
    KnowledgeBuilderImpl kbuilderImpl = (KnowledgeBuilderImpl) kbuilder;
    DMNCompilerImpl dmnCompiler = (DMNCompilerImpl) kbuilderImpl.getCachedOrCreate(DMN_COMPILER_CACHE_KEY, () -> getCompiler(kbuilderImpl));
    DMNMarshaller dmnMarshaller = dmnCompiler.getMarshaller();
    List<DMNResource> dmnResources = new ArrayList<>();
    for (ResourceWithConfiguration r : resources) {
        Definitions definitions = dmnMarshaller.unmarshal(r.getResource().getReader());
        DMNResource dmnResource = new DMNResource(definitions, r);
        dmnResources.add(dmnResource);
    }
    Collection<DMNModel> dmnModels = new ArrayList<>();
    // KIE API: KieContainer upgrade using KieContainer#updateToVersion -based DMN Import resolution strategy
    if (kbuilderImpl.getKnowledgeBase() != null) {
        for (InternalKnowledgePackage pr : kbuilderImpl.getKnowledgeBase().getPackagesMap().values()) {
            ResourceTypePackage resourceTypePackage = pr.getResourceTypePackages().get(ResourceType.DMN);
            if (resourceTypePackage != null) {
                DMNPackageImpl dmnpkg = (DMNPackageImpl) resourceTypePackage;
                dmnModels.addAll(dmnpkg.getAllModels().values());
            }
        }
    }
    // Workbench: InternalKieBuilder#createFileSet#build -based DMN Import resolution strategy
    for (PackageRegistry pr : kbuilderImpl.getPackageRegistry().values()) {
        ResourceTypePackage resourceTypePackage = pr.getPackage().getResourceTypePackages().get(ResourceType.DMN);
        if (resourceTypePackage != null) {
            DMNPackageImpl dmnpkg = (DMNPackageImpl) resourceTypePackage;
            dmnModels.addAll(dmnpkg.getAllModels().values());
        }
    }
    enrichDMNResourcesWithImportsDependencies(dmnResources, dmnModels);
    List<DMNResource> sortedDmnResources = DMNResourceDependenciesSorter.sort(dmnResources);
    for (DMNResource dmnRes : sortedDmnResources) {
        DMNModel dmnModel = internalAddResource(kbuilderImpl, dmnCompiler, dmnRes, dmnModels);
        dmnModels.add(dmnModel);
    }
}
Also used : DMNCompilerImpl(org.kie.dmn.core.compiler.DMNCompilerImpl) DMNMarshaller(org.kie.dmn.api.marshalling.DMNMarshaller) DMNPackageImpl(org.kie.dmn.core.impl.DMNPackageImpl) Definitions(org.kie.dmn.model.api.Definitions) ArrayList(java.util.ArrayList) ResourceWithConfiguration(org.kie.api.io.ResourceWithConfiguration) ResourceTypePackageRegistry(org.drools.core.definitions.ResourceTypePackageRegistry) PackageRegistry(org.drools.compiler.compiler.PackageRegistry) KnowledgeBuilderImpl(org.drools.compiler.builder.impl.KnowledgeBuilderImpl) ResourceTypePackage(org.kie.api.internal.io.ResourceTypePackage) DMNModel(org.kie.dmn.api.core.DMNModel) InternalKnowledgePackage(org.drools.core.definitions.InternalKnowledgePackage)

Example 78 with Definitions

use of org.kie.dmn.model.api.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_4.TDefinitions) Definitions(org.kie.dmn.model.api.Definitions) XMLStreamException(javax.xml.stream.XMLStreamException)

Example 79 with Definitions

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

the class DMNValidatorImpl method validateModel.

private List<DMNMessage> validateModel(DMNResource mainModel, List<DMNResource> otherModels) {
    Definitions mainDefinitions = mainModel.getDefinitions();
    StatelessKieSession kieSession = mainDefinitions instanceof org.kie.dmn.model.v1_1.KieDMNModelInstrumentedBase ? kb11.newStatelessKieSession() : kb12.newStatelessKieSession();
    MessageReporter reporter = new MessageReporter(mainModel);
    kieSession.setGlobal("reporter", reporter);
    // exclude dynamicDecisionService for validation
    List<DMNModelInstrumentedBase> dmnModelElements = allChildren(mainDefinitions).filter(d -> !(d instanceof DecisionService && Boolean.parseBoolean(d.getAdditionalAttributes().get(new QName("http://www.trisotech.com/2015/triso/modeling", "dynamicDecisionService"))))).collect(toList());
    List<Definitions> otherModelsDefinitions = otherModels.stream().map(DMNResource::getDefinitions).collect(Collectors.toList());
    BatchExecutionCommand batch = CommandFactory.newBatchExecution(Arrays.asList(CommandFactory.newInsertElements(dmnModelElements, "DEFAULT", false, "DEFAULT"), CommandFactory.newInsertElements(otherModelsDefinitions, "DMNImports", false, "DMNImports")));
    kieSession.execute(batch);
    return reporter.getMessages().getMessages();
}
Also used : Arrays(java.util.Arrays) DMNModelInstrumentedBase(org.kie.dmn.model.api.DMNModelInstrumentedBase) DMNMessage(org.kie.dmn.api.core.DMNMessage) URL(java.net.URL) LoggerFactory(org.slf4j.LoggerFactory) DMNCompilerImpl(org.kie.dmn.core.compiler.DMNCompilerImpl) FileSystemResource(org.drools.core.io.impl.FileSystemResource) CommandFactory(org.kie.internal.command.CommandFactory) XStreamMarshaller(org.kie.dmn.backend.marshalling.v1x.XStreamMarshaller) DMNModel(org.kie.dmn.api.core.DMNModel) StatelessKieSession(org.kie.api.runtime.StatelessKieSession) ResourceWithConfigurationImpl(org.kie.internal.io.ResourceWithConfigurationImpl) DMNAssemblerService(org.kie.dmn.core.assembler.DMNAssemblerService) DMNCompilerConfiguration(org.kie.dmn.api.core.DMNCompilerConfiguration) DMNProfile(org.kie.dmn.core.compiler.DMNProfile) EnumSet(java.util.EnumSet) DMNFactory(org.kie.dmn.core.api.DMNFactory) DMNCompilerConfigurationImpl(org.kie.dmn.core.compiler.DMNCompilerConfigurationImpl) DefaultDMNMessagesManager(org.kie.dmn.core.util.DefaultDMNMessagesManager) DMN_VERSION(org.kie.dmn.backend.marshalling.v1x.XStreamMarshaller.DMN_VERSION) Collection(java.util.Collection) Set(java.util.Set) Reader(java.io.Reader) ChainedProperties(org.kie.internal.utils.ChainedProperties) Collectors(java.util.stream.Collectors) BatchExecutionCommand(org.kie.api.command.BatchExecutionCommand) Resource(org.kie.api.io.Resource) List(java.util.List) Stream(java.util.stream.Stream) VALIDATE_SCHEMA(org.kie.dmn.validation.DMNValidator.Validation.VALIDATE_SCHEMA) SAXException(org.xml.sax.SAXException) InternalDMNDTAnalyserFactory(org.kie.dmn.validation.dtanalysis.InternalDMNDTAnalyserFactory) ANALYZE_DECISION_TABLE(org.kie.dmn.validation.DMNValidator.Validation.ANALYZE_DECISION_TABLE) DTAnalysis(org.kie.dmn.validation.dtanalysis.model.DTAnalysis) QName(javax.xml.namespace.QName) MsgUtil(org.kie.dmn.core.util.MsgUtil) BaseResource(org.drools.core.io.impl.BaseResource) DMNMessageImpl(org.kie.dmn.core.impl.DMNMessageImpl) VALIDATE_COMPILATION(org.kie.dmn.validation.DMNValidator.Validation.VALIDATE_COMPILATION) StreamSource(javax.xml.transform.stream.StreamSource) ReaderResource(org.drools.core.io.impl.ReaderResource) ClassLoaderUtil(org.kie.dmn.feel.util.ClassLoaderUtil) Source(javax.xml.transform.Source) Function(java.util.function.Function) Schema(javax.xml.validation.Schema) Definitions(org.kie.dmn.model.api.Definitions) ArrayList(java.util.ArrayList) DMNMarshallerFactory(org.kie.dmn.backend.marshalling.v1x.DMNMarshallerFactory) XMLConstants(javax.xml.XMLConstants) InternalKnowledgeBase(org.drools.kiesession.rulebase.InternalKnowledgeBase) InternalDMNDTAnalyser(org.kie.dmn.validation.dtanalysis.InternalDMNDTAnalyser) Properties(java.util.Properties) SchemaFactory(javax.xml.validation.SchemaFactory) Logger(org.slf4j.Logger) DMNMessageManager(org.kie.dmn.core.api.DMNMessageManager) IOException(java.io.IOException) Validator(javax.xml.validation.Validator) File(java.io.File) KieBaseBuilder(org.drools.modelcompiler.builder.KieBaseBuilder) Collectors.toList(java.util.stream.Collectors.toList) StringReader(java.io.StringReader) DMNResourceDependenciesSorter(org.kie.dmn.core.assembler.DMNResourceDependenciesSorter) DMNResource(org.kie.dmn.core.assembler.DMNResource) Msg(org.kie.dmn.core.util.Msg) VALIDATE_MODEL(org.kie.dmn.validation.DMNValidator.Validation.VALIDATE_MODEL) Collections(java.util.Collections) DecisionService(org.kie.dmn.model.api.DecisionService) InputStream(java.io.InputStream) QName(javax.xml.namespace.QName) Definitions(org.kie.dmn.model.api.Definitions) DMNModelInstrumentedBase(org.kie.dmn.model.api.DMNModelInstrumentedBase) DecisionService(org.kie.dmn.model.api.DecisionService) BatchExecutionCommand(org.kie.api.command.BatchExecutionCommand) StatelessKieSession(org.kie.api.runtime.StatelessKieSession)

Example 80 with Definitions

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

the class DMNValidatorImpl method unmarshallDMNResource.

private static DMNResource unmarshallDMNResource(DMNCompilerConfiguration config, Resource originalResource, String content) {
    Definitions dmndefs = DMNMarshallerFactory.newMarshallerWithExtensions(config.getRegisteredExtensions()).unmarshal(content);
    dmndefs.normalize();
    return wrapDefinitions(dmndefs, originalResource.getSourcePath());
}
Also used : Definitions(org.kie.dmn.model.api.Definitions)

Aggregations

Definitions (org.kie.dmn.model.api.Definitions)114 Test (org.junit.Test)71 DMNRuntime (org.kie.dmn.api.core.DMNRuntime)39 DMNMessage (org.kie.dmn.api.core.DMNMessage)37 DMNModel (org.kie.dmn.api.core.DMNModel)34 DMNResult (org.kie.dmn.api.core.DMNResult)32 TDefinitions (org.kie.dmn.model.v1_1.TDefinitions)31 Arrays (java.util.Arrays)28 Assert.assertTrue (org.junit.Assert.assertTrue)28 List (java.util.List)26 ItemDefinition (org.kie.dmn.model.api.ItemDefinition)26 Logger (org.slf4j.Logger)26 LoggerFactory (org.slf4j.LoggerFactory)26 HashMap (java.util.HashMap)25 Decision (org.kie.dmn.model.api.Decision)25 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)24 Assert.assertFalse (org.junit.Assert.assertFalse)24 DecisionNodeImpl (org.kie.dmn.core.ast.DecisionNodeImpl)24 DMNModelImpl (org.kie.dmn.core.impl.DMNModelImpl)24 ArrayList (java.util.ArrayList)23