Skip to content

Commit

Permalink
Merge pull request #75 from rgdoliveira/sync_main
Browse files Browse the repository at this point in the history
Sync main branch with Apache main branch
  • Loading branch information
rgdoliveira authored Aug 26, 2024
2 parents c550c53 + a27cb22 commit 4291186
Show file tree
Hide file tree
Showing 18 changed files with 1,180 additions and 271 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -71,19 +71,26 @@ public static Collection<Object[]> getParameters() {
@Test(timeout = 10000)
public void testSalienceIntegerAndLoadOrder() throws Exception {
KieBase kbase = KieBaseUtil.getKieBaseFromClasspathResources(this.getClass(), kieBaseTestConfiguration, "test_salienceIntegerRule.drl");
KieSession ksession = kbase.newKieSession();
final List list = new ArrayList();
ksession.setGlobal( "list", list );
KieSession ksession = null;
try {
ksession = kbase.newKieSession();
final List<String> list = new ArrayList<>();
ksession.setGlobal("list", list);

final PersonInterface person = new Person( "Edson", "cheese" );
ksession.insert( person );
final PersonInterface person = new Person("Edson", "cheese");
ksession.insert(person);

ksession.fireAllRules();
ksession.fireAllRules();

assertThat(list.size()).as("Three rules should have been fired").isEqualTo(3);
assertThat(list.get(0)).as("Rule 4 should have been fired first").isEqualTo("Rule 4");
assertThat(list.get(1)).as("Rule 2 should have been fired second").isEqualTo("Rule 2");
assertThat(list.get(2)).as("Rule 3 should have been fired third").isEqualTo("Rule 3");
assertThat(list.size()).as("Three rules should have been fired").isEqualTo(3);
assertThat(list.get(0)).as("Rule 4 should have been fired first").isEqualTo("Rule 4");
assertThat(list.get(1)).as("Rule 2 should have been fired second").isEqualTo("Rule 2");
assertThat(list.get(2)).as("Rule 3 should have been fired third").isEqualTo("Rule 3");
} finally {
if (ksession != null) {
ksession.dispose();
}
}
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -387,7 +387,7 @@ private void processItemDefinitions(DMNCompilerContext ctx, DMNModelImpl model,
if (id.getItemComponent() != null && !id.getItemComponent().isEmpty()) {
DMNCompilerHelper.checkVariableName(model, id, id.getName());
CompositeTypeImpl compType = new CompositeTypeImpl(model.getNamespace(), id.getName(), id.getId(), id.isIsCollection());
DMNType preregistered = model.getTypeRegistry().registerType(compType);
model.getTypeRegistry().registerType(compType);
}
}

Expand Down Expand Up @@ -598,7 +598,31 @@ public void linkRequirements(DMNModelImpl model, DMNBaseNode node) {
*/
public static String getId(DMNElementReference er) {
String href = er.getHref();
return href.startsWith("#") ? href.substring(1) : href;
if (href.startsWith("#")) {
return href.substring(1);
} else {
Definitions rootElement = getRootElement(er);
String toRemove = String.format("%s#", rootElement.getNamespace());
return href.replace(toRemove, "");
}
}

/**
* Recursively navigate the given <code>DMNModelInstrumentedBase</code> until it gets to the root <code>Definitions</code> element.
* it throws a <code>RuntimeException</code> if such element could not be found.
*
* @param toNavigate
* @return
* @throws RuntimeException
*/
public static Definitions getRootElement(DMNModelInstrumentedBase toNavigate) {
if ( toNavigate instanceof Definitions ) {
return (Definitions) toNavigate;
} else if ( toNavigate.getParent() != null ) {
return getRootElement(toNavigate.getParent());
} else {
throw new RuntimeException("Failed to get Definitions parent for " + toNavigate);
}
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,32 +25,33 @@
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.kie.dmn.api.core.DMNContext;
import org.kie.dmn.api.core.DMNDecisionResult;
import org.kie.dmn.api.core.DMNMessage;
import org.kie.dmn.api.core.DMNModel;
import org.kie.dmn.api.core.DMNResult;
import org.kie.dmn.api.core.DMNRuntime;
import org.kie.dmn.api.core.DMNType;
import org.kie.dmn.api.core.FEELPropertyAccessible;
import org.kie.dmn.api.core.ast.DecisionNode;
import org.kie.dmn.api.core.ast.ItemDefNode;
import org.kie.dmn.core.api.DMNFactory;
import org.kie.dmn.core.compiler.DMNTypeRegistry;
import org.kie.dmn.core.impl.BaseDMNTypeImpl;
import org.kie.dmn.core.impl.CompositeTypeImpl;
import org.kie.dmn.core.impl.DMNContextFPAImpl;
import org.kie.dmn.core.impl.DMNModelImpl;
import org.kie.dmn.core.impl.DMNResultImpl;
import org.kie.dmn.core.impl.SimpleTypeImpl;
import org.kie.dmn.core.util.DMNRuntimeUtil;
import org.kie.dmn.feel.lang.EvaluationContext;
import org.kie.dmn.feel.lang.types.AliasFEELType;
import org.kie.dmn.feel.lang.types.BuiltInType;
import org.kie.dmn.model.api.Decision;
import org.kie.dmn.model.api.InformationRequirement;
import org.kie.dmn.model.api.KnowledgeRequirement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.InstanceOfAssertFactories.map;
import static org.kie.dmn.api.core.DMNDecisionResult.DecisionEvaluationStatus.SUCCEEDED;
import static org.kie.dmn.core.util.DynamicTypeUtils.entry;
import static org.kie.dmn.core.util.DynamicTypeUtils.mapOf;
Expand Down Expand Up @@ -470,6 +471,32 @@ void allowedValuesForComplexTypeInherited(VariantTestConf conf) {
assertThat(dmnAdultBobPerson.isAssignableValue(instanceYoungJoe)).isFalse();
}

@ParameterizedTest
@MethodSource("params")
void localHrefs(VariantTestConf conf) {
testConfig = conf;
String nameSpace = "http://www.montera.com.au/spec/DMN/local-hrefs";
final DMNRuntime runtime = DMNRuntimeUtil.createRuntime("valid_models/DMNv1_5/LocalHrefs.dmn", this.getClass());
final DMNModel dmnModel = runtime.getModel(
nameSpace,
"LocalHrefs");
assertThat(dmnModel).isNotNull();
assertThat(dmnModel.hasErrors()).as(DMNRuntimeUtil.formatMessages(dmnModel.getMessages())).isFalse();
DecisionNode retrievedDecisionNode = dmnModel.getDecisionByName("decision_002");
assertThat(retrievedDecisionNode).isNotNull();
Decision retrievedDecision = retrievedDecisionNode.getDecision();
assertThat(retrievedDecision).isNotNull();
assertThat(retrievedDecision.getInformationRequirement())
.isNotNull()
.isNotEmpty()
.allSatisfy((Consumer<InformationRequirement>) informationRequirement -> assertThat(informationRequirement).isNotNull());
assertThat(retrievedDecision.getKnowledgeRequirement())
.isNotNull()
.isNotEmpty()
.allSatisfy((Consumer<KnowledgeRequirement>) knowledgeRequirement -> assertThat(knowledgeRequirement).isNotNull());

}

private void commonValidateUnnamedImport(String importingModelRef, String importedModelRef) {
final DMNRuntime runtime = createRuntimeWithAdditionalResources(importingModelRef,
this.getClass(),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.kie.dmn.core.compiler;

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.kie.dmn.model.api.DMNElementReference;
import org.kie.dmn.model.api.Definitions;
import org.kie.dmn.model.api.InformationRequirement;
import org.kie.dmn.model.v1_5.TDMNElementReference;
import org.kie.dmn.model.v1_5.TDefinitions;
import org.kie.dmn.model.v1_5.TInformationRequirement;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;

class DMNCompilerImplTest {

private static final String nameSpace = "http://www.montera.com.au/spec/DMN/local-hrefs";
private static Definitions parent;

@BeforeAll
static void setup() {
String modelName = "LocalHrefs";
parent = new TDefinitions();
parent.setName(modelName);
parent.setNamespace(nameSpace);
}

@Test
void getId() {
String localPart = "reference";
DMNElementReference elementReference = new TDMNElementReference();
elementReference.setHref(String.format("%s#%s", nameSpace, localPart));
elementReference.setParent(parent);
String retrieved = DMNCompilerImpl.getId(elementReference);
assertThat(retrieved).isNotNull().isEqualTo(localPart);

String expected = String.format("%s#%s", "http://a-different-namespace", localPart);
elementReference.setHref(expected);
retrieved = DMNCompilerImpl.getId(elementReference);
assertThat(retrieved).isNotNull().isEqualTo(expected);
}

@Test
void getRootElement() {
String localPart = "reference";
DMNElementReference elementReference = new TDMNElementReference();
String href = String.format("%s#%s", nameSpace, localPart);
elementReference.setHref(href);
elementReference.setParent(parent);
Definitions retrieved = DMNCompilerImpl.getRootElement(elementReference);
assertThat(retrieved).isNotNull().isEqualTo(parent);

InformationRequirement informationRequirement = new TInformationRequirement();
elementReference.setParent(informationRequirement);
assertThrows(RuntimeException.class, () -> DMNCompilerImpl.getRootElement(elementReference));

informationRequirement.setParent(parent);
retrieved = DMNCompilerImpl.getRootElement(elementReference);
assertThat(retrieved).isNotNull().isEqualTo(parent);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
import org.kie.dmn.feel.lang.Type;
import org.kie.dmn.feel.lang.ast.forexpressioniterators.ForIteration;
import org.kie.dmn.feel.lang.types.BuiltInType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collections;
Expand All @@ -35,6 +37,7 @@
public class ForExpressionNode
extends BaseNode {

private static final Logger LOG = LoggerFactory.getLogger(ForExpressionNode.class);

private List<IterationContextNode> iterationContexts;
private BaseNode expression;
Expand Down Expand Up @@ -74,16 +77,11 @@ public void setExpression(BaseNode expression) {
public Object evaluate(EvaluationContext ctx) {
try {
ctx.enterFrame();
List results = new ArrayList();
ctx.setValue("partial", results);
ForIteration[] ictx = initializeContexts(ctx, iterationContexts);

while (nextIteration(ctx, ictx)) {
Object result = expression.evaluate(ctx);
results.add(result);
ctx.exitFrame(); // last i-th scope unrolled, see also ForExpressionNode.nextIteration(...)
}
return results;
List<Object> toReturn = new ArrayList<>();
ctx.setValue("partial", toReturn);
populateToReturn(0, ctx, toReturn);
LOG.trace("returning {}", toReturn);
return toReturn;
} catch (EndpointOfRangeNotValidTypeException | EndpointOfRangeOfDifferentTypeException e) {
// ast error already reported
return null;
Expand All @@ -92,61 +90,54 @@ public Object evaluate(EvaluationContext ctx) {
}
}

public static boolean nextIteration(EvaluationContext ctx, ForIteration[] ictx) {
int i = ictx.length - 1;
while (i >= 0 && i < ictx.length) {
if (ictx[i].hasNextValue()) {
ctx.enterFrame(); // on first iter, open last scope frame; or new ones when prev unrolled
setValueIntoContext(ctx, ictx[i]);
i++;
} else {
if (i > 0) {
// end of iter loop for this i-th scope; i-th scope is always unrolled as part of the
// for-loop cycle, so here must unroll the _prev_ scope;
// the if-guard for this code block makes sure NOT to unroll bottom one.
ctx.exitFrame();
}
i--;
private void populateToReturn(int k, EvaluationContext ctx, List<Object> toPopulate) {
LOG.trace("populateToReturn at index {}", k);
if (k > iterationContexts.size() - 1) {
LOG.trace("Index {} out of range, returning", k);
return;
}
IterationContextNode iterationContextNode = iterationContexts.get(k);
ForIteration forIteration = createForIteration(ctx, iterationContextNode);
while (forIteration.hasNextValue()) {
LOG.trace("{} has next value", forIteration);
ctx.enterFrame(); // open loop scope frame, for every iter ctx, except last one as guarded by if clause
// above
setValueIntoContext(ctx, forIteration.getName(), forIteration.getNextValue());
if (k == iterationContexts.size() - 1) {
LOG.trace("i == iterationContexts.size() -1: this is the last iteration context; evaluating {}",
expression);
Object result = expression.evaluate(ctx);
LOG.trace("add {} to toReturn", result);
toPopulate.add(result);
} else if (k < iterationContexts.size() - 1) {
populateToReturn(k + 1, ctx, toPopulate);
}
}
return i >= 0;
ctx.exitFrame();
}

public static void setValueIntoContext(EvaluationContext ctx, ForIteration forIteration) {
ctx.setValue(forIteration.getName(), forIteration.getNextValue());
static void setValueIntoContext(EvaluationContext ctx, String name, Object value) {
ctx.setValue(name, value);
}

@Override
public Type getResultType() {
return BuiltInType.LIST;
}

private ForIteration[] initializeContexts(EvaluationContext ctx, List<IterationContextNode> iterationContexts) {
ForIteration[] ictx = new ForIteration[iterationContexts.size()];
int i = 0;
for (IterationContextNode icn : iterationContexts) {
ictx[i] = createQuantifiedExpressionIterationContext(ctx, icn);
if (i < iterationContexts.size() - 1 && ictx[i].hasNextValue()) {
ctx.enterFrame(); // open loop scope frame, for every iter ctx, except last one as guarded by if clause above
setValueIntoContext(ctx, ictx[i]);
}
i++;
}
return ictx;
}

private ForIteration createQuantifiedExpressionIterationContext(EvaluationContext ctx, IterationContextNode icn) {
ForIteration fi;
String name = icn.evaluateName(ctx);
Object result = icn.evaluate(ctx);
Object rangeEnd = icn.evaluateRangeEnd(ctx);
private ForIteration createForIteration(EvaluationContext ctx, IterationContextNode iterationContextNode) {
LOG.trace("Creating ForIteration for {}", iterationContextNode);
ForIteration toReturn;
String name = iterationContextNode.evaluateName(ctx);
Object result = iterationContextNode.evaluate(ctx);
Object rangeEnd = iterationContextNode.evaluateRangeEnd(ctx);
if (rangeEnd == null) {
Iterable values = result instanceof Iterable ? (Iterable) result : Collections.singletonList(result);
fi = new ForIteration(name, values);
Iterable values = result instanceof Iterable iterable? iterable : Collections.singletonList(result);
toReturn = new ForIteration(name, values);
} else {
fi = getForIteration(ctx, name, result, rangeEnd);
toReturn = getForIteration(ctx, name, result, rangeEnd);
}
return fi;
return toReturn;
}

@Override
Expand All @@ -161,5 +152,4 @@ public ASTNode[] getChildrenNode() {
public <T> T accept(Visitor<T> v) {
return v.visit(this);
}

}
Loading

0 comments on commit 4291186

Please sign in to comment.