use of org.kie.dmn.model.api.dmndi.DMNShape 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 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());
}
use of org.kie.dmn.model.api.dmndi.DMNShape in project kie-wb-common by kiegroup.
the class DMNMarshallerStandaloneTest method test_diamond.
@Test
public void test_diamond() throws IOException {
// round trip test
roundTripUnmarshalThenMarshalUnmarshal(this.getClass().getResourceAsStream("/diamondDMN12.dmn"), this::checkDiamondGraph);
// additionally, check the marshalled is still DMN executable as expected
DMNMarshallerStandalone m = getDMNMarshaller();
Graph<?, ?> g = m.unmarshall(createMetadata(), this.getClass().getResourceAsStream("/diamondDMN12.dmn"));
DiagramImpl diagram = createDiagram();
diagram.setGraph(g);
String mString = m.marshall(diagram);
final KieServices ks = KieServices.Factory.get();
final KieContainer kieContainer = KieHelper.getKieContainer(ks.newReleaseId("org.kie", "dmn-test_diamond", "1.0"), ks.getResources().newByteArrayResource(mString.getBytes()).setTargetPath("src/main/resources/diamond.dmn"));
final DMNRuntime runtime = kieContainer.newKieSession().getKieRuntime(DMNRuntime.class);
Assert.assertNotNull(runtime);
DMNModel diamondModel = runtime.getModel("http://www.trisotech.com/definitions/_8afa6c24-55c8-43cf-8a02-fdde7fc5d1f2", "three decisions in a diamond shape");
DMNContext dmnContext = runtime.newContext();
dmnContext.set("My Name", "John Doe");
DMNResult dmnResult = runtime.evaluateAll(diamondModel, dmnContext);
assertFalse(dmnResult.getMessages().toString(), dmnResult.hasErrors());
DMNContext result = dmnResult.getContext();
assertEquals("Hello, John Doe.", result.get("My Decision"));
// additionally, check DMN DD/DI
org.kie.dmn.api.marshalling.DMNMarshaller dmnMarshaller = DMNMarshallerFactory.newDefaultMarshaller();
Definitions definitions = dmnMarshaller.unmarshal(mString);
org.kie.dmn.model.api.dmndi.DMNDiagram ddRoot = (org.kie.dmn.model.api.dmndi.DMNDiagram) definitions.getDMNDI().getDMNDiagram().get(0);
DMNShape myname = findShapeByDMNI(ddRoot, "_4cd17e52-6253-41d6-820d-5824bf5197f3");
assertBounds(500, 500, 100, 50, myname.getBounds());
assertColor(255, 255, 255, ((DMNStyle) myname.getStyle()).getFillColor());
assertColor(0, 0, 0, ((DMNStyle) myname.getStyle()).getStrokeColor());
assertDMNStyle("Open Sans", 24, 255, 0, 0, (DMNStyle) myname.getStyle());
DMNShape prefix = findShapeByDMNI(ddRoot, "_e920f38a-293c-41b8-adb3-69d0dc184fab");
assertBounds(300, 400, 100, 50, prefix.getBounds());
assertColor(0, 253, 25, ((DMNStyle) prefix.getStyle()).getFillColor());
assertColor(253, 0, 0, ((DMNStyle) prefix.getStyle()).getStrokeColor());
assertDMNStyle("Times New Roman", 8, 70, 60, 50, (DMNStyle) prefix.getStyle());
DMNShape postfix = findShapeByDMNI(ddRoot, "_f49f9c34-29d5-4e72-91d2-f4f92117c8da");
assertBounds(700, 400, 100, 50, postfix.getBounds());
assertColor(247, 255, 0, ((DMNStyle) postfix.getStyle()).getFillColor());
assertColor(0, 51, 255, ((DMNStyle) postfix.getStyle()).getStrokeColor());
assertDMNStyle("Arial", 10, 50, 60, 70, (DMNStyle) postfix.getStyle());
DMNShape mydecision = findShapeByDMNI(ddRoot, "_9b061fc3-8109-42e2-9fe4-fc39c90b654e");
assertBounds(487.5, 275, 125, 75, mydecision.getBounds());
assertColor(255, 255, 255, ((DMNStyle) mydecision.getStyle()).getFillColor());
assertColor(0, 0, 0, ((DMNStyle) mydecision.getStyle()).getStrokeColor());
assertDMNStyle("Monospaced", 32, 55, 66, 77, (DMNStyle) mydecision.getStyle());
}
use of org.kie.dmn.model.api.dmndi.DMNShape in project kie-wb-common by kiegroup.
the class DMNMarshallerStandaloneTest method testRemoveDrgElementsWithoutShapeFromDMN11.
@Test
public void testRemoveDrgElementsWithoutShapeFromDMN11() {
final String id1 = "id1";
final String id2 = "id2";
final String id3 = "id3";
final DRGElement e1 = createDRGElement(id1);
final DRGElement e2 = createDRGElement(id2);
final DRGElement e3 = createDRGElement(id3);
final List<org.kie.dmn.model.api.DRGElement> drgElements = new ArrayList<>(Arrays.asList(e1, e2, e3));
final List<DMNShape> dmnShapes = new ArrayList<>();
getDMNMarshaller().removeDrgElementsWithoutShape(drgElements, dmnShapes);
assertEquals(3, drgElements.size());
assertEquals(e1, drgElements.get(0));
assertEquals(e2, drgElements.get(1));
assertEquals(e3, drgElements.get(2));
}
use of org.kie.dmn.model.api.dmndi.DMNShape in project kie-wb-common by kiegroup.
the class DMNMarshallerStandalone method stunnerToDDExt.
@SuppressWarnings("unchecked")
private static DMNShape stunnerToDDExt(final Definitions definitions, final View<? extends DMNElement> v) {
final DMNShape result = new org.kie.dmn.model.v1_2.dmndi.DMNShape();
result.setId("dmnshape-" + v.getDefinition().getId().getValue());
result.setDmnElementRef(getDmnElementRef(definitions, v));
final Bounds bounds = new org.kie.dmn.model.v1_2.dmndi.Bounds();
result.setBounds(bounds);
bounds.setX(xOfBound(upperLeftBound(v)));
bounds.setY(yOfBound(upperLeftBound(v)));
result.setStyle(new org.kie.dmn.model.v1_2.dmndi.DMNStyle());
result.setDMNLabel(new org.kie.dmn.model.v1_2.dmndi.DMNLabel());
if (v.getDefinition() instanceof Decision) {
final Decision d = (Decision) v.getDefinition();
applyBounds(d.getDimensionsSet(), bounds);
applyBackgroundStyles(d.getStylingSet(), result);
applyFontStyle(d.getStylingSet(), result);
} else if (v.getDefinition() instanceof InputData) {
final InputData d = (InputData) v.getDefinition();
applyBounds(d.getDimensionsSet(), bounds);
applyBackgroundStyles(d.getStylingSet(), result);
applyFontStyle(d.getStylingSet(), result);
} else if (v.getDefinition() instanceof BusinessKnowledgeModel) {
final BusinessKnowledgeModel d = (BusinessKnowledgeModel) v.getDefinition();
applyBounds(d.getDimensionsSet(), bounds);
applyBackgroundStyles(d.getStylingSet(), result);
applyFontStyle(d.getStylingSet(), result);
} else if (v.getDefinition() instanceof KnowledgeSource) {
final KnowledgeSource d = (KnowledgeSource) v.getDefinition();
applyBounds(d.getDimensionsSet(), bounds);
applyBackgroundStyles(d.getStylingSet(), result);
applyFontStyle(d.getStylingSet(), result);
} else if (v.getDefinition() instanceof TextAnnotation) {
final TextAnnotation d = (TextAnnotation) v.getDefinition();
applyBounds(d.getDimensionsSet(), bounds);
applyBackgroundStyles(d.getStylingSet(), result);
applyFontStyle(d.getStylingSet(), result);
} else if (v.getDefinition() instanceof DecisionService) {
final DecisionService d = (DecisionService) v.getDefinition();
applyBounds(d.getDimensionsSet(), bounds);
applyBackgroundStyles(d.getStylingSet(), result);
applyFontStyle(d.getStylingSet(), result);
final DMNDecisionServiceDividerLine dl = new org.kie.dmn.model.v1_2.dmndi.DMNDecisionServiceDividerLine();
final org.kie.dmn.model.api.dmndi.Point leftPoint = new org.kie.dmn.model.v1_2.dmndi.Point();
leftPoint.setX(v.getBounds().getUpperLeft().getX());
final double dlY = v.getBounds().getUpperLeft().getY() + d.getDividerLineY().getValue();
leftPoint.setY(dlY);
dl.getWaypoint().add(leftPoint);
final org.kie.dmn.model.api.dmndi.Point rightPoint = new org.kie.dmn.model.v1_2.dmndi.Point();
rightPoint.setX(v.getBounds().getLowerRight().getX());
rightPoint.setY(dlY);
dl.getWaypoint().add(rightPoint);
result.setDMNDecisionServiceDividerLine(dl);
}
return result;
}
use of org.kie.dmn.model.api.dmndi.DMNShape in project kie-wb-common by kiegroup.
the class DMNMarshallerStandalone method internalAugment.
@SuppressWarnings("unchecked")
private void internalAugment(final Stream<DMNShape> drgShapeStream, final Id id, final Bound ulBound, final RectangleDimensionsSet dimensionsSet, final Bound lrBound, final StylingSet stylingSet, final DoubleConsumer decisionServiceDividerLineYSetter) {
final Optional<DMNShape> drgShapeOpt = drgShapeStream.filter(shape -> shape.getDmnElementRef().getLocalPart().endsWith(id.getValue())).findFirst();
if (!drgShapeOpt.isPresent()) {
return;
}
final DMNShape drgShape = drgShapeOpt.get();
if (ulBound != null) {
ulBound.setX(xOfShape(drgShape));
ulBound.setY(yOfShape(drgShape));
}
dimensionsSet.setWidth(new Width(widthOfShape(drgShape)));
dimensionsSet.setHeight(new Height(heightOfShape(drgShape)));
if (lrBound != null) {
lrBound.setX(xOfShape(drgShape) + widthOfShape(drgShape));
lrBound.setY(yOfShape(drgShape) + heightOfShape(drgShape));
}
final DMNStyle dmnStyleOfDrgShape = drgShape.getStyle() instanceof DMNStyle ? (DMNStyle) drgShape.getStyle() : null;
if (dmnStyleOfDrgShape != null) {
if (null != dmnStyleOfDrgShape.getFillColor()) {
stylingSet.setBgColour(new BgColour(ColorUtils.wbFromDMN(dmnStyleOfDrgShape.getFillColor())));
}
if (null != dmnStyleOfDrgShape.getStrokeColor()) {
stylingSet.setBorderColour(new BorderColour(ColorUtils.wbFromDMN(dmnStyleOfDrgShape.getStrokeColor())));
}
}
final StylingSet fontSet = new StylingSet();
if (dmnStyleOfDrgShape != null) {
mergeFontSet(fontSet, FontSetPropertyConverter.wbFromDMN(dmnStyleOfDrgShape));
}
if (drgShape.getDMNLabel() != null && drgShape.getDMNLabel().getSharedStyle() instanceof DMNStyle) {
mergeFontSet(fontSet, FontSetPropertyConverter.wbFromDMN((DMNStyle) drgShape.getDMNLabel().getSharedStyle()));
}
if (drgShape.getDMNLabel() != null && drgShape.getDMNLabel().getStyle() instanceof DMNStyle) {
mergeFontSet(fontSet, FontSetPropertyConverter.wbFromDMN((DMNStyle) drgShape.getDMNLabel().getStyle()));
}
mergeFontSet(stylingSet, fontSet);
if (drgShape.getDMNDecisionServiceDividerLine() != null) {
decisionServiceDividerLineYSetter.accept(drgShape.getDMNDecisionServiceDividerLine().getWaypoint().get(0).getY());
}
}
Aggregations