Search in sources :

Example 1 with DecisionTable

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

the class XStreamMarshaller method newXStream.

private XStream newXStream() {
    XStream xStream = createTrustingXStream(staxDriver, Definitions.class.getClassLoader());
    xStream.alias("artifact", Artifact.class);
    xStream.alias("definitions", Definitions.class);
    xStream.alias("inputData", InputData.class);
    xStream.alias("decision", Decision.class);
    xStream.alias("variable", InformationItem.class);
    xStream.alias("informationRequirement", InformationRequirement.class);
    xStream.alias("requiredInput", DMNElementReference.class);
    xStream.alias("literalExpression", LiteralExpression.class);
    // TODO will need to remove dups and find missing element not captured?
    xStream.alias("DMNElement", DMNElement.class);
    xStream.alias("allowedValues", UnaryTests.class);
    xStream.alias("artifact", Artifact.class);
    xStream.alias("association", Association.class);
    xStream.alias("authorityRequirement", AuthorityRequirement.class);
    xStream.alias("authorityRequirement", AuthorityRequirement.class);
    xStream.alias("authorityRequirement", AuthorityRequirement.class);
    xStream.alias("binding", Binding.class);
    xStream.alias("businessContextElement", BusinessContextElement.class);
    xStream.alias("businessKnowledgeModel", BusinessKnowledgeModel.class);
    xStream.alias("column", InformationItem.class);
    xStream.alias("context", Context.class);
    xStream.alias("contextEntry", ContextEntry.class);
    xStream.alias("decision", Decision.class);
    xStream.alias("decisionMade", DMNElementReference.class);
    xStream.alias("decisionMaker", DMNElementReference.class);
    xStream.alias("decisionOwned", DMNElementReference.class);
    xStream.alias("decisionOwner", DMNElementReference.class);
    xStream.alias("decisionService", DecisionService.class);
    xStream.alias("decisionTable", DecisionTable.class);
    xStream.alias("defaultOutputEntry", LiteralExpression.class);
    xStream.alias("definitions", Definitions.class);
    xStream.alias("drgElement", DMNElementReference.class);
    // xStream.alias("drgElement", DRGElement.class ); ambiguity, also referring to top-level xsd element just under xsd root.
    xStream.alias("elementCollection", ElementCollection.class);
    xStream.alias("elementCollection", ElementCollection.class);
    xStream.alias("encapsulatedDecision", DMNElementReference.class);
    xStream.alias("encapsulatedLogic", FunctionDefinition.class);
    xStream.alias("expression", Expression.class);
    xStream.alias("formalParameter", InformationItem.class);
    xStream.alias("functionDefinition", FunctionDefinition.class);
    xStream.alias("impactedPerformanceIndicator", DMNElementReference.class);
    xStream.alias("impactingDecision", DMNElementReference.class);
    xStream.alias("import", Import.class);
    xStream.alias("import", Import.class);
    // TODO where?
    xStream.alias("importedElement", String.class);
    xStream.alias("importedValues", ImportedValues.class);
    xStream.alias("informationItem", InformationItem.class);
    xStream.alias("informationRequirement", InformationRequirement.class);
    xStream.alias("input", InputClause.class);
    xStream.alias("inputData", DMNElementReference.class);
    xStream.alias("inputData", InputData.class);
    xStream.alias("inputDecision", DMNElementReference.class);
    xStream.alias("inputEntry", UnaryTests.class);
    xStream.alias("inputExpression", LiteralExpression.class);
    xStream.alias("inputValues", UnaryTests.class);
    xStream.alias("invocation", Invocation.class);
    xStream.alias("itemComponent", ItemDefinition.class);
    xStream.alias("itemDefinition", ItemDefinition.class);
    xStream.alias("itemDefinition", ItemDefinition.class);
    xStream.alias("knowledgeRequirement", KnowledgeRequirement.class);
    xStream.alias("knowledgeRequirement", KnowledgeRequirement.class);
    xStream.alias("knowledgeSource", KnowledgeSource.class);
    xStream.alias("literalExpression", LiteralExpression.class);
    xStream.alias("namedElement", NamedElement.class);
    xStream.alias("organizationUnit", OrganizationUnit.class);
    xStream.alias("output", OutputClause.class);
    xStream.alias("outputDecision", DMNElementReference.class);
    xStream.alias("outputEntry", LiteralExpression.class);
    xStream.alias("outputValues", UnaryTests.class);
    xStream.alias("owner", DMNElementReference.class);
    xStream.alias("parameter", InformationItem.class);
    xStream.alias("performanceIndicator", PerformanceIndicator.class);
    xStream.alias("relation", Relation.class);
    xStream.alias("requiredAuthority", DMNElementReference.class);
    xStream.alias("requiredDecision", DMNElementReference.class);
    xStream.alias("requiredDecision", DMNElementReference.class);
    xStream.alias("requiredInput", DMNElementReference.class);
    xStream.alias("requiredInput", DMNElementReference.class);
    xStream.alias("requiredKnowledge", DMNElementReference.class);
    xStream.alias("rule", DecisionRule.class);
    xStream.alias("sourceRef", DMNElementReference.class);
    xStream.alias("supportedObjective", DMNElementReference.class);
    xStream.alias("targetRef", DMNElementReference.class);
    xStream.alias("textAnnotation", TextAnnotation.class);
    // TODO where?
    xStream.alias("type", String.class);
    xStream.alias("typeRef", QName.class);
    xStream.alias("usingProcess", DMNElementReference.class);
    xStream.alias("usingTask", DMNElementReference.class);
    xStream.alias("variable", InformationItem.class);
    xStream.alias("variable", InformationItem.class);
    xStream.alias("variable", InformationItem.class);
    xStream.alias("variable", InformationItem.class);
    // xStream.alias("allowedAnswers", xsd:string.class );
    // xStream.alias("description", xsd:string.class );
    // xStream.alias("question", xsd:string.class );
    // xStream.alias("text", xsd:string.class );
    // xStream.alias("text", xsd:string.class );
    // xStream.alias("text", xsd:string.class );
    xStream.alias("row", org.kie.dmn.model.v1_1.List.class);
    xStream.alias("list", org.kie.dmn.model.v1_1.List.class);
    xStream.alias("extensionElements", DMNElement.ExtensionElements.class);
    // Manually imported TEXT = String
    xStream.alias(LiteralExpressionConverter.TEXT, String.class);
    xStream.alias(TextAnnotationConverter.TEXT, String.class);
    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);
    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.ignoreUnknownElements();
    for (DMNExtensionRegister extensionRegister : extensionRegisters) {
        extensionRegister.registerExtensionConverters(xStream);
    }
    return xStream;
}
Also used : DMNElement(org.kie.dmn.model.v1_1.DMNElement) XStream(com.thoughtworks.xstream.XStream) XStreamUtils.createTrustingXStream(org.kie.soup.commons.xstream.XStreamUtils.createTrustingXStream) Definitions(org.kie.dmn.model.v1_1.Definitions) DMNExtensionRegister(org.kie.dmn.api.marshalling.v1_1.DMNExtensionRegister)

Example 2 with DecisionTable

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

the class DMNEvaluatorCompiler method compileDecisionTable.

private DMNExpressionEvaluator compileDecisionTable(DMNCompilerContext ctx, DMNModelImpl model, DMNBaseNode node, String dtName, DecisionTable dt) {
    java.util.List<DTInputClause> inputs = new ArrayList<>();
    int index = 0;
    for (InputClause ic : dt.getInput()) {
        index++;
        String inputExpressionText = ic.getInputExpression().getText();
        String inputValuesText = Optional.ofNullable(ic.getInputValues()).map(UnaryTests::getText).orElse(null);
        java.util.List<UnaryTest> inputValues = null;
        if (inputValuesText != null) {
            inputValues = textToUnaryTestList(ctx, inputValuesText, model, ic, Msg.ERR_COMPILING_FEEL_EXPR_ON_DT_INPUT_CLAUSE_IDX, inputValuesText, node.getIdentifierString(), index);
        } else if (ic.getInputExpression().getTypeRef() != null) {
            QName inputExpressionTypeRef = ic.getInputExpression().getTypeRef();
            BaseDMNTypeImpl typeRef = (BaseDMNTypeImpl) model.getTypeRegistry().resolveType(resolveNamespaceForTypeRef(inputExpressionTypeRef, ic.getInputExpression()), inputExpressionTypeRef.getLocalPart());
            inputValues = typeRef.getAllowedValuesFEEL();
        }
        CompiledExpression compiledInput = feel.compileFeelExpression(ctx, inputExpressionText, model, dt, Msg.ERR_COMPILING_FEEL_EXPR_ON_DT_INPUT_CLAUSE_IDX, inputExpressionText, dtName, index);
        inputs.add(new DTInputClause(inputExpressionText, inputValuesText, inputValues, compiledInput));
    }
    java.util.List<DTOutputClause> outputs = new ArrayList<>();
    index = 0;
    boolean hasOutputValues = false;
    for (OutputClause oc : dt.getOutput()) {
        String outputName = oc.getName();
        if (outputName != null) {
            DMNCompilerHelper.checkVariableName(model, node.getSource(), outputName);
        }
        String id = oc.getId();
        String outputValuesText = Optional.ofNullable(oc.getOutputValues()).map(UnaryTests::getText).orElse(null);
        String defaultValue = oc.getDefaultOutputEntry() != null ? oc.getDefaultOutputEntry().getText() : null;
        BaseDMNTypeImpl typeRef = (BaseDMNTypeImpl) DMNTypeRegistry.UNKNOWN;
        java.util.List<UnaryTest> outputValues = null;
        if (oc.getTypeRef() != null) {
            QName outputExpressionTypeRef = oc.getTypeRef();
            typeRef = (BaseDMNTypeImpl) model.getTypeRegistry().resolveType(resolveNamespaceForTypeRef(outputExpressionTypeRef, oc), outputExpressionTypeRef.getLocalPart());
            if (typeRef == null) {
                typeRef = (BaseDMNTypeImpl) DMNTypeRegistry.UNKNOWN;
            }
        } else if (dt.getOutput().size() == 1 && (dt.getParent() instanceof Decision || dt.getParent() instanceof BusinessKnowledgeModel || dt.getParent() instanceof ContextEntry)) {
            QName inferredTypeRef = recurseUpToInferTypeRef(model, oc, dt);
            // if inferredTypeRef is null, a std err will have been reported
            if (inferredTypeRef != null) {
                typeRef = (BaseDMNTypeImpl) model.getTypeRegistry().resolveType(resolveNamespaceForTypeRef(inferredTypeRef, oc), inferredTypeRef.getLocalPart());
            }
        }
        if (outputValuesText != null) {
            outputValues = textToUnaryTestList(ctx, outputValuesText, model, oc, Msg.ERR_COMPILING_FEEL_EXPR_ON_DT_OUTPUT_CLAUSE_IDX, outputValuesText, node.getIdentifierString(), ++index);
        } else if (typeRef != DMNTypeRegistry.UNKNOWN) {
            outputValues = typeRef.getAllowedValuesFEEL();
        }
        if (outputValues != null && !outputValues.isEmpty()) {
            hasOutputValues = true;
        }
        outputs.add(new DTOutputClause(outputName, id, outputValues, defaultValue, typeRef.getFeelType(), typeRef.isCollection()));
    }
    if (dt.getHitPolicy().equals(HitPolicy.PRIORITY) && !hasOutputValues) {
        MsgUtil.reportMessage(logger, DMNMessage.Severity.ERROR, dt.getParent(), model, null, null, Msg.MISSING_OUTPUT_VALUES, dt.getParent());
    }
    java.util.List<DTDecisionRule> rules = new ArrayList<>();
    index = 0;
    for (DecisionRule dr : dt.getRule()) {
        DTDecisionRule rule = new DTDecisionRule(index);
        for (UnaryTests ut : dr.getInputEntry()) {
            final java.util.List<UnaryTest> tests;
            if (ut == null || ut.getText() == null || ut.getText().isEmpty()) {
                tests = Collections.emptyList();
                MsgUtil.reportMessage(logger, DMNMessage.Severity.ERROR, ut, model, null, null, Msg.DTABLE_EMPTY_ENTRY, dt.getRule().indexOf(dr) + 1, dr.getInputEntry().indexOf(ut) + 1, dt.getParentDRDElement().getIdentifierString());
            } else {
                tests = textToUnaryTestList(ctx, ut.getText(), model, dr, Msg.ERR_COMPILING_FEEL_EXPR_ON_DT_RULE_IDX, ut.getText(), node.getIdentifierString(), index + 1);
            }
            rule.getInputEntry().add((c, x) -> tests.stream().anyMatch(t -> {
                Boolean result = t.apply(c, x);
                return result != null && result == true;
            }));
        }
        for (LiteralExpression le : dr.getOutputEntry()) {
            String expressionText = le.getText();
            CompiledExpression compiledExpression = feel.compileFeelExpression(ctx, expressionText, model, dr, Msg.ERR_COMPILING_FEEL_EXPR_ON_DT_RULE_IDX, expressionText, dtName, index + 1);
            rule.getOutputEntry().add(compiledExpression);
        }
        rules.add(rule);
        index++;
    }
    String policy = dt.getHitPolicy().value() + (dt.getAggregation() != null ? " " + dt.getAggregation().value() : "");
    org.kie.dmn.feel.runtime.decisiontables.HitPolicy hp = org.kie.dmn.feel.runtime.decisiontables.HitPolicy.fromString(policy);
    java.util.List<String> parameterNames = new ArrayList<>();
    if (node instanceof BusinessKnowledgeModelNode) {
        // need to break this statement down and check for nulls
        parameterNames.addAll(((BusinessKnowledgeModelNode) node).getBusinessKnowledModel().getEncapsulatedLogic().getFormalParameter().stream().map(f -> f.getName()).collect(toList()));
    } else {
        parameterNames.addAll(node.getDependencies().keySet());
    }
    // creates a FEEL instance which will be used by the invoker/impl (s)
    FEEL feelInstance = feel.newFEELInstance();
    DecisionTableImpl dti = new DecisionTableImpl(dtName, parameterNames, inputs, outputs, rules, hp, feelInstance);
    DTInvokerFunction dtf = new DTInvokerFunction(dti);
    DMNDTExpressionEvaluator dtee = new DMNDTExpressionEvaluator(node, feelInstance, dtf);
    return dtee;
}
Also used : InformationItem(org.kie.dmn.model.v1_1.InformationItem) DMNMessage(org.kie.dmn.api.core.DMNMessage) ContextEntry(org.kie.dmn.model.v1_1.ContextEntry) OutputClause(org.kie.dmn.model.v1_1.OutputClause) FunctionDefinition(org.kie.dmn.model.v1_1.FunctionDefinition) LoggerFactory(org.slf4j.LoggerFactory) LiteralExpression(org.kie.dmn.model.v1_1.LiteralExpression) DMNExpressionEvaluator(org.kie.dmn.core.api.DMNExpressionEvaluator) DTDecisionRule(org.kie.dmn.feel.runtime.decisiontables.DTDecisionRule) EvaluatorResult(org.kie.dmn.core.api.EvaluatorResult) Binding(org.kie.dmn.model.v1_1.Binding) UnaryTest(org.kie.dmn.feel.runtime.UnaryTest) DMNModelInstrumentedBase(org.kie.dmn.model.v1_1.DMNModelInstrumentedBase) BaseDMNTypeImpl(org.kie.dmn.core.impl.BaseDMNTypeImpl) DMNModelImpl(org.kie.dmn.core.impl.DMNModelImpl) DecisionTable(org.kie.dmn.model.v1_1.DecisionTable) DMNRelationEvaluator(org.kie.dmn.core.ast.DMNRelationEvaluator) Collectors(java.util.stream.Collectors) BusinessKnowledgeModelNode(org.kie.dmn.api.core.ast.BusinessKnowledgeModelNode) Context(org.kie.dmn.model.v1_1.Context) List(java.util.List) DMNDTExpressionEvaluator(org.kie.dmn.core.ast.DMNDTExpressionEvaluator) CompiledExpression(org.kie.dmn.feel.lang.CompiledExpression) Invocation(org.kie.dmn.model.v1_1.Invocation) Optional(java.util.Optional) QName(javax.xml.namespace.QName) DMNLiteralExpressionEvaluator(org.kie.dmn.core.ast.DMNLiteralExpressionEvaluator) BusinessKnowledgeModel(org.kie.dmn.model.v1_1.BusinessKnowledgeModel) DMNElement(org.kie.dmn.model.v1_1.DMNElement) FEEL(org.kie.dmn.feel.FEEL) MsgUtil(org.kie.dmn.core.util.MsgUtil) DMNType(org.kie.dmn.api.core.DMNType) DMNContextEvaluator(org.kie.dmn.core.ast.DMNContextEvaluator) DTOutputClause(org.kie.dmn.feel.runtime.decisiontables.DTOutputClause) EvaluatorResultImpl(org.kie.dmn.core.ast.EvaluatorResultImpl) DTInputClause(org.kie.dmn.feel.runtime.decisiontables.DTInputClause) ArrayList(java.util.ArrayList) HitPolicy(org.kie.dmn.model.v1_1.HitPolicy) Relation(org.kie.dmn.model.v1_1.Relation) DecisionNode(org.kie.dmn.api.core.ast.DecisionNode) FEELFunction(org.kie.dmn.feel.runtime.FEELFunction) DMNBaseNode(org.kie.dmn.core.ast.DMNBaseNode) DecisionRule(org.kie.dmn.model.v1_1.DecisionRule) UnaryTests(org.kie.dmn.model.v1_1.UnaryTests) Expression(org.kie.dmn.model.v1_1.Expression) DMNInvocationEvaluator(org.kie.dmn.core.ast.DMNInvocationEvaluator) Logger(org.slf4j.Logger) DMNListEvaluator(org.kie.dmn.core.ast.DMNListEvaluator) DTInvokerFunction(org.kie.dmn.feel.runtime.functions.DTInvokerFunction) Decision(org.kie.dmn.model.v1_1.Decision) Collectors.toList(java.util.stream.Collectors.toList) DMNFunctionDefinitionEvaluator(org.kie.dmn.core.ast.DMNFunctionDefinitionEvaluator) InputClause(org.kie.dmn.model.v1_1.InputClause) Msg(org.kie.dmn.core.util.Msg) DecisionTableImpl(org.kie.dmn.feel.runtime.decisiontables.DecisionTableImpl) Collections(java.util.Collections) BaseFEELFunction(org.kie.dmn.feel.runtime.functions.BaseFEELFunction) FEEL(org.kie.dmn.feel.FEEL) ArrayList(java.util.ArrayList) BusinessKnowledgeModelNode(org.kie.dmn.api.core.ast.BusinessKnowledgeModelNode) UnaryTest(org.kie.dmn.feel.runtime.UnaryTest) CompiledExpression(org.kie.dmn.feel.lang.CompiledExpression) ContextEntry(org.kie.dmn.model.v1_1.ContextEntry) DTDecisionRule(org.kie.dmn.feel.runtime.decisiontables.DTDecisionRule) DecisionRule(org.kie.dmn.model.v1_1.DecisionRule) DTDecisionRule(org.kie.dmn.feel.runtime.decisiontables.DTDecisionRule) DTInputClause(org.kie.dmn.feel.runtime.decisiontables.DTInputClause) DTInputClause(org.kie.dmn.feel.runtime.decisiontables.DTInputClause) InputClause(org.kie.dmn.model.v1_1.InputClause) QName(javax.xml.namespace.QName) DecisionTableImpl(org.kie.dmn.feel.runtime.decisiontables.DecisionTableImpl) LiteralExpression(org.kie.dmn.model.v1_1.LiteralExpression) DTOutputClause(org.kie.dmn.feel.runtime.decisiontables.DTOutputClause) DMNDTExpressionEvaluator(org.kie.dmn.core.ast.DMNDTExpressionEvaluator) BaseDMNTypeImpl(org.kie.dmn.core.impl.BaseDMNTypeImpl) Decision(org.kie.dmn.model.v1_1.Decision) OutputClause(org.kie.dmn.model.v1_1.OutputClause) DTOutputClause(org.kie.dmn.feel.runtime.decisiontables.DTOutputClause) BusinessKnowledgeModel(org.kie.dmn.model.v1_1.BusinessKnowledgeModel) DTInvokerFunction(org.kie.dmn.feel.runtime.functions.DTInvokerFunction) UnaryTests(org.kie.dmn.model.v1_1.UnaryTests)

Example 3 with DecisionTable

use of org.kie.dmn.model.v1_1.DecisionTable 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 4 with DecisionTable

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

the class DMNCompilerImpl method resolveTypeRef.

public DMNType resolveTypeRef(DMNModelImpl dmnModel, DMNNode node, NamedElement model, DMNModelInstrumentedBase localElement, QName typeRef) {
    if (typeRef != null) {
        QName nsAndName = getNamespaceAndName(localElement, dmnModel.getImportAliasesForNS(), typeRef);
        DMNType type = dmnModel.getTypeRegistry().resolveType(nsAndName.getNamespaceURI(), nsAndName.getLocalPart());
        if (type == null && DMNModelInstrumentedBase.URI_FEEL.equals(nsAndName.getNamespaceURI())) {
            if (model instanceof Decision && ((Decision) model).getExpression() instanceof DecisionTable) {
                DecisionTable dt = (DecisionTable) ((Decision) model).getExpression();
                if (dt.getOutput().size() > 1) {
                    // implicitly define a type for the decision table result
                    CompositeTypeImpl compType = new CompositeTypeImpl(dmnModel.getNamespace(), model.getName() + "_Type", model.getId(), dt.getHitPolicy().isMultiHit());
                    for (OutputClause oc : dt.getOutput()) {
                        DMNType fieldType = resolveTypeRef(dmnModel, node, model, oc, oc.getTypeRef());
                        compType.addField(oc.getName(), fieldType);
                    }
                    dmnModel.getTypeRegistry().registerType(compType);
                    return compType;
                } else if (dt.getOutput().size() == 1) {
                    return resolveTypeRef(dmnModel, node, model, dt.getOutput().get(0), dt.getOutput().get(0).getTypeRef());
                }
            }
        } else if (type == null) {
            MsgUtil.reportMessage(logger, DMNMessage.Severity.ERROR, localElement, dmnModel, null, null, Msg.UNKNOWN_TYPE_REF_ON_NODE, typeRef.toString(), localElement.getParentDRDElement().getIdentifierString());
        }
        return type;
    }
    return dmnModel.getTypeRegistry().resolveType(DMNModelInstrumentedBase.URI_FEEL, BuiltInType.UNKNOWN.getName());
}
Also used : OutputClause(org.kie.dmn.model.v1_1.OutputClause) DecisionTable(org.kie.dmn.model.v1_1.DecisionTable) QName(javax.xml.namespace.QName) Decision(org.kie.dmn.model.v1_1.Decision) CompositeTypeImpl(org.kie.dmn.core.impl.CompositeTypeImpl) DMNType(org.kie.dmn.api.core.DMNType)

Aggregations

QName (javax.xml.namespace.QName)3 DMNType (org.kie.dmn.api.core.DMNType)2 DMNElement (org.kie.dmn.model.v1_1.DMNElement)2 XStream (com.thoughtworks.xstream.XStream)1 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 FileOutputStream (java.io.FileOutputStream)1 FileWriter (java.io.FileWriter)1 InputStreamReader (java.io.InputStreamReader)1 Files (java.nio.file.Files)1 ArrayList (java.util.ArrayList)1 Arrays (java.util.Arrays)1 Collections (java.util.Collections)1 HashSet (java.util.HashSet)1 List (java.util.List)1 Optional (java.util.Optional)1 Set (java.util.Set)1 Collectors (java.util.stream.Collectors)1 Collectors.toList (java.util.stream.Collectors.toList)1 Source (javax.xml.transform.Source)1