+ * 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.drools.model.codegen.execmodel;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.drools.model.codegen.execmodel.domain.Person;
+import org.junit.Before;
+import org.junit.Test;
+import org.kie.api.runtime.KieSession;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class ConditionalExprTest extends BaseModelTest {
+
+ private static final String RULE_STRING = "package constraintexpression\n" +
+ "\n" +
+ "import " + Person.class.getCanonicalName() + "\n" +
+ "import java.util.List; \n" +
+ "global List booleanListGlobal; \n" +
+ "rule \"r1\"\n" +
+ "when \n" +
+ " $p : Person($booleanVariable: (name != null ? true : false))\n" +
+ "then \n" +
+ " System.out.println($booleanVariable); \n" +
+ " System.out.println($p); \n" +
+ " booleanListGlobal.add($booleanVariable); \n " +
+ "end \n";
+
+ private KieSession ksession;
+ private List booleanListGlobal;
+
+ public ConditionalExprTest(RUN_TYPE testRunType) {
+ super(testRunType);
+ }
+
+ @Before
+ public void setup() {
+ ksession = getKieSession(RULE_STRING);
+ booleanListGlobal = new ArrayList<>();
+ ksession.setGlobal("booleanListGlobal", booleanListGlobal);
+ }
+
+ @Test
+ public void testConditionalExpressionWithNamedPerson() {
+ try {
+ Person person = new Person("someName");
+ ksession.insert(person);
+ int rulesFired = ksession.fireAllRules();
+ assertThat(rulesFired).isEqualTo(1);
+ assertThat(booleanListGlobal).isNotEmpty().containsExactly(Boolean.TRUE);
+ } finally {
+ ksession.dispose();
+ }
+ }
+
+ @Test
+ public void testConditionalExpressionWithUnnamedPerson() {
+ try {
+ Person person = new Person();
+ ksession.insert(person);
+ int rulesFired = ksession.fireAllRules();
+ assertThat(rulesFired).isEqualTo(1);
+ assertThat(booleanListGlobal).isNotEmpty().containsExactly(Boolean.FALSE);
+ } finally {
+ ksession.dispose();
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ConstraintTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ConstraintTest.java
new file mode 100644
index 00000000000..b3475e58c2d
--- /dev/null
+++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ConstraintTest.java
@@ -0,0 +1,90 @@
+/**
+ * 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.drools.model.codegen.execmodel;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.drools.model.codegen.execmodel.domain.Person;
+import org.junit.Before;
+import org.junit.Test;
+import org.kie.api.runtime.KieSession;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class ConstraintTest extends BaseModelTest {
+
+ private static final String RULE_STRING = "package constraintexpression\n" +
+ "\n" +
+ "import " + Person.class.getCanonicalName() + "\n" +
+ "import java.util.List; \n" +
+ "import java.math.BigDecimal; \n" +
+ "global List bigDecimalListGlobal; \n" +
+ "rule \"r1\"\n" +
+ "when \n" +
+ " $p : Person($amount: (money == null ? BigDecimal.valueOf(100.0) : money))\n" +
+ "then \n" +
+ " System.out.println($amount); \n" +
+ " System.out.println($p); \n" +
+ " bigDecimalListGlobal.add($amount); \n " +
+ "end \n";
+
+ private KieSession ksession;
+
+ private List bigDecimalListGlobal;
+
+ public ConstraintTest(RUN_TYPE testRunType) {
+ super(testRunType);
+ }
+
+ @Before
+ public void setup() {
+ ksession = getKieSession(RULE_STRING);
+ bigDecimalListGlobal = new ArrayList<>();
+ ksession.setGlobal("bigDecimalListGlobal", bigDecimalListGlobal);
+ }
+
+ @Test
+ public void testConstraintWithMoney() {
+ try {
+ BigDecimal money = BigDecimal.valueOf(34.45);
+ Person person = new Person("", money);
+ ksession.insert(person);
+ int rulesFired = ksession.fireAllRules();
+ assertThat(rulesFired).isEqualTo(1);
+ assertThat(bigDecimalListGlobal).isNotEmpty().containsExactly(money);
+ } finally {
+ ksession.dispose();
+ }
+ }
+
+ @Test
+ public void testConstraintWithoutMoney() {
+ try {
+ Person person = new Person();
+ ksession.insert(person);
+ int rulesFired = ksession.fireAllRules();
+ assertThat(rulesFired).isEqualTo(1);
+ assertThat(bigDecimalListGlobal).isNotEmpty().containsExactly(BigDecimal.valueOf(100.0));
+ } finally {
+ ksession.dispose();
+ }
+ }
+}
diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ArithmeticCoecionTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NumberAndStringArithmeticOperationCoercionTest.java
similarity index 97%
rename from drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ArithmeticCoecionTest.java
rename to drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NumberAndStringArithmeticOperationCoercionTest.java
index 012a2532add..b92641ad932 100644
--- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/ArithmeticCoecionTest.java
+++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/NumberAndStringArithmeticOperationCoercionTest.java
@@ -26,9 +26,9 @@
import static org.assertj.core.api.Assertions.assertThat;
-public class ArithmeticCoecionTest extends BaseModelTest {
+public class NumberAndStringArithmeticOperationCoercionTest extends BaseModelTest {
- public ArithmeticCoecionTest(RUN_TYPE testRunType) {
+ public NumberAndStringArithmeticOperationCoercionTest(RUN_TYPE testRunType) {
super(testRunType);
}
diff --git a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TypeCoercionTest.java b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TypeCoercionTest.java
index 95a49e3ac1b..67cd73f3bd3 100644
--- a/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TypeCoercionTest.java
+++ b/drools-model/drools-model-codegen/src/test/java/org/drools/model/codegen/execmodel/TypeCoercionTest.java
@@ -612,4 +612,30 @@ public void testFloatOperation() {
assertThat(list.size()).isEqualTo(1);
assertThat(list.get(0)).isEqualTo("Mario");
}
+
+ @Test
+ public void testCoerceObjectToString() {
+ String str = "package constraintexpression\n" +
+ "\n" +
+ "import " + Person.class.getCanonicalName() + "\n" +
+ "import java.util.List; \n" +
+ "rule \"r1\"\n" +
+ "when \n" +
+ " $p: Person() \n" +
+ " String(this == \"someString\" + $p)\n" +
+ "then \n" +
+ " System.out.println($p); \n" +
+ "end \n";
+
+ KieSession ksession = getKieSession(str);
+ try {
+ Person person = new Person("someName");
+ ksession.insert(person);
+ ksession.insert(new String("someStringsomeName"));
+ int rulesFired = ksession.fireAllRules();
+ assertThat(rulesFired).isEqualTo(1);
+ } finally {
+ ksession.dispose();
+ }
+ }
}
\ No newline at end of file
diff --git a/drools-model/drools-mvel-parser/src/test/java/org/drools/mvel/parser/DroolsMvelParserTest.java b/drools-model/drools-mvel-parser/src/test/java/org/drools/mvel/parser/DroolsMvelParserTest.java
index ea5f6987194..49910e35269 100644
--- a/drools-model/drools-mvel-parser/src/test/java/org/drools/mvel/parser/DroolsMvelParserTest.java
+++ b/drools-model/drools-mvel-parser/src/test/java/org/drools/mvel/parser/DroolsMvelParserTest.java
@@ -182,6 +182,22 @@ public void testDotFreeEnclosed() {
assertThat(printNode(expression)).isEqualTo(expr);
}
+ @Test
+ public void testConstantUnaryExpression() {
+ String expr = "-49";
+ Expression expression = parseExpression( parser, expr ).getExpr();
+ assertThat(printNode(expression)).isEqualTo(expr);
+ assertThat(expression.isUnaryExpr()).isTrue();
+ }
+
+ @Test
+ public void testVariableUnaryExpression() {
+ String expr = "-$a";
+ Expression expression = parseExpression( parser, expr ).getExpr();
+ assertThat(printNode(expression)).isEqualTo(expr);
+ assertThat(expression.isUnaryExpr()).isTrue();
+ }
+
@Test
public void testDotFreeEnclosedWithNameExpr() {
String expr = "(something after $a)";
@@ -402,10 +418,12 @@ public void testAndWithImplicitNegativeParameter() {
BinaryExpr first = (BinaryExpr) comboExpr.getLeft();
assertThat(toString(first.getLeft())).isEqualTo("value");
assertThat(toString(first.getRight())).isEqualTo("-2");
+ assertThat(first.getRight().isUnaryExpr()).isTrue();
assertThat(first.getOperator()).isEqualTo(Operator.GREATER);
HalfBinaryExpr second = (HalfBinaryExpr) comboExpr.getRight();
assertThat(toString(second.getRight())).isEqualTo("-1");
+ assertThat(second.getRight().isUnaryExpr()).isTrue();
assertThat(second.getOperator()).isEqualTo(HalfBinaryExpr.Operator.LESS);
}
diff --git a/drools-mvel/src/main/java/org/drools/mvel/MVELConstraintBuilder.java b/drools-mvel/src/main/java/org/drools/mvel/MVELConstraintBuilder.java
index 7d03ed6cb31..38809896b71 100644
--- a/drools-mvel/src/main/java/org/drools/mvel/MVELConstraintBuilder.java
+++ b/drools-mvel/src/main/java/org/drools/mvel/MVELConstraintBuilder.java
@@ -480,7 +480,7 @@ public boolean canConvertFrom(Class cls) {
public static class StringCoercionCompatibilityEvaluator extends CompatibilityStrategy.DefaultCompatibilityEvaluator {
- private static final CompatibilityStrategy.CompatibilityEvaluator INSTANCE = new StringCoercionCompatibilityEvaluator();
+ public static final CompatibilityStrategy.CompatibilityEvaluator INSTANCE = new StringCoercionCompatibilityEvaluator();
private StringCoercionCompatibilityEvaluator() { }
diff --git a/drools-mvel/src/test/java/org/drools/mvel/MVELDateCoercionTest.java b/drools-mvel/src/test/java/org/drools/mvel/MVELDateCoercionTest.java
index 4eec3e14162..9e06729024a 100644
--- a/drools-mvel/src/test/java/org/drools/mvel/MVELDateCoercionTest.java
+++ b/drools-mvel/src/test/java/org/drools/mvel/MVELDateCoercionTest.java
@@ -20,13 +20,23 @@
import java.text.SimpleDateFormat;
import java.util.Date;
+import java.util.HashMap;
import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import org.drools.mvel.MVELConstraintBuilder.StringCoercionCompatibilityEvaluator;
import org.drools.util.DateUtils;
import org.drools.mvel.expr.MVELDateCoercion;
import org.junit.Test;
+import org.mvel2.DataConversion;
+import org.mvel2.MVEL;
+import org.mvel2.ParserContext;
+import org.mvel2.util.CompatibilityStrategy;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.within;
+import static org.mvel2.MVEL.executeExpression;
public class MVELDateCoercionTest {
@@ -51,4 +61,66 @@ public void testString() throws Exception {
assertThat(co.convertFrom(dt)).isEqualTo(dt_);
}
+ @Test
+ public void testCoercionDuringAnalyze() {
+ CompatibilityStrategy.setCompatibilityEvaluator(StringCoercionCompatibilityEvaluator.INSTANCE);
+
+ DataConversion.addConversionHandler(Date.class,
+ new MVELDateCoercion());
+
+ String expr = "f.departureTime >= \"01-Jan-1970\" && f.departureTime <= \"01-Jan-2018\"";
+
+ ParserContext ctx = new ParserContext();
+ ctx.setStrongTyping(true);
+ ctx.setStrictTypeEnforcement(true);
+ ctx.addInput("f", Flight.class);
+
+ Class cls = MVEL.analyze( expr,
+ ctx );
+
+ assertThat(cls).isNotNull();
+ }
+
+ public static class Flight {
+ private Date departureTime;
+
+ public Flight(Date departureTime) {
+ this.departureTime = departureTime;
+ }
+
+ public Date getDepartureTime() {
+ return departureTime;
+ }
+
+ public void setDepartureTime(Date departureTime) {
+ this.departureTime = departureTime;
+ }
+
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+
+ Flight flight = (Flight) o;
+
+ return Objects.equals(departureTime, flight.departureTime);
+ }
+
+ @Override
+ public int hashCode() {
+ return departureTime != null ? departureTime.hashCode() : 0;
+ }
+
+ @Override
+ public String toString() {
+ return "Flight{" +
+ "departureTime=" + departureTime +
+ '}';
+ }
+ }
}
diff --git a/drools-persistence/drools-persistence-jpa/pom.xml b/drools-persistence/drools-persistence-jpa/pom.xml
index 2192238f8c4..be32646c131 100644
--- a/drools-persistence/drools-persistence-jpa/pom.xml
+++ b/drools-persistence/drools-persistence-jpa/pom.xml
@@ -39,7 +39,6 @@
- org.hibernate.dialect.H2Dialectorg.h2.jdbcx.JdbcDataSourceorg.h2.Driver
@@ -74,6 +73,7 @@
${maven.jdbc.driver.jar}
+ -javaagent:${settings.localRepository}/org/apache/openjpa/openjpa/${version.org.apache.openjpa}/openjpa-${version.org.apache.openjpa}.jar
@@ -161,22 +161,12 @@
test
-
-
- org.hibernate.orm
- hibernate-core
+
+ org.apache.openjpa
+ openjpatest
-
-
- org.glassfish.jaxb
- jaxb-runtime
-
-
- org.jboss
- jandex
-
-
+
io.smallryejandex
@@ -193,12 +183,18 @@
logback-classictest
+
+ org.jboss.logging
+ jboss-logging
+ test
+ com.h2databaseh2test
+
org.jboss.narayana.jtanarayana-jta
diff --git a/drools-persistence/drools-persistence-jpa/src/main/java/org/drools/persistence/info/SessionInfo.java b/drools-persistence/drools-persistence-jpa/src/main/java/org/drools/persistence/info/SessionInfo.java
index 54fd6cc38ad..2c16a42b663 100644
--- a/drools-persistence/drools-persistence-jpa/src/main/java/org/drools/persistence/info/SessionInfo.java
+++ b/drools-persistence/drools-persistence-jpa/src/main/java/org/drools/persistence/info/SessionInfo.java
@@ -38,7 +38,7 @@
public class SessionInfo implements PersistentSession {
private @Id
- @GeneratedValue(strategy = GenerationType.AUTO, generator="sessionInfoIdSeq")
+ @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="sessionInfoIdSeq")
Long id;
@Version
diff --git a/drools-persistence/drools-persistence-jpa/src/main/java/org/drools/persistence/info/WorkItemInfo.java b/drools-persistence/drools-persistence-jpa/src/main/java/org/drools/persistence/info/WorkItemInfo.java
index ce26c9d2f87..2f65a971ca8 100644
--- a/drools-persistence/drools-persistence-jpa/src/main/java/org/drools/persistence/info/WorkItemInfo.java
+++ b/drools-persistence/drools-persistence-jpa/src/main/java/org/drools/persistence/info/WorkItemInfo.java
@@ -55,7 +55,7 @@ public class WorkItemInfo implements PersistentWorkItem {
private static final Logger logger = LoggerFactory.getLogger(WorkItemInfo.class);
@Id
- @GeneratedValue(strategy = GenerationType.AUTO, generator="workItemInfoIdSeq")
+ @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="workItemInfoIdSeq")
private Long workItemId;
@Version
diff --git a/drools-persistence/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/OptimisticLockRetryInterceptor.java b/drools-persistence/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/OptimisticLockRetryInterceptor.java
index 91485667576..046085e94d5 100644
--- a/drools-persistence/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/OptimisticLockRetryInterceptor.java
+++ b/drools-persistence/drools-persistence-jpa/src/main/java/org/drools/persistence/jpa/OptimisticLockRetryInterceptor.java
@@ -18,15 +18,15 @@
*/
package org.drools.persistence.jpa;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import jakarta.persistence.OptimisticLockException;
import org.drools.commands.impl.AbstractInterceptor;
import org.kie.api.runtime.Executable;
import org.kie.api.runtime.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import jakarta.persistence.OptimisticLockException;
-import java.util.concurrent.atomic.AtomicInteger;
-
/**
* ExecutableInterceptor that is capable of retrying command execution. It is intended to retry only if right exception
* has been thrown. By default it will look for org.hibernate.StaleObjectStateException and only
@@ -58,14 +58,14 @@ public class OptimisticLockRetryInterceptor extends AbstractInterceptor {
private static final ThreadLocal invocationsCounter = new ThreadLocal<>();
public OptimisticLockRetryInterceptor() {
- String clazz = System.getProperty("org.kie.optlock.exclass", "org.hibernate.StaleObjectStateException");
+ String clazz = System.getProperty("org.kie.optlock.exclass", "org.apache.openjpa.persistence.OptimisticLockException");
try {
targetExceptionClass = Class.forName(clazz);
} catch (ClassNotFoundException e) {
logger.error("Optimistic locking exception class not found {}", clazz, e);
}
- clazz = System.getProperty("org.kie.constraint.exclass", "org.hibernate.exception.ConstraintViolationException");
+ clazz = System.getProperty("org.kie.constraint.exclass", "org.apache.openjpa.util.InvalidStateException");
try {
targetConstraintViolationExceptionClass = Class.forName(clazz);
} catch (ClassNotFoundException e) {
diff --git a/drools-persistence/drools-persistence-jpa/src/test/filtered-resources/META-INF/persistence.xml b/drools-persistence/drools-persistence-jpa/src/test/filtered-resources/META-INF/persistence.xml
index 845fcc9f72a..c57bf903ac7 100644
--- a/drools-persistence/drools-persistence-jpa/src/test/filtered-resources/META-INF/persistence.xml
+++ b/drools-persistence/drools-persistence-jpa/src/test/filtered-resources/META-INF/persistence.xml
@@ -25,7 +25,7 @@
xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_0.xsd">
- org.hibernate.jpa.HibernatePersistenceProvider
+ org.apache.openjpa.persistence.PersistenceProviderImpljdbc/testDS1org.drools.persistence.info.SessionInfoorg.drools.persistence.info.WorkItemInfo
@@ -34,19 +34,7 @@
org.drools.persistence.jta.TransactionTestObject
-
-
-
-
-
-
-
-
-
-
-
-
-
+
diff --git a/drools-persistence/drools-persistence-jpa/src/test/java/org/drools/persistence/jta/JtaTransactionManagerTest.java b/drools-persistence/drools-persistence-jpa/src/test/java/org/drools/persistence/jta/JtaTransactionManagerTest.java
index 449fc7759ae..f8cbff8e23a 100644
--- a/drools-persistence/drools-persistence-jpa/src/test/java/org/drools/persistence/jta/JtaTransactionManagerTest.java
+++ b/drools-persistence/drools-persistence-jpa/src/test/java/org/drools/persistence/jta/JtaTransactionManagerTest.java
@@ -35,7 +35,6 @@
import org.drools.persistence.api.TransactionManager;
import org.drools.persistence.jpa.JpaPersistenceContextManager;
import org.drools.persistence.util.DroolsPersistenceUtil;
-import org.hibernate.TransientObjectException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -150,7 +149,7 @@ public void showingTransactionTestObjectsNeedTransactions() throws Exception {
tx.commit();
}
catch( Exception e ) {
- if( e instanceof RollbackException || e.getCause() instanceof TransientObjectException ) {
+ if ( e instanceof RollbackException ) {
rollBackExceptionthrown = true;
if( tx.getStatus() == 1 ) {
diff --git a/drools-persistence/drools-persistence-jpa/src/test/java/org/drools/persistence/jta/TransactionTestObject.java b/drools-persistence/drools-persistence-jpa/src/test/java/org/drools/persistence/jta/TransactionTestObject.java
index c9930291c87..e2d1b407c88 100644
--- a/drools-persistence/drools-persistence-jpa/src/test/java/org/drools/persistence/jta/TransactionTestObject.java
+++ b/drools-persistence/drools-persistence-jpa/src/test/java/org/drools/persistence/jta/TransactionTestObject.java
@@ -41,7 +41,7 @@ public class TransactionTestObject implements Serializable {
private static final long serialVersionUID = 8991032325499307158L;
@Id
- @GeneratedValue(strategy=GenerationType.AUTO, generator="txTestIdSeq")
+ @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="txTestIdSeq")
@Column(name="ID")
private Long id;
diff --git a/drools-persistence/drools-persistence-jpa/src/test/java/org/drools/persistence/map/impl/JpaBasedPersistenceTest.java b/drools-persistence/drools-persistence-jpa/src/test/java/org/drools/persistence/map/impl/JpaBasedPersistenceTest.java
index 730575a1a4d..e2e75149da6 100644
--- a/drools-persistence/drools-persistence-jpa/src/test/java/org/drools/persistence/map/impl/JpaBasedPersistenceTest.java
+++ b/drools-persistence/drools-persistence-jpa/src/test/java/org/drools/persistence/map/impl/JpaBasedPersistenceTest.java
@@ -18,6 +18,11 @@
*/
package org.drools.persistence.map.impl;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Map;
+
+import jakarta.persistence.EntityManagerFactory;
import org.drools.persistence.jpa.marshaller.JPAPlaceholderResolverStrategy;
import org.drools.persistence.jta.JtaTransactionManager;
import org.drools.persistence.util.DroolsPersistenceUtil;
@@ -34,11 +39,6 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import jakarta.persistence.EntityManagerFactory;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Map;
-
import static org.drools.persistence.util.DroolsPersistenceUtil.DROOLS_PERSISTENCE_UNIT_NAME;
import static org.drools.persistence.util.DroolsPersistenceUtil.OPTIMISTIC_LOCKING;
import static org.drools.persistence.util.DroolsPersistenceUtil.PESSIMISTIC_LOCKING;
@@ -115,7 +115,7 @@ protected long getSavedSessionsCount() {
if( useTransactions ) {
transactionOwner = txm.begin();
}
- long savedSessionsCount = emf.createEntityManager().createQuery( "FROM SessionInfo" ).getResultList().size();
+ long savedSessionsCount = emf.createEntityManager().createQuery( "SELECT DISTINCT id FROM SessionInfo AS id" ).getResultList().size();
if( useTransactions ) {
txm.commit(transactionOwner);
}
diff --git a/drools-quarkus-extension/drools-quarkus-quickstart-test/guide.adoc b/drools-quarkus-extension/drools-quarkus-quickstart-test/guide.adoc
index 3ce852d4a17..bb74e51dc27 100644
--- a/drools-quarkus-extension/drools-quarkus-quickstart-test/guide.adoc
+++ b/drools-quarkus-extension/drools-quarkus-quickstart-test/guide.adoc
@@ -17,8 +17,8 @@ To complete this guide, you need:
* less than 15 minutes
* an IDE
-* JDK 11+ installed with `JAVA_HOME` configured appropriately
-* Apache Maven 3.8.6+
+* JDK 17+ installed with `JAVA_HOME` configured appropriately
+* Apache Maven 3.9.3+
* Docker
* link:{quarkus-guides-url}/building-native-image[GraalVM installed if you want to run in native mode]
diff --git a/drools-quarkus-extension/drools-quarkus/pom.xml b/drools-quarkus-extension/drools-quarkus/pom.xml
index 75ef13e08ac..b30722604f1 100644
--- a/drools-quarkus-extension/drools-quarkus/pom.xml
+++ b/drools-quarkus-extension/drools-quarkus/pom.xml
@@ -29,8 +29,10 @@
999-SNAPSHOT
- Drools :: Quarkus Extension :: Runtimedrools-quarkus
+ Drools Quarkus - Runtime
+ Define and execute your business rules with Drools
+ https://www.drools.org/org.drools.quarkus.runtime
@@ -124,7 +126,7 @@
${project.groupId}:${project.artifactId}-deployment:${project.version}
- org.drools.drl
+ org.drools
diff --git a/drools-quarkus-extension/drools-quarkus/src/main/resources/META-INF/quarkus-extension.yaml b/drools-quarkus-extension/drools-quarkus/src/main/resources/META-INF/quarkus-extension.yaml
index 714ddd8efc2..0ed9233b1d2 100644
--- a/drools-quarkus-extension/drools-quarkus/src/main/resources/META-INF/quarkus-extension.yaml
+++ b/drools-quarkus-extension/drools-quarkus/src/main/resources/META-INF/quarkus-extension.yaml
@@ -18,9 +18,15 @@
#
---
-name: "Drools-DRL"
+name: "Drools"
metadata:
keywords:
- "drools"
- "rules"
+ - "rule engine"
+ - "artificial intelligence"
- "DRL"
+ guide: "https://quarkus.io/guides/drools"
+ categories:
+ - "business-automation"
+ status: "stable"
\ No newline at end of file
diff --git a/drools-traits/pom.xml b/drools-traits/pom.xml
index 09f4e5a7875..896e33b2774 100644
--- a/drools-traits/pom.xml
+++ b/drools-traits/pom.xml
@@ -41,7 +41,6 @@
- org.hibernate.dialect.H2Dialectorg.h2.jdbcx.JdbcDataSourceorg.h2.Driver
@@ -128,6 +127,11 @@
org.slf4jslf4j-api
+
+ org.jboss.logging
+ jboss-logging
+ test
+ ch.qos.logbacklogback-classic
@@ -156,23 +160,12 @@
jboss-transaction-spi-jakartatest
-
-
-
- org.hibernate.orm
- hibernate-core
+
+ org.apache.openjpa
+ openjpatest
-
-
- org.glassfish.jaxb
- jaxb-runtime
-
-
- org.jboss
- jandex
-
-
+
io.smallryejandex
@@ -200,10 +193,9 @@
mockito-coretest
-
-
+
@@ -215,6 +207,16 @@
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+ -javaagent:${settings.localRepository}/org/apache/openjpa/openjpa/${version.org.apache.openjpa}/openjpa-${version.org.apache.openjpa}.jar
+
+
+
+
src/test/resources
diff --git a/drools-traits/src/test/filtered-resources/META-INF/persistence.xml b/drools-traits/src/test/filtered-resources/META-INF/persistence.xml
index 845fcc9f72a..04c82efe309 100644
--- a/drools-traits/src/test/filtered-resources/META-INF/persistence.xml
+++ b/drools-traits/src/test/filtered-resources/META-INF/persistence.xml
@@ -25,28 +25,16 @@
xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_0.xsd">
- org.hibernate.jpa.HibernatePersistenceProvider
- jdbc/testDS1
+ org.apache.openjpa.persistence.PersistenceProviderImpl
+ jdbc/testDS1org.drools.persistence.info.SessionInfoorg.drools.persistence.info.WorkItemInfo
-
+
org.drools.persistence.jta.TransactionTestObject
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
+
diff --git a/drools-util/pom.xml b/drools-util/pom.xml
index 7bc2377c5fc..3fd81109ddf 100644
--- a/drools-util/pom.xml
+++ b/drools-util/pom.xml
@@ -41,6 +41,10 @@
+
+ org.slf4j
+ slf4j-api
+ org.eclipse.microprofile.configmicroprofile-config-api
diff --git a/drools-util/src/main/java/org/drools/util/FileUtils.java b/drools-util/src/main/java/org/drools/util/FileUtils.java
index d62a9ef730b..799d7464980 100644
--- a/drools-util/src/main/java/org/drools/util/FileUtils.java
+++ b/drools-util/src/main/java/org/drools/util/FileUtils.java
@@ -42,6 +42,7 @@ private FileUtils() {
/**
* Retrieve the File of the given file
+ * This method does not guarantee the returned file if multiple files, with same name, are present in different directories
* @param fileName
* @return
*/
@@ -58,6 +59,31 @@ public static File getFile(String fileName) {
return toReturn;
}
+ /**
+ * Retrieve the File of the given file
+ * @param fileName
+ * @param parentDir
+ * @return
+ */
+ public static File getFile(String fileName, String parentDir) {
+ String extension = fileName.substring(fileName.lastIndexOf('.') + 1);
+ File parentDirectory = new File(parentDir);
+ if (!parentDirectory.exists() || !parentDirectory.canRead() || !parentDirectory.isDirectory()) {
+ throw new IllegalArgumentException("Failed to find parent directory " + parentDir);
+ }
+ File toReturn = ResourceHelper.getFileResourcesByExtension(extension)
+ .stream()
+ .filter(file -> file.getName().equals(fileName) &&
+ file.getParentFile() != null &&
+ file.getParentFile().getAbsolutePath().equals(parentDirectory.getAbsolutePath()))
+ .findFirst()
+ .orElse(null);
+ if (toReturn == null) {
+ throw new IllegalArgumentException("Failed to find file " + fileName);
+ }
+ return toReturn;
+ }
+
/**
* Retrieve the FileInputStream of the given file
* @param fileName
@@ -69,6 +95,18 @@ public static FileInputStream getFileInputStream(String fileName) throws IOExcep
return new FileInputStream(sourceFile);
}
+ /**
+ * Retrieve the FileInputStream of the given file
+ * @param fileName
+ * @param parentDir
+ * @return
+ * @throws IOException
+ */
+ public static FileInputStream getFileInputStream(String fileName, String parentDir) throws IOException {
+ File sourceFile = getFile(fileName, parentDir);
+ return new FileInputStream(sourceFile);
+ }
+
/**
* Retrieve the content of the given file
* @param fileName
@@ -84,6 +122,22 @@ public static String getFileContent(String fileName) throws IOException {
return toReturn;
}
+ /**
+ * Retrieve the content of the given file
+ * @param fileName
+ * @param parentDir
+ * @return
+ * @throws IOException
+ */
+ public static String getFileContent(String fileName, String parentDir) throws IOException {
+ File file = getFile(fileName, parentDir);
+ Path path = file.toPath();
+ Stream lines = Files.lines(path);
+ String toReturn = lines.collect(Collectors.joining("\n"));
+ lines.close();
+ return toReturn;
+ }
+
/**
* @param fileName
* @param classLoader
diff --git a/drools-util/src/main/java/org/drools/util/Pair.java b/drools-util/src/main/java/org/drools/util/Pair.java
new file mode 100644
index 00000000000..4408263db50
--- /dev/null
+++ b/drools-util/src/main/java/org/drools/util/Pair.java
@@ -0,0 +1,28 @@
+package org.drools.util;
+
+public class Pair {
+
+ private final K left;
+ private final V right;
+
+ public Pair(K k, V v) {
+ this.left = k;
+ this.right = v;
+ }
+
+ public K getLeft() {
+ return left;
+ }
+
+ public V getRight() {
+ return right;
+ }
+
+ public boolean hasLeft() {
+ return left != null;
+ }
+
+ public boolean hasRight() {
+ return right != null;
+ }
+}
diff --git a/drools-util/src/main/java/org/drools/util/RemoveCommentsMain.java b/drools-util/src/main/java/org/drools/util/RemoveCommentsMain.java
index 014a1b23bf1..024320a8b28 100644
--- a/drools-util/src/main/java/org/drools/util/RemoveCommentsMain.java
+++ b/drools-util/src/main/java/org/drools/util/RemoveCommentsMain.java
@@ -1,27 +1,50 @@
package org.drools.util;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import java.io.IOException;
import java.nio.file.Files;
+import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.stream.Collectors;
public class RemoveCommentsMain {
+ private static final Logger LOGGER = LoggerFactory.getLogger(RemoveCommentsMain.class);
+
public static void main(String... args) {
- for (String fileName : args) {
- try {
- Files.write(Path.of(fileName), removeComments(fileName).getBytes());
- } catch (IOException e) {
- throw new RuntimeException(e);
+ final String ignoreMissingFilesArgument = args[0];
+ final boolean ignoreMissingFiles = Boolean.parseBoolean(ignoreMissingFilesArgument);
+ for (int i = 0; i < args.length; i++) {
+ // If the ignoreMissingFiles argument is defined, skip it in this iteration.
+ if ((ignoreMissingFiles || "false".equalsIgnoreCase(ignoreMissingFilesArgument)) && i == 0) {
+ continue;
+ } else {
+ try {
+ final String fileName = args[i];
+ final String result = removeComments(fileName, ignoreMissingFiles);
+ if (result != null) {
+ Files.write(Path.of(fileName), result.getBytes());
+ }
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
}
}
}
- static String removeComments(String fileName) {
+ static String removeComments(String fileName, final boolean ignoreMissingFiles) {
try (var lines = Files.lines(Path.of(fileName))) {
return lines.filter(line -> !line.startsWith("#")).collect(Collectors.joining("\n"));
} catch (IOException e) {
- throw new RuntimeException(e);
+ // Ignore non-existant files.
+ if (ignoreMissingFiles && e instanceof NoSuchFileException) {
+ LOGGER.info("Ignoring file that doesn't exist: " + fileName);
+ return null;
+ } else {
+ throw new RuntimeException(e);
+ }
}
}
diff --git a/drools-util/src/test/java/org/drools/util/FileUtilsTest.java b/drools-util/src/test/java/org/drools/util/FileUtilsTest.java
index c48d53f9e92..1a7e1064ac5 100644
--- a/drools-util/src/test/java/org/drools/util/FileUtilsTest.java
+++ b/drools-util/src/test/java/org/drools/util/FileUtilsTest.java
@@ -22,6 +22,7 @@
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
@@ -33,14 +34,24 @@
public class FileUtilsTest {
- private static final String TEST_FILE = "TestFile.txt";
+ public static final String TEST_FILE = "TestFile.txt";
private static final String NOT_EXISTING_FILE = "NotExisting.txt";
+ private static final String EXISTING_DIRECTORY = "subdir";
+
+ private static final String NOT_EXISTING_DIRECTORY = String.format(".%snotexisting", File.separator);
+
@Test
public void getFileExisting() {
final File retrieved = FileUtils.getFile(TEST_FILE);
- assertThat(retrieved).exists();
- assertThat(retrieved.getName()).isEqualTo(TEST_FILE);
+ assertThat(retrieved).exists().hasName(TEST_FILE);
+ }
+
+ @Test
+ public void getFileExistingFromDirectory() {
+ final File retrieved = FileUtils.getFile(TEST_FILE, getSubdir());
+ assertThat(retrieved).exists().hasName(TEST_FILE);
+ assertThat(retrieved.getParentFile()).exists().isDirectory().hasName(EXISTING_DIRECTORY);
}
@Test
@@ -48,6 +59,11 @@ public void getFileNotExisting() {
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> FileUtils.getFile(NOT_EXISTING_FILE));
}
+ @Test
+ public void getFileNotExistingDirectory() {
+ assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> FileUtils.getFile(TEST_FILE, NOT_EXISTING_DIRECTORY));
+ }
+
@Test
public void getFileInputStreamExisting() throws IOException {
final FileInputStream retrieved = FileUtils.getFileInputStream(TEST_FILE);
@@ -80,4 +96,13 @@ public void deleteDirectory() throws IOException {
assertThat(Files.exists(tempDirectory)).isFalse();
assertThat(Files.exists(tempFile)).isFalse();
}
+
+ private static String getSubdir() {
+ URL subdirResource = FileUtilsTest.class.getClassLoader().getResource(EXISTING_DIRECTORY);
+ if (subdirResource == null) {
+ throw new RuntimeException("Failed to find subdir folder");
+ } else {
+ return subdirResource.getFile();
+ }
+ }
}
\ No newline at end of file
diff --git a/drools-util/src/test/java/org/drools/util/RemoveCommentsTest.java b/drools-util/src/test/java/org/drools/util/RemoveCommentsTest.java
index 91bbceba3dd..1b529b5acc7 100644
--- a/drools-util/src/test/java/org/drools/util/RemoveCommentsTest.java
+++ b/drools-util/src/test/java/org/drools/util/RemoveCommentsTest.java
@@ -8,7 +8,7 @@ public class RemoveCommentsTest {
@Test
public void test() {
- String result = RemoveCommentsMain.removeComments("src/test/resources/commented.properties");
+ String result = RemoveCommentsMain.removeComments("src/test/resources/commented.properties", false);
String expected = "provides-capabilities=org.drools.drl\ndeployment-artifact=org.drools\\:drools-quarkus-deployment\\:999-SNAPSHOT";
assertEquals(expected, result);
}
diff --git a/drools-util/src/test/java/org/drools/util/ResourceHelperTest.java b/drools-util/src/test/java/org/drools/util/ResourceHelperTest.java
index e33653772c4..f314dfc7017 100644
--- a/drools-util/src/test/java/org/drools/util/ResourceHelperTest.java
+++ b/drools-util/src/test/java/org/drools/util/ResourceHelperTest.java
@@ -29,6 +29,7 @@
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.drools.util.FileUtilsTest.TEST_FILE;
import static org.drools.util.ResourceHelper.getFileResourcesByExtension;
import static org.drools.util.ResourceHelper.getFileResourcesFromDirectory;
import static org.drools.util.ResourceHelper.getResourcesByExtension;
@@ -37,14 +38,13 @@
public class ResourceHelperTest {
- private static final String TEST_FILE = "TestFile.txt";
@Test
public void getResourcesByExtensionTest() {
Collection resources = getResourcesByExtension("txt");
assertThat(resources)
- .hasSize(1)
- .anyMatch(elem -> elem.endsWith(TEST_FILE));
+ .hasSize(2)
+ .allMatch(elem -> elem.endsWith(TEST_FILE));
}
@Test
@@ -64,11 +64,11 @@ public void getResourcesFromDirectoryTest() {
List classPathElements = Arrays.asList(ResourceHelper.getClassPathElements());
Optional testFolder =
classPathElements.stream().filter(elem -> elem.contains("test-classes")).findFirst();
- assertThat(testFolder.isPresent()).isTrue();
+ assertThat(testFolder).isPresent();
File dir = new File(testFolder.get());
String regex = ".*" + TEST_FILE;
Collection filesFound = getResourcesFromDirectory(dir, Pattern.compile(regex));
- assertThat(filesFound).hasSize(1);
+ assertThat(filesFound).hasSize(2);
assertThat(getResourcesFromDirectory(null, null)).isEmpty();
assertThat(getResourcesFromDirectory(dir, Pattern.compile("noMatch"))).isEmpty();
@@ -108,9 +108,9 @@ public void getClassPathElementsTest() {
public void internalGetResourcesTest() {
List classPathElements = Arrays.asList(ResourceHelper.getClassPathElements());
Optional testFolder = classPathElements.stream().filter(elem -> elem.contains("test-classes")).findFirst();
- assertThat(testFolder.isPresent()).isTrue();
+ assertThat(testFolder).isPresent();
Collection filesFound = internalGetResources(testFolder.get(), Pattern.compile(".*\\.txt$"));
- assertThat(filesFound.size()).isEqualTo(1);
+ assertThat(filesFound).hasSize(2);
assertThat(internalGetResources(filesFound.iterator().next(), Pattern.compile(".*\\.txt$"))).isEmpty();
}
@@ -133,7 +133,7 @@ public void internalGetResourcesNotExisting() {
private void commonVerifyCollectionWithExpectedFile(final Collection toVerify, String expectedFile) {
assertThat(toVerify).isNotNull();
- assertThat(toVerify).hasSize(1)
+ assertThat(toVerify).hasSize(2)
.allMatch(file -> file.exists() && file.getName().equals(expectedFile));
}
diff --git a/drools-util/src/test/resources/subdir/TestFile.txt b/drools-util/src/test/resources/subdir/TestFile.txt
new file mode 100644
index 00000000000..9e95ffa46c8
--- /dev/null
+++ b/drools-util/src/test/resources/subdir/TestFile.txt
@@ -0,0 +1 @@
+// Empty file
\ No newline at end of file
diff --git a/jpmml-migration-recipe/Readme.md b/jpmml-migration-recipe/Readme.md
deleted file mode 100644
index dbf554dcea0..00000000000
--- a/jpmml-migration-recipe/Readme.md
+++ /dev/null
@@ -1,53 +0,0 @@
-JPPML migration recipe
-======================
-
-The jpmml-recipe contains code needed to migrate jpmml from version 1.5.1 to 1.6.4.
-
-The main `JPMMLRecipe` features the OpenRewrite recipe declarative chain-ability to re-use some already existing recipes, so that
-
-1. It invokes `ChangeType` for classes that changed name/package, but kept the same method signature
-2. It invokes `JPMMLCodeRecipe` for more fine-grained manipulation, e.g. removal of `FieldName` usage and replacement of `ScoreDistribution`; this is actually done inside `JPMMLVisitor`
-3. It invokes `RemoveUnusedImports` to remove unused imports
-
-There are three main modification steps:
-
-1. `JPMMLVisitor`
-2. `JPMMLCodeRecipe`
-3. `JPMMLRecipe`
-
-for each of which there is a specific unit test class.
-Testing of `JPMMLVisitor` is focused on very low level LST modification.
-Testing of `JPMMLCodeRecipe` is focused on the overall modifications implemented in this module.
-Testing of `JPMMLRecipe` is focused on the full modifications applied by all the involved recipes. It is at this phase that the final, expected result should be evaluated.
-
-The `CommonTestingUtilities` has been thought to be re-usable by different recipes, even if currently defined in that module
-
-Usage
-=====
-
-To execute `JPMMLRecipe`, simply add the following snippet in the target project's pom
-
-```xml
-
- org.openrewrite.maven
- rewrite-maven-plugin
-
-
- org.kie.openrewrite.recipe.jpmml.JPMMLRecipe
-
-
-
-
- org.kie
- jpmml-migration-recipe
-
-
-
-```
-
-and issue
-
-`mvn rewrite:run`
-
-
-
diff --git a/jpmml-migration-recipe/pom.xml b/jpmml-migration-recipe/pom.xml
deleted file mode 100644
index 7efc9d5232b..00000000000
--- a/jpmml-migration-recipe/pom.xml
+++ /dev/null
@@ -1,200 +0,0 @@
-
-
-
-
- 4.0.0
-
- org.kie
- drools-build-parent
- 999-SNAPSHOT
- ../build-parent/pom.xml
-
-
- jpmml-migration-recipe
-
- Kie :: Jpmml Migration Recipe
- OpenRewrite recipe to migrate JPMML model library from 1.5.1 to 1.6.4
-
-
- org.kie.jpmml.migration.recipe
-
-
-
-
-
- org.openrewrite.recipe
- rewrite-recipe-bom
- 1.19.4
- pom
- import
-
-
- org.jpmml
- pmml-model
- 1.5.1
- test
-
-
-
-
-
-
-
-
- org.openrewrite
- rewrite-java
- compile
-
-
- org.jboss
- jandex
-
-
-
-
-
-
- org.openrewrite
- rewrite-java-11
- runtime
-
-
-
-
- org.openrewrite
- rewrite-maven
- compile
-
-
-
-
- org.openrewrite
- rewrite-yaml
- compile
-
-
-
-
- org.openrewrite
- rewrite-properties
- compile
-
-
-
-
- org.openrewrite
- rewrite-xml
- compile
-
-
-
-
-
- org.slf4j
- slf4j-api
-
-
-
-
- org.openrewrite
- rewrite-test
- test
-
-
- commons-logging
- commons-logging
-
-
-
-
-
- org.jpmml
- pmml-model
- test
-
-
-
- ch.qos.logback
- logback-classic
- test
-
-
-
-
- org.junit.jupiter
- junit-jupiter-api
- test
-
-
- org.junit.jupiter
- junit-jupiter-engine
- test
-
-
-
- org.assertj
- assertj-core
- test
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-surefire-plugin
-
-
- org.junit.jupiter
- junit-jupiter-engine
- ${version.org.junit}
-
-
-
-
-
- org.apache.maven.plugins
- maven-dependency-plugin
-
-
- download_new_pmml
-
- get
-
- validate
-
- org.jpmml
- pmml-model
- 1.6.4
- false
-
-
-
-
-
-
-
-
diff --git a/jpmml-migration-recipe/src/main/java/org/kie/openrewrite/recipe/jpmml/JPMMLCodeRecipe.java b/jpmml-migration-recipe/src/main/java/org/kie/openrewrite/recipe/jpmml/JPMMLCodeRecipe.java
deleted file mode 100644
index e2071a3171e..00000000000
--- a/jpmml-migration-recipe/src/main/java/org/kie/openrewrite/recipe/jpmml/JPMMLCodeRecipe.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/**
- * 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.openrewrite.recipe.jpmml;
-
-import com.fasterxml.jackson.annotation.JsonCreator;
-import com.fasterxml.jackson.annotation.JsonProperty;
-import org.jetbrains.annotations.NotNull;
-import org.openrewrite.ExecutionContext;
-import org.openrewrite.Option;
-import org.openrewrite.Recipe;
-import org.openrewrite.java.JavaVisitor;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class JPMMLCodeRecipe extends Recipe {
-
- private static final Logger logger = LoggerFactory.getLogger(JPMMLCodeRecipe.class);
-
- @Option(displayName = "Old fully-qualified type name",
- description = "Fully-qualified class name of the original instantiated type.",
- example = "org.dmg.pmml.ScoreDistribution")
- @NotNull
- String oldInstantiatedFullyQualifiedTypeName;
-
- @Option(displayName = "New fully-qualified type name",
- description = "Fully-qualified class name of the replacement type. The `OuterClassName$NestedClassName` naming convention should be used for nested classes.",
- example = "org.dmg.pmml.ComplexScoreDistributions")
- @NotNull
- String newInstantiatedFullyQualifiedTypeName;
-
- @JsonCreator
- public JPMMLCodeRecipe(@NotNull @JsonProperty("oldInstantiatedFullyQualifiedTypeName") String oldInstantiatedFullyQualifiedTypeName,
- @NotNull @JsonProperty("newInstantiatedFullyQualifiedTypeName") String newInstantiatedFullyQualifiedTypeName) {
- this.oldInstantiatedFullyQualifiedTypeName = oldInstantiatedFullyQualifiedTypeName;
- this.newInstantiatedFullyQualifiedTypeName = newInstantiatedFullyQualifiedTypeName;
- logger.info("Created new instance... ");
- }
-
-
-
- @Override
- public String getDisplayName() {
- return "JPMML Update Code recipe";
- }
-
- @Override
- public String getDescription() {
- return "Migrate JPMML Code version from 1.5.1 to 1.6.4.";
- }
-
-
-
- @Override
- protected JavaVisitor getVisitor() {
- logger.info("Retrieving new visitor...");
- return new JPMMLVisitor(oldInstantiatedFullyQualifiedTypeName, newInstantiatedFullyQualifiedTypeName);
- }
-
-
-
-}
\ No newline at end of file
diff --git a/jpmml-migration-recipe/src/main/java/org/kie/openrewrite/recipe/jpmml/JPMMLVisitor.java b/jpmml-migration-recipe/src/main/java/org/kie/openrewrite/recipe/jpmml/JPMMLVisitor.java
deleted file mode 100644
index ba8db77801a..00000000000
--- a/jpmml-migration-recipe/src/main/java/org/kie/openrewrite/recipe/jpmml/JPMMLVisitor.java
+++ /dev/null
@@ -1,506 +0,0 @@
-/**
- * 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.openrewrite.recipe.jpmml;
-
-import org.openrewrite.ExecutionContext;
-import org.openrewrite.Tree;
-import org.openrewrite.java.ChangeType;
-import org.openrewrite.java.JavaParser;
-import org.openrewrite.java.JavaTemplate;
-import org.openrewrite.java.JavaVisitor;
-import org.openrewrite.java.tree.*;
-import org.openrewrite.marker.Markers;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.File;
-import java.nio.file.Path;
-import java.util.*;
-
-public class JPMMLVisitor extends JavaVisitor {
-
- public static final String NEW_JPMML_MODEL = "pmml-model-1.6.4.jar";
-
- public static final String NEW_JPMML_MAVEN_PATH = String.format("%1$s%2$s.m2%2$srepository%2$sorg%2$sjpmml%2$spmml-model%2$s1.6.4%2$s%3$s", System.getProperty("user.home"), File.separator, NEW_JPMML_MODEL);
-
- private static final Logger logger = LoggerFactory.getLogger(JPMMLVisitor.class);
- static final String JPMML_MODEL_PACKAGE_BASE = "org.jpmml.model";
- static final String DMG_PMML_MODEL_PACKAGE_BASE = "org.dmg.pmml";
- final JavaType.Class originalInstantiatedType;
- final JavaType targetInstantiatedType;
-
- private static final String FIELD_NAME_FQDN = "org.dmg.pmml.FieldName";
- private static final String MODEL_NAME_FQDN = "org.dmg.pmml.Model";
- private static final String MINING_FUNCTION_NAME_FQDN = "org.dmg.pmml.MiningFunction";
- private static final String MINING_SCHEMA_NAME_FQDN = "org.dmg.pmml.MiningSchema";
-
- private static final String NUMERIC_PREDICTOR_FQDN = "org.dmg.pmml.regression.NumericPredictor";
-
- private static final String CATEGORICAL_PREDICTOR_FQDN = "org.dmg.pmml.regression.CategoricalPredictor";
-
- private static final List GET_NAME_TO_GET_FIELD_CLASSES = Arrays.asList(NUMERIC_PREDICTOR_FQDN,
- CATEGORICAL_PREDICTOR_FQDN);
-
- private static final String DATADICTIONARY_FQDN = "org.dmg.pmml.DataDictionary";
-
- private static final Map REMOVED_LIST_FROM_INSTANTIATION = Map.of(DATADICTIONARY_FQDN,
- new RemovedListTuple("addDataFields", JavaType.buildType("org.dmg.pmml.DataField")));
-
-
- private static final J.Identifier STRING_IDENTIFIER = new J.Identifier(Tree.randomId(), Space.build(" ", Collections.emptyList()), Markers.EMPTY, "String", JavaType.buildType(String.class.getCanonicalName()), null);
-
- private static final J.Identifier PREDICTOR_GET_FIELD_IDENTIFIER = new J.Identifier(Tree.randomId(), Space.EMPTY, Markers.EMPTY, "getField", JavaType.Primitive.String, null);
-
-
- private static final JavaType LIST_JAVA_TYPE = JavaType.buildType(List.class.getCanonicalName());
-
- private static final JavaType.Parameterized LIST_GENERIC_JAVA_TYPE = new JavaType.Parameterized(null, (JavaType.FullyQualified) LIST_JAVA_TYPE, List.of(JavaType.GenericTypeVariable.Primitive.String));
-
- private static final JavaParser NEW_JPMMLMODEL_JAVAPARSER = getNewJPMMLJavaParser();
-
- private final JavaTemplate requireMiningFunctionTemplate = JavaTemplate.builder(this::getCursor,
- "@Override\n" +
- " public MiningFunction requireMiningFunction() {\n" +
- " return null;\n" +
- " }\n")
- .javaParser(() -> NEW_JPMMLMODEL_JAVAPARSER)
- .build();
-
- private final JavaTemplate requireMiningSchemaTemplate = JavaTemplate.builder(this::getCursor,
- "@Override\n" +
- " public MiningSchema requireMiningSchema() {\n" +
- " return null;\n" +
- " }\n")
- .javaParser(() -> NEW_JPMMLMODEL_JAVAPARSER)
- .build();
-
-
- public JPMMLVisitor(String oldInstantiatedFullyQualifiedTypeName, String newInstantiatedFullyQualifiedTypeName) {
- this.originalInstantiatedType = JavaType.ShallowClass.build(oldInstantiatedFullyQualifiedTypeName);
- this.targetInstantiatedType = JavaType.buildType(newInstantiatedFullyQualifiedTypeName);
- }
-
-
- @Override
- public J visitBinary(J.Binary binary, ExecutionContext executionContext) {
- logger.trace("visitBinary {}", binary);
- Expression left = (Expression) super.visitExpression(binary.getLeft(), executionContext);
- Expression right = (Expression) super.visitExpression(binary.getRight(), executionContext);
- binary = binary
- .withLeft(left)
- .withRight(right);
- return super.visitBinary(binary, executionContext);
- }
-
- @Override
- public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext executionContext) {
- if (extendsModel(classDecl)) {
- classDecl = addMissingMethod(classDecl, "requireMiningFunction", requireMiningFunctionTemplate);
- classDecl = addMissingMethod(classDecl, "requireMiningSchema", requireMiningSchemaTemplate);
- }
- return (J.ClassDeclaration) super.visitClassDeclaration(classDecl, executionContext);
- }
-
- @Override
- public J.CompilationUnit visitCompilationUnit(J.CompilationUnit cu, ExecutionContext executionContext) {
- logger.trace("visitCompilationUnit {}", cu);
- String cuName = cu.getSourcePath().toString();
- boolean toMigrate = toMigrate(cu.getImports());
- if (!toMigrate) {
- logger.info("Skipping {}", cuName);
- return cu;
- } else {
- logger.info("Going to migrate {}", cuName);
- }
- try {
- cu = (J.CompilationUnit) super.visitCompilationUnit(cu, executionContext);
- maybeAddImport(targetInstantiatedType.toString());
- maybeAddImport(MINING_FUNCTION_NAME_FQDN);
- maybeAddImport(MINING_SCHEMA_NAME_FQDN);
- maybeRemoveImport(FIELD_NAME_FQDN);
- cu = (J.CompilationUnit) new ChangeType(FIELD_NAME_FQDN, String.class.getCanonicalName(), false)
- .getVisitor()
- .visitCompilationUnit(cu, executionContext);
- return cu;
- } catch (Throwable t) {
- logger.error("Failed to visit {}", cu, t);
- return cu;
- }
- }
-
- @Override
- public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext executionContext) {
- logger.trace("visitMethodInvocation {}", method);
- if (isFieldNameCreate(method)) {
- Expression createArgument = method.getArguments().get(0);
- createArgument = (Expression) super.visit(createArgument, executionContext);
- return createArgument;
- }
- if (useFieldNameGetValue(method)) {
- return method.getSelect();
- }
- if (isFieldNameGetNameToGetFieldMapped(method)) {
- JavaType.Method methodType = method
- .getMethodType()
- .withReturnType(JavaType.Primitive.String);
- return method
- .withName(PREDICTOR_GET_FIELD_IDENTIFIER)
- .withMethodType(methodType);
- }
- if (hasFieldNameParameter(method)) {
- JavaType.Method methodType = method.getMethodType()
- .withParameterTypes(Collections.singletonList(JavaType.Primitive.String));
- return method.withMethodType(methodType);
- }
- return super.visitMethodInvocation(method, executionContext);
- }
-
-
- @Override
- public J visitNewClass(J.NewClass newClass, ExecutionContext executionContext) {
- logger.trace("visitNewClass {}", newClass);
- J toReturn = replaceInstantiation(newClass);
- if (toReturn != newClass) {
- return toReturn;
- } else {
- return super.visitNewClass(newClass, executionContext);
- }
- }
-
- @Override
- public J.VariableDeclarations.NamedVariable visitVariable(J.VariableDeclarations.NamedVariable variable, ExecutionContext executionContext) {
- logger.trace("visitVariable {}", variable);
- if (variable.getType() != null && variable.getType().toString().equals(FIELD_NAME_FQDN)) {
- variable = variable
- .withType(JavaType.Primitive.String)
- .withVariableType(variable.getVariableType().withType(JavaType.Primitive.String));
- }
- return (J.VariableDeclarations.NamedVariable) super.visitVariable(variable, executionContext);
- }
-
- @Override
- public J.VariableDeclarations visitVariableDeclarations(J.VariableDeclarations multiVariable,
- ExecutionContext executionContext) {
- logger.trace("visitVariableDeclarations {}", multiVariable);
- multiVariable = (J.VariableDeclarations) super.visitVariableDeclarations(multiVariable, executionContext);
- if (multiVariable.getTypeAsFullyQualified() != null &&
- multiVariable.getTypeAsFullyQualified().getFullyQualifiedName() != null &&
- multiVariable.getTypeAsFullyQualified().getFullyQualifiedName().equals(FIELD_NAME_FQDN)) {
- multiVariable = multiVariable.withType(JavaType.Primitive.String).withTypeExpression(STRING_IDENTIFIER);
- }
- return multiVariable;
- }
-
- /**
- * Return true if the given J.ClassDeclaration extends it extends org.dmg.pmml.Model
- *
- * @param classDecl
- * @return
- */
- protected boolean extendsModel(J.ClassDeclaration classDecl) {
- return classDecl.getType() != null &&
- classDecl.getType().getSupertype() != null &&
- MODEL_NAME_FQDN.equals(classDecl.getType().getSupertype().getFullyQualifiedName());
- }
-
- /**
- * Return true if the given J.CompilationUnit contains an {@see #FIELD_NAME_FQDN} import,
- * false otherwise
- *
- * @param toCheck
- * @return
- */
- protected boolean hasFieldNameImport(J.CompilationUnit toCheck) {
- return toCheck.getImports().stream().anyMatch(this::isFieldNameImport);
- }
-
- /**
- * Return true if the given J.Import is {@see #FIELD_NAME_FQDN},
- * false otherwise
- *
- * @param toCheck
- * @return
- */
- protected boolean isFieldNameImport(J.Import toCheck) {
- return isSpecificImport(toCheck, FIELD_NAME_FQDN);
- }
-
- /**
- * Return true if the given J.Import is fqdn,
- * false otherwise
- *
- * @param toCheck
- * @return
- */
- protected boolean isSpecificImport(J.Import toCheck, String fqdn) {
- return (toCheck.getQualid().getType() instanceof JavaType.Class) && ((JavaType.Class) toCheck.getQualid().getType()).getFullyQualifiedName().equals(fqdn);
- }
-
- /**
- * Add a J.MethodDeclaration to the given J.ClassDeclaration if the latter does not contain the searchedMethod,
- * otherwise it does nothing
- *
- * @param classDecl
- * @param searchedMethod
- * @param javaTemplate
- * @return
- */
- protected J.ClassDeclaration addMissingMethod(J.ClassDeclaration classDecl, String searchedMethod, JavaTemplate javaTemplate) {
- if (methodExists(classDecl, searchedMethod)) {
- return classDecl;
- }
- classDecl = classDecl.withBody(
- classDecl.getBody().withTemplate(
- javaTemplate,
- classDecl.getBody().getCoordinates().lastStatement()
- ));
- return classDecl;
- }
-
- /**
- * Return true if the given J.ClassDeclaration contains the searchedMethod,
- * false otherwise
- *
- * @param toCheck
- * @param searchedMethod
- * @return
- */
- protected boolean methodExists(J.ClassDeclaration toCheck, String searchedMethod) {
- return toCheck.getBody().getStatements().stream()
- .filter(statement -> statement instanceof J.MethodDeclaration)
- .map(J.MethodDeclaration.class::cast)
- .anyMatch(methodDeclaration -> methodDeclaration.getName().getSimpleName().equals(searchedMethod));
- }
-
- /**
- * @param newClass
- * @return
- */
- protected Expression replaceInstantiation(J.NewClass newClass) {
- logger.trace("replaceInstantiation {}", newClass);
- newClass = replaceOriginalToTargetInstantiation(newClass);
- return replaceInstantiationListRemoved(newClass);
- }
-
- /**
- * Returns a new J.NewClass with the originalInstantiatedType
- * replaced by targetInstantiatedType, if present.
- * Otherwise, returns the original newClass.
- *
- * @param newClass
- * @return
- */
- protected J.NewClass replaceOriginalToTargetInstantiation(J.NewClass newClass) {
- logger.trace("replaceOriginalToTargetInstantiation {}", newClass);
- if (newClass.getType() != null && newClass.getType().toString().equals(originalInstantiatedType.toString())) {
- JavaType.Method updatedMethod = updateMethodToTargetInstantiatedType(newClass.getConstructorType());
- TypeTree typeTree = updateTypeTreeToTargetInstantiatedType(newClass);
- newClass = newClass.withConstructorType(updatedMethod)
- .withClazz(typeTree);
- }
- return newClass;
- }
-
- /**
- * Returns a new J.NewClass with the originalInstantiatedType
- * replaced by targetInstantiatedType, if present.
- * Otherwise, returns the original newClass.
- *
- * @param newClass
- * @return
- */
- protected Expression replaceInstantiationListRemoved(J.NewClass newClass) {
- logger.trace("replaceInstantiationListRemoved {}", newClass);
- Optional optionalRetrieved = getRemovedListTuple(newClass);
- if (optionalRetrieved.isPresent()) {
- RemovedListTuple removedListTuple = optionalRetrieved.get();
- return removedListTuple.getJMethod(newClass);
- } else {
- return newClass;
- }
- }
-
- /**
- * Return Optional<RemovedListTuple> if the given J.NewClass constructor has not the List anymore
- * Optional.empty() otherwise
- *
- * @param toCheck
- * @return
- */
- protected Optional getRemovedListTuple(J.NewClass toCheck) {
- return toCheck.getType() != null &&
- REMOVED_LIST_FROM_INSTANTIATION.containsKey(toCheck.getType().toString()) &&
- toCheck.getArguments() != null &&
- !toCheck.getArguments().isEmpty()
- && (toCheck.getArguments().get(0) instanceof J.Identifier) ? Optional.of(REMOVED_LIST_FROM_INSTANTIATION.get(toCheck.getType().toString())) : Optional.empty();
- }
-
- /**
- * Return true if the given J.MethodInvocation is FieldName.create(...),
- * false otherwise
- *
- * @param toCheck
- * @return
- */
- protected boolean isFieldNameCreate(J.MethodInvocation toCheck) {
- return toCheck.getType() != null && toCheck.getType().toString().equals(FIELD_NAME_FQDN) && toCheck.getName().toString().equals("create");
- }
-
- /**
- * Return true if the given J.MethodInvocation is FieldName.create(...),
- * false otherwise
- *
- * @param toCheck
- * @return
- */
- protected boolean hasFieldNameParameter(J.MethodInvocation toCheck) {
- return toCheck.getMethodType() != null &&
- toCheck.getMethodType().getParameterTypes() != null &&
- toCheck.getMethodType().getParameterTypes().stream().anyMatch(javaType -> javaType != null && javaType.toString().equals(FIELD_NAME_FQDN));
- }
-
- /**
- * Return true if the given J.MethodInvocation is #FieldName(_any_).getName(...),
- * and the modified method is String(_any_).getField(...)
- * false otherwise.
- * Mapped elements are defined in {@link #GET_NAME_TO_GET_FIELD_CLASSES}
- *
- * @param toCheck
- * @return
- */
- protected boolean isFieldNameGetNameToGetFieldMapped(J.MethodInvocation toCheck) {
- return toCheck.getMethodType() != null &&
- toCheck.getMethodType().getDeclaringType() != null &&
- GET_NAME_TO_GET_FIELD_CLASSES.contains(toCheck.getMethodType().getDeclaringType().toString()) &&
- toCheck.getName().toString().equals("getName");
- }
-
-
- /**
- * Return true if the given J.MethodInvocation invokes (_field_).getValue(),
- * false otherwise
- *
- * @param toCheck
- * @return
- */
- protected boolean useFieldNameGetValue(J.MethodInvocation toCheck) {
- return toCheck.getMethodType() != null &&
- toCheck.getMethodType().getDeclaringType() != null &&
- toCheck.getMethodType().getDeclaringType().getFullyQualifiedName() != null &&
- toCheck.getMethodType().getDeclaringType().getFullyQualifiedName().equals(FIELD_NAME_FQDN) && toCheck.getMethodType().getName().equals("getValue");
- }
-
- protected boolean toMigrate(List imports) {
- return imports.stream()
- .anyMatch(anImport -> anImport.getPackageName().startsWith(JPMML_MODEL_PACKAGE_BASE) ||
- anImport.getPackageName().startsWith(DMG_PMML_MODEL_PACKAGE_BASE));
- }
-
- protected JavaType.Method updateMethodToTargetInstantiatedType(JavaType.Method oldMethodType) {
- if (oldMethodType != null) {
- JavaType.Method method = oldMethodType;
- method = method.withDeclaringType((JavaType.FullyQualified) targetInstantiatedType)
- .withReturnType(targetInstantiatedType);
- return method;
- }
- return null;
- }
-
- protected TypeTree updateTypeTreeToTargetInstantiatedType(J.NewClass newClass) {
- return ((J.Identifier) newClass.getClazz())
- .withSimpleName(((JavaType.ShallowClass) targetInstantiatedType).getClassName())
- .withType(targetInstantiatedType);
- }
-
- static class RemovedListTuple {
-
- private final String addMethodName;
-
- private final J.Identifier elementIdentifier;
-
- private final JavaType.Array elementArray;
-
- private final J.Identifier elementToArrayIdentifier;
- private final J.Identifier addMethodIdentifier;
-
- public RemovedListTuple(String addMethodName, JavaType elementJavaType) {
- this.addMethodName = addMethodName;
- elementIdentifier = new J.Identifier(Tree.randomId(), Space.build(" ", Collections.emptyList()), Markers.EMPTY, elementJavaType.toString(), elementJavaType, null);
- elementArray = new JavaType.Array(null, elementJavaType);
- JavaType.Parameterized elementListJavaType = new JavaType.Parameterized(null, (JavaType.FullyQualified) LIST_JAVA_TYPE, List.of(elementJavaType));
- elementToArrayIdentifier = new J.Identifier(Tree.randomId(), Space.EMPTY, Markers.EMPTY, "toArray", elementListJavaType, null);
- addMethodIdentifier = new J.Identifier(Tree.randomId(), Space.EMPTY, Markers.EMPTY, addMethodName, elementListJavaType, null);
- }
-
- public J.MethodInvocation getJMethod(J.NewClass newClass) {
- J.Identifier originalListIdentifier = (J.Identifier) newClass.getArguments().get(0);
- J.Literal literal = new J.Literal(Tree.randomId(), Space.EMPTY, Markers.EMPTY, 0, "0", null, JavaType.Primitive.Int);
- J.ArrayDimension arrayDimension = new J.ArrayDimension(Tree.randomId(), Space.EMPTY, Markers.EMPTY, JRightPadded.build(literal));
- J.NewArray newArray = new J.NewArray(Tree.randomId(), Space.EMPTY, Markers.EMPTY, elementIdentifier, Collections.singletonList(arrayDimension), null, elementArray);
- JavaType.Method methodType = new JavaType.Method(null, 1025, LIST_GENERIC_JAVA_TYPE, "toArray",
- elementArray,
- Collections.singletonList("arg0"),
- Collections.singletonList(elementArray), null, null);
- J.MethodInvocation toArrayInvocation = new J.MethodInvocation(Tree.randomId(), Space.EMPTY, Markers.EMPTY, null, null,
- elementToArrayIdentifier,
- JContainer.build(Collections.emptyList()),
- methodType)
- .withSelect(originalListIdentifier)
- .withArguments(Collections.singletonList(newArray));
- JavaType.Method constructorType = newClass.getConstructorType()
- .withParameterTypes(Collections.emptyList())
- .withParameterNames(Collections.emptyList());
- J.NewClass noArgClass = newClass.withArguments(Collections.emptyList())
- .withConstructorType(constructorType);
-
- JavaType.Method addMethodInvocation = new JavaType.Method(null, 1025,
- (JavaType.FullyQualified) JavaType.buildType(noArgClass.getType().toString()),
- addMethodName,
- JavaType.Primitive.Void,
- Collections.singletonList("toAdd"),
- Collections.singletonList(elementArray), null, null);
-
- return new J.MethodInvocation(Tree.randomId(), Space.EMPTY, Markers.EMPTY, null, null,
- addMethodIdentifier,
- JContainer.build(Collections.emptyList()),
- addMethodInvocation)
- .withSelect(noArgClass)
- .withArguments(Collections.singletonList(toArrayInvocation));
- }
- }
-
- private static JavaParser getNewJPMMLJavaParser() {
- List paths = JavaParser.runtimeClasspath();
- Path newJpmmlModel = getNewJPMMLModelPath();
- paths.add(newJpmmlModel);
- return JavaParser.fromJavaVersion()
- .classpath(paths)
- .logCompilationWarningsAndErrors(true).build();
- }
-
- public static Path getNewJPMMLModelPath() {
- // The new version is expected to have been downloaded by maven plugin at validate phase
- File defaultTarget = new File(NEW_JPMML_MAVEN_PATH);
- if (!defaultTarget.exists()) {
- throw new RuntimeException("Failed to find " + NEW_JPMML_MAVEN_PATH);
- }
- return defaultTarget.toPath();
- }
-
-}
diff --git a/jpmml-migration-recipe/src/main/resources/META-INF/rewrite/rewrite.yml b/jpmml-migration-recipe/src/main/resources/META-INF/rewrite/rewrite.yml
deleted file mode 100644
index 188d842ec0e..00000000000
--- a/jpmml-migration-recipe/src/main/resources/META-INF/rewrite/rewrite.yml
+++ /dev/null
@@ -1,49 +0,0 @@
-#
-# 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.
-#
-
----
-type: specs.openrewrite.org/v1beta/recipe
-name: org.kie.openrewrite.recipe.jpmml.JPMMLRecipe
-recipeList:
- - org.openrewrite.java.ChangeType:
- oldFullyQualifiedTypeName: org.jpmml.model.inlinetable.OutputCell
- newFullyQualifiedTypeName: org.jpmml.model.cells.OutputCell
- ignoreDefinition: true
- - org.openrewrite.java.ChangeType:
- oldFullyQualifiedTypeName: org.jpmml.model.inlinetable.InputCell
- newFullyQualifiedTypeName: org.jpmml.model.cells.InputCell
- ignoreDefinition: true
- - org.kie.openrewrite.recipe.jpmml.JPMMLCodeRecipe:
- oldInstantiatedFullyQualifiedTypeName: org.dmg.pmml.ScoreDistribution
- newInstantiatedFullyQualifiedTypeName: org.dmg.pmml.ComplexScoreDistribution
- - org.openrewrite.maven.ChangePropertyValue:
- key: version.org.jpmml.model
- newValue: 1.6.4
-
-# This creates issue with generic imports like
-#
-# import org.kie.api.event.rule.*;
-# import org.kie.api.event.rule.AgendaGroupPoppedEvent;
-# import org.kie.api.event.rule.AgendaGroupPushedEvent;
-# import org.kie.api.event.rule.RuleFlowGroupActivatedEvent;
-# import org.kie.api.event.rule.RuleFlowGroupDeactivatedEvent;
-#
-# origin: https://github.com/kiegroup/drools/blob/main/drools-core/src/main/java/org/drools/core/event/DefaultAgendaEventListener.java
-#
-# - org.openrewrite.java.RemoveUnusedImports
\ No newline at end of file
diff --git a/jpmml-migration-recipe/src/test/java/org/kie/openrewrite/recipe/jpmml/CommonTestingUtilities.java b/jpmml-migration-recipe/src/test/java/org/kie/openrewrite/recipe/jpmml/CommonTestingUtilities.java
deleted file mode 100644
index 52d7596ae2c..00000000000
--- a/jpmml-migration-recipe/src/test/java/org/kie/openrewrite/recipe/jpmml/CommonTestingUtilities.java
+++ /dev/null
@@ -1,205 +0,0 @@
-/**
- * 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.openrewrite.recipe.jpmml;
-
-import org.openrewrite.ExecutionContext;
-import org.openrewrite.InMemoryExecutionContext;
-import org.openrewrite.java.Java11Parser;
-import org.openrewrite.java.JavaIsoVisitor;
-import org.openrewrite.java.JavaParser;
-import org.openrewrite.java.tree.Expression;
-import org.openrewrite.java.tree.J;
-
-import java.nio.file.Path;
-import java.util.List;
-import java.util.Optional;
-
-public class CommonTestingUtilities {
-
- private static final List paths = JavaParser.runtimeClasspath();
-
- private CommonTestingUtilities() {
- }
-
- public static J.CompilationUnit getCompilationUnitFromClassSource(String classSource) {
- JavaParser parser = Java11Parser.builder()
- .classpath(paths)
- .logCompilationWarningsAndErrors(true)
- .build();
- return parser.parse(classSource).get(0);
- }
-
- public static Optional getBinaryFromClassSource(String classSource,
- String binaryString) {
- J.CompilationUnit compilationUnit = getCompilationUnitFromClassSource(classSource);
- TestingVisitor testingVisitor = new TestingVisitor(J.Binary.class, binaryString);
- testingVisitor.visit(compilationUnit, getExecutionContext(null));
- return (Optional) testingVisitor.getFoundItem();
- }
-
- public static Optional getClassDeclarationFromClassSource(String classSource,
- String className) {
- J.CompilationUnit compilationUnit = getCompilationUnitFromClassSource(classSource);
- TestingVisitor testingVisitor = new TestingVisitor(J.ClassDeclaration.class, className);
- testingVisitor.visit(compilationUnit, getExecutionContext(null));
- return (Optional) testingVisitor.getFoundItem();
- }
-
- public static Optional getClassDeclarationFromCompilationUnit(J.CompilationUnit compilationUnit,
- String className) {
- TestingVisitor testingVisitor = new TestingVisitor(J.ClassDeclaration.class, className);
- testingVisitor.visit(compilationUnit, getExecutionContext(null));
- return (Optional) testingVisitor.getFoundItem();
- }
-
- public static Optional getMethodInvocationFromClassSource(String classSource,
- String methodInvocation) {
- J.CompilationUnit compilationUnit = getCompilationUnitFromClassSource(classSource);
- TestingVisitor testingVisitor = new TestingVisitor(J.MethodInvocation.class, methodInvocation);
- testingVisitor.visit(compilationUnit, getExecutionContext(null));
- return (Optional) testingVisitor.getFoundItem();
- }
-
- public static Optional getNewClassFromClassSource(String classSource,
- String fqdnInstantiatedClass) {
- J.CompilationUnit compilationUnit = getCompilationUnitFromClassSource(classSource);
- TestingVisitor testingVisitor = new TestingVisitor(J.NewClass.class, fqdnInstantiatedClass);
- testingVisitor.visit(compilationUnit, getExecutionContext(null));
- return (Optional) testingVisitor.getFoundItem();
- }
-
- public static Optional getVariableDeclarationsFromClassSource(String classSource,
- String variableDeclaration) {
- J.CompilationUnit compilationUnit = getCompilationUnitFromClassSource(classSource);
- TestingVisitor testingVisitor = new TestingVisitor(J.VariableDeclarations.class, variableDeclaration);
- testingVisitor.visit(compilationUnit, getExecutionContext(null));
- return (Optional) testingVisitor.getFoundItem();
- }
-
- public static Optional getExpressionFromClassSource(String classSource, String expression) {
- J.CompilationUnit compilationUnit = getCompilationUnitFromClassSource(classSource);
- TestingVisitor testingVisitor = new TestingVisitor(Expression.class, expression);
- testingVisitor.visit(compilationUnit, getExecutionContext(null));
- return (Optional) testingVisitor.getFoundItem();
- }
-
- public static Optional getExpressionFromCompilationUnit(J.CompilationUnit compilationUnit, String expression) {
- TestingVisitor testingVisitor = new TestingVisitor(Expression.class, expression);
- testingVisitor.visit(compilationUnit, getExecutionContext(null));
- return (Optional) testingVisitor.getFoundItem();
- }
-
- public static List getImportsFromClassSource(String classSource) {
- J.CompilationUnit compilationUnit = getCompilationUnitFromClassSource(classSource);
- return compilationUnit.getImports();
- }
-
-
- public static ExecutionContext getExecutionContext(Throwable expected) {
- return new InMemoryExecutionContext(throwable -> org.assertj.core.api.Assertions.assertThat(throwable).isEqualTo(expected));
- }
-
- private static class TestingVisitor extends JavaIsoVisitor {
-
- private final Class extends J> SEARCHED_J;
- private final String SEARCHED_STRING;
-
- private Optional extends J> foundItem;
-
- public TestingVisitor(Class extends J> SEARCHED_J, String SEARCHED_STRING) {
- this.SEARCHED_J = SEARCHED_J;
- this.SEARCHED_STRING = SEARCHED_STRING;
- foundItem = Optional.empty();
- }
-
- public Optional extends J> getFoundItem() {
- return foundItem;
- }
-
- @Override
- public J.Binary visitBinary(J.Binary binary, ExecutionContext executionContext) {
- if (SEARCHED_J.equals(J.Binary.class) && binary.toString().equals(SEARCHED_STRING)) {
- foundItem = Optional.of(binary);
- return binary;
- } else {
- return super.visitBinary(binary, executionContext);
- }
- }
-
- @Override
- public J.CompilationUnit visitCompilationUnit(J.CompilationUnit cu, ExecutionContext executionContext) {
- if (SEARCHED_J.equals(J.CompilationUnit.class)) {
- foundItem = Optional.of(cu);
- return cu;
- } else {
- return super.visitCompilationUnit(cu, executionContext);
- }
- }
-
- @Override
- public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext executionContext) {
- if (SEARCHED_J.equals(J.ClassDeclaration.class) && classDecl.getSimpleName().equals(SEARCHED_STRING)) {
- foundItem = Optional.of(classDecl);
- return classDecl;
- } else {
- return super.visitClassDeclaration(classDecl, executionContext);
- }
- }
-
- @Override
- public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext executionContext) {
- if (SEARCHED_J.equals(J.MethodInvocation.class) && method.toString().startsWith(SEARCHED_STRING + "(")) {
- foundItem = Optional.of(method);
- return method;
- } else {
- return super.visitMethodInvocation(method, executionContext);
- }
- }
-
- @Override
- public J.NewClass visitNewClass(J.NewClass newClass, ExecutionContext executionContext) {
- if (SEARCHED_J.equals(J.NewClass.class) && newClass.getType().toString().equals(SEARCHED_STRING)) {
- foundItem = Optional.of(newClass);
- return newClass;
- } else {
- return super.visitNewClass(newClass, executionContext);
- }
- }
-
- @Override
- public J.VariableDeclarations visitVariableDeclarations(J.VariableDeclarations multiVariable, ExecutionContext executionContext) {
- if (SEARCHED_J.equals(J.VariableDeclarations.class) && multiVariable.toString().startsWith(SEARCHED_STRING)) {
- foundItem = Optional.of(multiVariable);
- return multiVariable;
- } else {
- return super.visitVariableDeclarations(multiVariable, executionContext);
- }
- }
-
- @Override
- public Expression visitExpression(Expression expression, ExecutionContext executionContext) {
- if (SEARCHED_J.equals(Expression.class) && expression.toString().equals(SEARCHED_STRING)) {
- foundItem = Optional.of(expression);
- return expression;
- } else {
- return super.visitExpression(expression, executionContext);
- }
- }
- }
-}
diff --git a/jpmml-migration-recipe/src/test/java/org/kie/openrewrite/recipe/jpmml/JPMMLCodeRecipeTest.java b/jpmml-migration-recipe/src/test/java/org/kie/openrewrite/recipe/jpmml/JPMMLCodeRecipeTest.java
deleted file mode 100644
index ea72a3e8c68..00000000000
--- a/jpmml-migration-recipe/src/test/java/org/kie/openrewrite/recipe/jpmml/JPMMLCodeRecipeTest.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/**
- * 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.openrewrite.recipe.jpmml;
-
-import org.intellij.lang.annotations.Language;
-import org.junit.jupiter.api.Test;
-import org.openrewrite.java.Assertions;
-import org.openrewrite.java.Java11Parser;
-import org.openrewrite.java.JavaParser;
-import org.openrewrite.test.RecipeSpec;
-import org.openrewrite.test.RewriteTest;
-
-import java.nio.file.Path;
-import java.util.List;
-
-class JPMMLCodeRecipeTest implements RewriteTest {
-
- @Override
- public void defaults(RecipeSpec spec) {
- List paths = JavaParser.runtimeClasspath();
- spec.recipe(new JPMMLCodeRecipe("org.dmg.pmml.ScoreDistribution",
- "org.dmg.pmml.ComplexScoreDistribution"));
- spec.parser(Java11Parser.builder()
- .classpath(paths)
- .logCompilationWarningsAndErrors(true));
- }
-
- @Test
- void removeFieldNameCreate() {
- @Language("java")
- String before = "package com.yourorg;\n" +
- "import org.dmg.pmml.FieldName;\n" +
- "class FooBar {\n" +
- "static void method() {\n" +
- "System.out.println(FieldName.create(\"OUTPUT_\"));\n" +
- "}\n" +
- "}";
- @Language("java")
- String after = "package com.yourorg;\n" +
- "class FooBar {\n" +
- "static void method() {\n" +
- "System.out.println(\"OUTPUT_\");\n" +
- "}\n" +
- "}";
- rewriteRun(
- Assertions.java(before, after)
- );
- }
-
- @Test
- public void changeInstantiation_ScoreDistribution() {
- @Language("java")
- String before = "package com.yourorg;\n" +
- "import org.dmg.pmml.ScoreDistribution;\n" +
- "class FooBar {\n" +
- "static void method() {\n" +
- "ScoreDistribution toReturn = new ScoreDistribution();\n" +
- "}\n" +
- "}";
- @Language("java")
- String after = "package com.yourorg;\n" +
- "import org.dmg.pmml.ComplexScoreDistribution;\n" +
- "import org.dmg.pmml.ScoreDistribution;\n" +
- "\n" +
- "class FooBar {\n" +
- "static void method() {\n" +
- "ScoreDistribution toReturn = new ComplexScoreDistribution();\n" +
- "}\n" +
- "}";
- rewriteRun(
- Assertions.java(before, after)
- );
- }
-
- @Test
- public void changeInstantiation_DataDictionary() {
- @Language("java")
- String before = "package com.yourorg;\n" +
- "import java.util.List;\n" +
- "import org.dmg.pmml.DataDictionary;\n" +
- "import org.dmg.pmml.DataField;\n" +
- "class FooBar {\n" +
- "static void method(List dataFields) {\n" +
- "DataDictionary dataDictionary = new DataDictionary(dataFields);\n" +
- "}\n" +
- "}";
- @Language("java")
- String after = "package com.yourorg;\n" +
- "import java.util.List;\n" +
- "import org.dmg.pmml.DataDictionary;\n" +
- "import org.dmg.pmml.DataField;\n" +
- "class FooBar {\n" +
- "static void method(List dataFields) {\n" +
- "DataDictionary dataDictionary = new DataDictionary().addDataFields(dataFields.toArray(new org.dmg.pmml.DataField[0]));\n" +
- "}\n" +
- "}";
- rewriteRun(
- Assertions.java(before, after)
- );
- }
-
- @Test
- public void changeUsage_FieldNameCreateWithBinary() {
- @Language("java")
- String before = "package com.yourorg;\n" +
- "\n" +
- "import org.dmg.pmml.DataField;\n" +
- "import org.dmg.pmml.FieldName;\n" +
- "\n" +
- "public class Stub {\n" +
- " \n" +
- " public void hello(DataField dataField) {\n" +
- " System.out.println(FieldName.create(\"OUTPUT_\" + dataField.getName().getValue()));\n" +
- " }\n" +
- "\n" +
- "}";
- @Language("java")
- String after = "package com.yourorg;\n" +
- "\n" +
- "import org.dmg.pmml.DataField;\n" +
- "\n" +
- "public class Stub {\n" +
- " \n" +
- " public void hello(DataField dataField) {\n" +
- " System.out.println(\"OUTPUT_\" +dataField.getName());\n" +
- " }\n" +
- "\n" +
- "}";
- rewriteRun(
- Assertions.java(before, after)
- );
- }
-
-}
\ No newline at end of file
diff --git a/jpmml-migration-recipe/src/test/java/org/kie/openrewrite/recipe/jpmml/JPMMLRecipeTest.java b/jpmml-migration-recipe/src/test/java/org/kie/openrewrite/recipe/jpmml/JPMMLRecipeTest.java
deleted file mode 100644
index f8ea02630d1..00000000000
--- a/jpmml-migration-recipe/src/test/java/org/kie/openrewrite/recipe/jpmml/JPMMLRecipeTest.java
+++ /dev/null
@@ -1,424 +0,0 @@
-/**
- * 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.openrewrite.recipe.jpmml;
-
-import org.intellij.lang.annotations.Language;
-import org.junit.jupiter.api.Test;
-import org.openrewrite.java.Assertions;
-import org.openrewrite.java.Java11Parser;
-import org.openrewrite.java.JavaParser;
-import org.openrewrite.test.RecipeSpec;
-import org.openrewrite.test.RewriteTest;
-
-import java.io.InputStream;
-import java.nio.file.Path;
-import java.util.List;
-
-import static org.kie.openrewrite.recipe.jpmml.JPMMLVisitor.getNewJPMMLModelPath;
-
-
-public class JPMMLRecipeTest implements RewriteTest {
-
- private static final String JPMML_RECIPE_NAME = "org.kie.openrewrite.recipe.jpmml.JPMMLRecipe";
-
- @Override
- public void defaults(RecipeSpec spec) {
- List paths = JavaParser.runtimeClasspath();
- Path newJpmmlModel = getNewJPMMLModelPath();
- paths.add(newJpmmlModel);
- try (InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("META-INF/rewrite/rewrite.yml")) {
- assert inputStream != null;
- spec.recipe(inputStream, JPMML_RECIPE_NAME);
- spec.parser(Java11Parser.builder()
- .classpath(paths)
- .logCompilationWarningsAndErrors(true)
- );
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- @Test
- public void changeInstantiation_DataDictionary() {
- @Language("java")
- String before = "package com.yourorg;\n" +
- "\n" +
- "import java.util.List;\n" +
- "import org.dmg.pmml.DataDictionary;\n" +
- "import org.dmg.pmml.DataField;\n" +
- "\n" +
- "public class Stub {\n" +
- "\n" +
- " public String hello(List dataFields) {\n" +
- " new DataDictionary(dataFields);\n" +
- " return \"Hello from com.yourorg.FooLol!\";\n" +
- " }\n" +
- "\n" +
- "}";
- @Language("java")
- String after = "package com.yourorg;\n" +
- "\n" +
- "import java.util.List;\n" +
- "import org.dmg.pmml.DataDictionary;\n" +
- "import org.dmg.pmml.DataField;\n" +
- "\n" +
- "public class Stub {\n" +
- "\n" +
- " public String hello(List dataFields) {\n" +
- " new DataDictionary().addDataFields(dataFields.toArray(new org.dmg.pmml.DataField[0]));\n" +
- " return \"Hello from com.yourorg.FooLol!\";\n" +
- " }\n" +
- "\n" +
- "}";
- rewriteRun(
- Assertions.java(before, after)
- );
- }
-
- @Test
- public void addMissingMethods_Model() {
- @Language("java")
- String before = "package com.yourorg;\n" +
- "\n" +
- "import org.dmg.pmml.LocalTransformations;\n" +
- "import org.dmg.pmml.MathContext;\n" +
- "import org.dmg.pmml.MiningFunction;\n" +
- "import org.dmg.pmml.MiningSchema;\n" +
- "import org.dmg.pmml.Model;\n" +
- "import org.dmg.pmml.Visitor;\n" +
- "import org.dmg.pmml.VisitorAction;\n" +
- "\n" +
- "public class SubModel extends Model {\n" +
- " @Override\n" +
- " public String getModelName() {\n" +
- " return null;\n" +
- " }\n" +
- "\n" +
- " @Override\n" +
- " public Model setModelName(String modelName) {\n" +
- " return null;\n" +
- " }\n" +
- "\n" +
- " @Override\n" +
- " public MiningFunction getMiningFunction() {\n" +
- " return null;\n" +
- " }\n" +
- "\n" +
- " @Override\n" +
- " public Model setMiningFunction(MiningFunction miningFunction) {\n" +
- " return null;\n" +
- " }\n" +
- "\n" +
- " @Override\n" +
- " public String getAlgorithmName() {\n" +
- " return null;\n" +
- " }\n" +
- "\n" +
- " @Override\n" +
- " public Model setAlgorithmName(String algorithmName) {\n" +
- " return null;\n" +
- " }\n" +
- "\n" +
- " @Override\n" +
- " public boolean isScorable() {\n" +
- " return false;\n" +
- " }\n" +
- "\n" +
- " @Override\n" +
- " public Model setScorable(Boolean scorable) {\n" +
- " return null;\n" +
- " }\n" +
- "\n" +
- " @Override\n" +
- " public MathContext getMathContext() {\n" +
- " return null;\n" +
- " }\n" +
- "\n" +
- " @Override\n" +
- " public Model setMathContext(MathContext mathContext) {\n" +
- " return null;\n" +
- " }\n" +
- "\n" +
- " @Override\n" +
- " public MiningSchema getMiningSchema() {\n" +
- " return null;\n" +
- " }\n" +
- "\n" +
- " @Override\n" +
- " public Model setMiningSchema(MiningSchema miningSchema) {\n" +
- " return null;\n" +
- " }\n" +
- "\n" +
- " @Override\n" +
- " public LocalTransformations getLocalTransformations() {\n" +
- " return null;\n" +
- " }\n" +
- "\n" +
- " @Override\n" +
- " public Model setLocalTransformations(LocalTransformations localTransformations) {\n" +
- " return null;\n" +
- " }\n" +
- "\n" +
- " @Override\n" +
- " public VisitorAction accept(Visitor visitor) {\n" +
- " return null;\n" +
- " }\n" +
- "}\n";
- @Language("java")
- String after = "package com.yourorg;\n" +
- "\n" +
- "import org.dmg.pmml.LocalTransformations;\n" +
- "import org.dmg.pmml.MathContext;\n" +
- "import org.dmg.pmml.MiningFunction;\n" +
- "import org.dmg.pmml.MiningSchema;\n" +
- "import org.dmg.pmml.Model;\n" +
- "import org.dmg.pmml.Visitor;\n" +
- "import org.dmg.pmml.VisitorAction;\n" +
- "\n" +
- "public class SubModel extends Model {\n" +
- " @Override\n" +
- " public String getModelName() {\n" +
- " return null;\n" +
- " }\n" +
- "\n" +
- " @Override\n" +
- " public Model setModelName(String modelName) {\n" +
- " return null;\n" +
- " }\n" +
- "\n" +
- " @Override\n" +
- " public MiningFunction getMiningFunction() {\n" +
- " return null;\n" +
- " }\n" +
- "\n" +
- " @Override\n" +
- " public Model setMiningFunction(MiningFunction miningFunction) {\n" +
- " return null;\n" +
- " }\n" +
- "\n" +
- " @Override\n" +
- " public String getAlgorithmName() {\n" +
- " return null;\n" +
- " }\n" +
- "\n" +
- " @Override\n" +
- " public Model setAlgorithmName(String algorithmName) {\n" +
- " return null;\n" +
- " }\n" +
- "\n" +
- " @Override\n" +
- " public boolean isScorable() {\n" +
- " return false;\n" +
- " }\n" +
- "\n" +
- " @Override\n" +
- " public Model setScorable(Boolean scorable) {\n" +
- " return null;\n" +
- " }\n" +
- "\n" +
- " @Override\n" +
- " public MathContext getMathContext() {\n" +
- " return null;\n" +
- " }\n" +
- "\n" +
- " @Override\n" +
- " public Model setMathContext(MathContext mathContext) {\n" +
- " return null;\n" +
- " }\n" +
- "\n" +
- " @Override\n" +
- " public MiningSchema getMiningSchema() {\n" +
- " return null;\n" +
- " }\n" +
- "\n" +
- " @Override\n" +
- " public Model setMiningSchema(MiningSchema miningSchema) {\n" +
- " return null;\n" +
- " }\n" +
- "\n" +
- " @Override\n" +
- " public LocalTransformations getLocalTransformations() {\n" +
- " return null;\n" +
- " }\n" +
- "\n" +
- " @Override\n" +
- " public Model setLocalTransformations(LocalTransformations localTransformations) {\n" +
- " return null;\n" +
- " }\n" +
- "\n" +
- " @Override\n" +
- " public VisitorAction accept(Visitor visitor) {\n" +
- " return null;\n" +
- " }\n" +
- "\n" +
- " @Override\n" +
- " public MiningFunction requireMiningFunction() {\n" +
- " return null;\n" +
- " }\n" +
- "\n" +
- " @Override\n" +
- " public MiningSchema requireMiningSchema() {\n" +
- " return null;\n" +
- " }\n" +
- "}\n";
- rewriteRun(
- Assertions.java(before, after)
- );
- }
-
- @Test
- public void changeImports() {
- @Language("java")
- String before = "package com.yourorg;\n" +
- "import org.jpmml.model.inlinetable.InputCell;\n" +
- "class FooBar {\n" +
- "static public void method() {\n" +
- "InputCell input = null;\n" +
- "}\n" +
- "}";
- @Language("java")
- String after = "package com.yourorg;\n" +
- "\n" +
- "import org.jpmml.model.cells.InputCell;\n" +
- "\n" +
- "class FooBar {\n" +
- "static public void method() {\n" +
- "InputCell input = null;\n" +
- "}\n" +
- "}";
- rewriteRun(
- Assertions.java(before, after)
- );
- }
-
- @Test
- public void changeFieldNameVariableDeclaration() {
- @Language("java")
- String before = "package com.yourorg;\n" +
- "import org.dmg.pmml.FieldName;\n" +
- "class FooBar {\n" +
- "static public void method() {\n" +
- "FieldName fieldName = FieldName.create(\"OUTPUT_\");\n" +
- "}\n" +
- "}";
- @Language("java")
- String after = "package com.yourorg;\n" +
- "class FooBar {\n" +
- "static public void method() {\n" +
- " String fieldName =\"OUTPUT_\";\n" +
- "}\n" +
- "}";
- rewriteRun(
- Assertions.java(before, after)
- );
- }
-
- @Test
- public void changeFieldNameVariableNull() {
- @Language("java")
- String before = "package com.yourorg;\n" +
- "import org.dmg.pmml.FieldName;\n" +
- "class FooBar {\n" +
- "static public void method() {\n" +
- "FieldName fieldName = null;\n" +
- "}\n" +
- "}";
- @Language("java")
- String after = "package com.yourorg;\n" +
- "class FooBar {\n" +
- "static public void method() {\n" +
- " String fieldName = null;\n" +
- "}\n" +
- "}";
- rewriteRun(
- Assertions.java(before, after)
- );
- }
-
- @Test
- public void removeFieldNameCreate() {
- @Language("java")
- String before = "package com.yourorg;\n" +
- "import org.dmg.pmml.FieldName;\n" +
- "class FooBar {\n" +
- "static public void method() {\n" +
- "System.out.println(FieldName.create(\"OUTPUT_\"));\n" +
- "}\n" +
- "}";
- @Language("java")
- String after = "package com.yourorg;\n" +
- "class FooBar {\n" +
- "static public void method() {\n" +
- "System.out.println(\"OUTPUT_\");\n" +
- "}\n" +
- "}";
- rewriteRun(
- Assertions.java(before, after)
- );
- }
-
- @Test
- public void removeFieldNameGetValue() {
- @Language("java")
- String before = "package com.yourorg;\n" +
- "import org.dmg.pmml.OutputField;\n" +
- "class FooBar {\n" +
- "static public void method(OutputField toConvert) {\n" +
- "final String name = toConvert.getName() != null ? toConvert.getName().getValue() : null;\n" +
- "}\n" +
- "}";
- String after = "package com.yourorg;\n" +
- "import org.dmg.pmml.OutputField;\n" +
- "class FooBar {\n" +
- "static public void method(OutputField toConvert) {\n" +
- "final String name = toConvert.getName() != null ?toConvert.getName() : null;\n" +
- "}\n" +
- "}";
- rewriteRun(
- Assertions.java(before, after)
- );
- }
-
-
- @Test
- public void changeInstantiation_ScoreDistribution() {
- @Language("java")
- String before = "package com.yourorg;\n" +
- "import org.dmg.pmml.ScoreDistribution;\n" +
- "class FooBar {\n" +
- "static public void method() {\n" +
- "ScoreDistribution toReturn = new ScoreDistribution();\n" +
- "}\n" +
- "}";
- @Language("java")
- String after = "package com.yourorg;\n" +
- "import org.dmg.pmml.ComplexScoreDistribution;\n" +
- "import org.dmg.pmml.ScoreDistribution;\n" +
- "\n" +
- "class FooBar {\n" +
- "static public void method() {\n" +
- "ScoreDistribution toReturn = new ComplexScoreDistribution();\n" +
- "}\n" +
- "}";
- rewriteRun(
- Assertions.java(before, after)
- );
- }
-
-}
\ No newline at end of file
diff --git a/jpmml-migration-recipe/src/test/java/org/kie/openrewrite/recipe/jpmml/JPMMLVisitorTest.java b/jpmml-migration-recipe/src/test/java/org/kie/openrewrite/recipe/jpmml/JPMMLVisitorTest.java
deleted file mode 100644
index 8fd003771c7..00000000000
--- a/jpmml-migration-recipe/src/test/java/org/kie/openrewrite/recipe/jpmml/JPMMLVisitorTest.java
+++ /dev/null
@@ -1,1148 +0,0 @@
-/**
- * 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.openrewrite.recipe.jpmml;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.openrewrite.Cursor;
-import org.openrewrite.ExecutionContext;
-import org.openrewrite.java.JavaTemplate;
-import org.openrewrite.java.tree.Expression;
-import org.openrewrite.java.tree.J;
-import org.openrewrite.java.tree.JavaType;
-import org.openrewrite.java.tree.TypeTree;
-
-import java.util.Collections;
-import java.util.List;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.kie.openrewrite.recipe.jpmml.CommonTestingUtilities.*;
-
-class JPMMLVisitorTest {
-
- private JPMMLVisitor jpmmlVisitor;
-
- @BeforeEach
- public void init() {
- jpmmlVisitor = new JPMMLVisitor("org.dmg.pmml.ScoreDistribution", "org.dmg.pmml.ComplexScoreDistribution");
- }
-
- @Test
- public void visitBinary_StringFieldNameGetValue() {
- String classTested = "package com.yourorg;\n" +
- "\n" +
- "import org.dmg.pmml.FieldName;\n" +
- "import org.dmg.pmml.DataField;\n" +
- "\n" +
- "class Stub {\n" +
- " public void hello(DataField dataField) {\n" +
- " FieldName.create(\"DER_\" + dataField.getName().getValue());\n" +
- " }\n" +
- "}";
- String binary = "\"DER_\" + dataField.getName().getValue()";
- J.Binary toTest = getBinaryFromClassSource(classTested, binary)
- .orElseThrow(() -> new RuntimeException("Failed to find J.Binary " + binary));
- J retrieved = jpmmlVisitor.visitBinary(toTest, getExecutionContext(null));
- String expected = "\"DER_\" +dataField.getName()";
- assertThat(retrieved)
- .isNotNull()
- .isInstanceOf(J.Binary.class)
- .hasToString(expected);
- }
-
- @Test
- public void visitBinary_FieldNameGetValueString() {
- String classTested = "package com.yourorg;\n" +
- "\n" +
- "import org.dmg.pmml.FieldName;\n" +
- "import org.dmg.pmml.DataField;\n" +
- "\n" +
- "class Stub {\n" +
- " public void hello(DataField dataField) {\n" +
- " FieldName.create(dataField.getName().getValue() + \"DER_\");\n" +
- " }\n" +
- "}";
- String binary = "dataField.getName().getValue() + \"DER_\"";
- J.Binary toTest = getBinaryFromClassSource(classTested, binary)
- .orElseThrow(() -> new RuntimeException("Failed to find J.Binary " + binary));
- J retrieved = jpmmlVisitor.visitBinary(toTest, getExecutionContext(null));
- String expected = "dataField.getName() + \"DER_\"";
- assertThat(retrieved)
- .isNotNull()
- .isInstanceOf(J.Binary.class)
- .hasToString(expected);
- }
-
- @Test
- public void visitBinary_FieldNameGetValueFieldNameGetValue() {
- String classTested = "package com.yourorg;\n" +
- "\n" +
- "import org.dmg.pmml.FieldName;\n" +
- "import org.dmg.pmml.DataField;\n" +
- "\n" +
- "class Stub {\n" +
- " public void hello(DataField dataField) {\n" +
- " FieldName.create(dataField.getName().getValue() + dataField.getName().getValue());\n" +
- " }\n" +
- "}";
- String binary = "dataField.getName().getValue() + dataField.getName().getValue()";
- J.Binary toTest = getBinaryFromClassSource(classTested, binary)
- .orElseThrow(() -> new RuntimeException("Failed to find J.Binary " + binary));
- J retrieved = jpmmlVisitor.visitBinary(toTest, getExecutionContext(null));
- String expected = "dataField.getName() +dataField.getName()";
- assertThat(retrieved)
- .isNotNull()
- .isInstanceOf(J.Binary.class)
- .hasToString(expected);
- }
-
- @Test
- public void visitMethodInvocation_NumericPredictorGetName() {
- String classTested = "package com.yourorg;\n" +
- "\n" +
- "import org.dmg.pmml.FieldName;\n" +
- "import org.dmg.pmml.regression.NumericPredictor;\n" +
- "\n" +
- "class Stub {\n" +
- " public String bye(NumericPredictor numericPredictor) {\n" +
- " FieldName fieldName = numericPredictor.getName();\n" +
- " return fieldName.getValue();\n" +
- " }" +
- "}";
- String methodTested = "numericPredictor.getName";
- J.MethodInvocation toTest = getMethodInvocationFromClassSource(classTested, methodTested)
- .orElseThrow(() -> new RuntimeException("Failed to find J.MethodInvocation numericPredictor.getName()"));
- assertThat(toTest).isNotNull();
- ExecutionContext executionContext = getExecutionContext(null);
- J retrieved = jpmmlVisitor.visitMethodInvocation(toTest, executionContext);
- String expected = "numericPredictor.getField()";
- assertThat(retrieved)
- .isNotNull()
- .isInstanceOf(J.MethodInvocation.class)
- .hasToString(expected);
- }
-
- @Test
- public void visitMethodInvocation_CategoricalPredictorGetName() {
- String classTested = "package com.yourorg;\n" +
- "\n" +
- "import org.dmg.pmml.FieldName;\n" +
- "import org.dmg.pmml.regression.CategoricalPredictor;\n" +
- "\n" +
- "class Stub {\n" +
- " public String bye(CategoricalPredictor categoricalPredictor) {\n" +
- " FieldName fieldName = categoricalPredictor.getName();\n" +
- " return fieldName.getValue();\n" +
- " }" +
- "}";
- String methodTested = "categoricalPredictor.getName";
- J.MethodInvocation toTest = getMethodInvocationFromClassSource(classTested, methodTested)
- .orElseThrow(() -> new RuntimeException("Failed to find J.MethodInvocation categoricalPredictor.getName()"));
- assertThat(toTest).isNotNull();
- ExecutionContext executionContext = getExecutionContext(null);
- J retrieved = jpmmlVisitor.visitMethodInvocation(toTest, executionContext);
- String expected = "categoricalPredictor.getField()";
- assertThat(retrieved)
- .isNotNull()
- .isInstanceOf(J.MethodInvocation.class)
- .hasToString(expected);
- }
-
- @Test
- public void visitMethodInvocation_FieldNameCreate() {
- String classTested = "package com.yourorg;\n" +
- "\n" +
- "import org.dmg.pmml.FieldName;\n" +
- "\n" +
- "class Stub {\n" +
- " public String hello() {\n" +
- " System.out.println(FieldName.create(\"OUTPUT_\"));\n" +
- " return \"Hello from com.yourorg.FooBar!\";\n" +
- " }\n" +
- "}";
- String expressionTested = "FieldName.create";
- J.MethodInvocation toTest = getMethodInvocationFromClassSource(classTested, expressionTested)
- .orElseThrow(() -> new RuntimeException("Failed to find J.MethodInvocation FieldName.create(\"OUTPUT_\")"));
- assertThat(toTest)
- .isNotNull();
- ExecutionContext executionContext = getExecutionContext(null);
- J retrieved = jpmmlVisitor.visitMethodInvocation(toTest, executionContext);
- String expected = "OUTPUT_";
- assertThat(retrieved)
- .isNotNull()
- .isInstanceOf(J.Literal.class);
- assertThat(((J.Literal) retrieved).getValue()).isEqualTo(expected);
- }
-
- @Test
- public void visitMethodInvocation_FieldNameCreateWithBinary() {
- String classTested = "package com.yourorg;\n" +
- "\n" +
- "import org.dmg.pmml.DataField;\n" +
- "import org.dmg.pmml.FieldName;\n" +
- "\n" +
- "class Stub {\n" +
- " public String hello(DataField dataField) {\n" +
- " System.out.println(FieldName.create(\"OUTPUT_\" + dataField.getName().getValue()));\n" +
- " return \"Hello from com.yourorg.FooBar!\";\n" +
- " }\n" +
- "}";
- String expressionTested = "System.out.println";
- J.MethodInvocation toTest = getMethodInvocationFromClassSource(classTested, expressionTested)
- .orElseThrow(() -> new RuntimeException("Failed to find J.MethodInvocation System.out.println(FieldName.create(\"OUTPUT_\" + dataField.getName().getValue()))"));
- assertThat(toTest)
- .isNotNull();
- ExecutionContext executionContext = getExecutionContext(null);
- J retrieved = jpmmlVisitor.visitMethodInvocation(toTest, executionContext);
- String expected = "System.out.println(\"OUTPUT_\" +dataField.getName())";
- assertThat(retrieved)
- .isNotNull()
- .isInstanceOf(J.MethodInvocation.class);
- assertThat(((J.MethodInvocation) retrieved)).hasToString(expected);
- }
-
- @Test
- public void visitMethodInvocation_AccessFieldName() {
- String classTested = "package com.yourorg;\n" +
- "\n" +
- "import org.dmg.pmml.DataType;\n" +
- "import org.dmg.pmml.FieldName;\n" +
- "import org.dmg.pmml.MiningField;\n" +
- "import org.dmg.pmml.mining.MiningModel;\n" +
- "import org.dmg.pmml.OpType;\n" +
- "import org.dmg.pmml.OutputField;\n" +
- "import org.dmg.pmml.Target;\n" +
- "\n" +
- "class Stub {\n" +
- " public String bye() {\n" +
- " MiningField toReturn = new MiningField(FieldName.create(new String(\"TestingFIeld\")));\n" +
- " OutputField toConvert = new OutputField(FieldName.create(\"FIELDNAME\"), OpType.CATEGORICAL," +
- " DataType.BOOLEAN);\n" +
- " final String name = toConvert.getName() != null ? toConvert.getName().getValue() : null;\n" +
- " Target target = new Target();\n" +
- " String field = target.getField().getValue();\n" +
- " String key = target.getKey().getValue();\n" +
- " return name;\n" +
- " }" +
- "}";
- String methodTested = "toConvert.getName().getValue";
- J.MethodInvocation toTest = getMethodInvocationFromClassSource(classTested, methodTested)
- .orElseThrow(() -> new RuntimeException("Failed to find J.MethodInvocation toConvert.getName().getValue"));
- assertThat(toTest).isNotNull();
- ExecutionContext executionContext = getExecutionContext(null);
- J retrieved = jpmmlVisitor.visitMethodInvocation(toTest, executionContext);
- String expected = "toConvert.getName()";
- assertThat(retrieved)
- .isNotNull()
- .isInstanceOf(J.MethodInvocation.class)
- .hasToString(expected);
-
- methodTested = "target.getField().getValue";
- toTest = getMethodInvocationFromClassSource(classTested, methodTested)
- .orElseThrow(() -> new RuntimeException("Failed to find J.MethodInvocation target.getField().getValue"));
- assertThat(toTest).isNotNull();
- retrieved = jpmmlVisitor.visitMethodInvocation(toTest, executionContext);
- expected = "target.getField()";
- assertThat(retrieved)
- .isNotNull()
- .isInstanceOf(J.MethodInvocation.class)
- .hasToString(expected);
-
- methodTested = "target.getKey().getValue";
- toTest = getMethodInvocationFromClassSource(classTested, methodTested)
- .orElseThrow(() -> new RuntimeException("Failed to find J.MethodInvocation target.getKey().getValue"));
- assertThat(toTest).isNotNull();
- retrieved = jpmmlVisitor.visitMethodInvocation(toTest, executionContext);
- expected = "target.getKey()";
- assertThat(retrieved)
- .isNotNull()
- .isInstanceOf(J.MethodInvocation.class)
- .hasToString(expected);
- }
-
- @Test
- public void visitMethodInvocation_FieldNameGetValue() {
- String classTested = "package com.yourorg;\n" +
- "\n" +
- "import java.util.List;\n" +
- "import java.util.Objects;\n" +
- "\n" +
- "import org.dmg.pmml.DataField;\n" +
- "import org.dmg.pmml.Field;\n" +
- "\n" +
- "public class Stub {\n" +
- "\n" +
- " private List> fields;\n" +
- "\n" +
- " public void bye() {\n" +
- " DataField targetDataField = this.fields.stream()\n" +
- " .filter(DataField.class::isInstance)\n" +
- " .map(DataField.class::cast)\n" +
- " .filter(field -> Objects.equals(getTargetFieldName(), field.getName().getValue()))\n" +
- " .findFirst().orElse(null);\n" +
- " }\n" +
- " public String getTargetFieldName() {\n" +
- " return \"targetDataFieldName\";\n" +
- " }\n" +
- "}";
- String expressionTested = "field.getName().getValue";
- J.MethodInvocation toTest = getMethodInvocationFromClassSource(classTested, expressionTested)
- .orElseThrow(() -> new RuntimeException("Failed to find Expression FieldName.create(\"OUTPUT_\")"));
- assertThat(toTest)
- .isNotNull();
- ExecutionContext executionContext = getExecutionContext(null);
- J retrieved = jpmmlVisitor.visitMethodInvocation(toTest, executionContext);
- String expected = "field.getName()";
- assertThat(retrieved)
- .isNotNull()
- .isInstanceOf(J.MethodInvocation.class)
- .hasToString(expected);
- }
-
- @Test
- public void visitMethodInvocation_FieldNameGetNameToGetFieldMapped() {
- String classTested = "package com.yourorg;\n" +
- "\n" +
- "import org.dmg.pmml.FieldName;\n" +
- "import org.dmg.pmml.regression.CategoricalPredictor;\n" +
- "\n" +
- "class Stub {\n" +
- " public String hello(CategoricalPredictor categoricalPredictor) {\n" +
- " FieldName fieldName = categoricalPredictor.getName();\n" +
- " return \"Hello from com.yourorg.FooBar!\";\n" +
- " }\n" +
- "}";
- String methodInvocation = "categoricalPredictor.getName";
- J.MethodInvocation toTest = getMethodInvocationFromClassSource(classTested, methodInvocation)
- .orElseThrow(() -> new RuntimeException("Failed to find J.MethodInvocation categoricalPredictor.getName()"));
- ExecutionContext executionContext = getExecutionContext(null);
- J retrieved = jpmmlVisitor.visitMethodInvocation(toTest, executionContext);
- String expected = "categoricalPredictor.getField()";
- assertThat(retrieved)
- .isNotNull()
- .isInstanceOf(J.MethodInvocation.class)
- .hasToString(expected);
- }
-
- @Test
- public void visitMethodInvocation_HasFieldNameParameter() {
- String classTested = "package com.yourorg;\n" +
- "\n" +
- "import org.dmg.pmml.FieldName;\n" +
- "import org.dmg.pmml.DataField;\n" +
- "import org.dmg.pmml.DerivedField;\n" +
- "import java.util.Objects;\n" +
- "\n" +
- "class Stub {\n" +
- " public void hello(DataField dataField) {\n" +
- " DerivedField toReturn = new DerivedField();\n" +
- " toReturn.setName(FieldName.create(\"DER_\" + dataField.getName().getValue()));\n" +
- " }\n" +
- "}";
- String methodInvocation = "toReturn.setName";
- J.MethodInvocation toTest = getMethodInvocationFromClassSource(classTested, methodInvocation)
- .orElseThrow(() -> new RuntimeException("Failed to toReturn.setName"));
- ExecutionContext executionContext = getExecutionContext(null);
- J retrieved = jpmmlVisitor.visitMethodInvocation(toTest, executionContext);
- assertThat(retrieved)
- .isNotNull()
- .isInstanceOf(J.MethodInvocation.class);
- String expected = "String";
- assertThat(retrieved)
- .isNotNull()
- .isInstanceOf(J.MethodInvocation.class);
- assertThat(((J.MethodInvocation)retrieved).getMethodType().getParameterTypes().get(0))
- .hasToString(expected);
- }
-
- @Test
- public void visitNewClass_FieldNameCreate() {
- String classTested = "package com.yourorg;\n" +
- "\n" +
- "import org.dmg.pmml.FieldName;\n" +
- "import org.dmg.pmml.MiningField;\n" +
- "\n" +
- "public class Stub {\n" +
- "\n" +
- " public String hello() {\n" +
- " MiningField toReturn = new MiningField(FieldName.create(new String(\"TestingField\")));\n" +
- " return \"Hello from com.yourorg.FooLol!\";\n" +
- " }\n" +
- "\n" +
- "}";
- String classInstantiated = "org.dmg.pmml.MiningField";
- J.NewClass toTest = getNewClassFromClassSource(classTested, classInstantiated)
- .orElseThrow(() -> new RuntimeException("Failed to find J.NewClass org.dmg.pmml.MiningField"));
- assertThat(toTest)
- .isNotNull();
- ExecutionContext executionContext = getExecutionContext(null);
- J retrieved = jpmmlVisitor.visitNewClass(toTest, executionContext);
- String expected = "new MiningField(new String(\"TestingField\"))";
- assertThat(retrieved)
- .isNotNull()
- .isInstanceOf(J.NewClass.class)
- .hasToString(expected);
- }
-
- @Test
- public void visitNewClass_AccessFieldNameInsideConstructor() {
- String classTested = "package com.yourorg;\n" +
- "\n" +
- "import org.dmg.pmml.Target;\n" +
- "\n" +
- "class Stub {\n" +
- " public String bye() {\n" +
- " Target target = new Target();\n" +
- " String name = new String(target.getKey().getValue());\n" +
- " return name;\n" +
- " }" +
- "}";
- String classInstantiated = "java.lang.String";
- J.NewClass toTest = getNewClassFromClassSource(classTested, classInstantiated)
- .orElseThrow(() -> new RuntimeException("Failed to find J.NewClass java.lang.String"));
- assertThat(toTest).isNotNull();
- ExecutionContext executionContext = getExecutionContext(null);
- J retrieved = jpmmlVisitor.visitNewClass(toTest, executionContext);
- String expected = "new String(target.getKey())";
- assertThat(retrieved)
- .isNotNull()
- .isInstanceOf(J.NewClass.class)
- .hasToString(expected);
- }
-
- @Test
- public void visitNewClass_ScoreDistribution() {
- String classTested = "package com.yourorg;\n" +
- "\n" +
- "import org.dmg.pmml.ScoreDistribution;\n" +
- "\n" +
- "public class Stub {\n" +
- "\n" +
- " public String hello() {\n" +
- " ScoreDistribution scoreDistribution = new ScoreDistribution();\n" +
- " return \"Hello from com.yourorg.FooLol!\";\n" +
- " }\n" +
- "\n" +
- "}";
- String classInstantiated = "org.dmg.pmml.ScoreDistribution";
- J.NewClass toTest = getNewClassFromClassSource(classTested, classInstantiated)
- .orElseThrow(() -> new RuntimeException("Failed to find J.NewClass org.dmg.pmml.ScoreDistribution"));
- assertThat(toTest)
- .isNotNull();
- ExecutionContext executionContext = getExecutionContext(null);
- J retrieved = jpmmlVisitor.visitNewClass(toTest, executionContext);
- String expected = "new ComplexScoreDistribution()";
- assertThat(retrieved)
- .isNotNull()
- .isInstanceOf(J.NewClass.class)
- .hasToString(expected);
- }
-
- @Test
- public void visitNewClass_DataDictionary() {
- String classTested = "package com.yourorg;\n" +
- "\n" +
- "import java.util.List;\n" +
- "import org.dmg.pmml.DataDictionary;\n" +
- "import org.dmg.pmml.DataField;\n" +
- "\n" +
- "public class Stub {\n" +
- "\n" +
- " public String hello(List dataFields) {\n" +
- " DataDictionary dataDictionary = new DataDictionary(dataFields);\n" +
- " return \"Hello from com.yourorg.FooLol!\";\n" +
- " }\n" +
- "\n" +
- "}";
- String classInstantiated = "org.dmg.pmml.DataDictionary";
- J.NewClass toTest = getNewClassFromClassSource(classTested, classInstantiated)
- .orElseThrow(() -> new RuntimeException("Failed to find J.NewClass org.dmg.pmml.DataDictionary"));
- assertThat(toTest)
- .isNotNull();
- ExecutionContext executionContext = getExecutionContext(null);
- J retrieved = jpmmlVisitor.visitNewClass(toTest, executionContext);
- String expected = "new DataDictionary().addDataFields(dataFields.toArray(new org.dmg.pmml.DataField[0]))";
- assertThat(retrieved)
- .isNotNull()
- .isInstanceOf(J.MethodInvocation.class)
- .hasToString(expected);
- }
-
- @Test
- public void visitVariableDeclarations_AccessFieldNameAsSecondParameter() {
- String classTested = "package com.yourorg;\n" +
- "\n" +
- "import java.util.List;\n" +
- "import java.util.Objects;\n" +
- "\n" +
- "import org.dmg.pmml.DataField;\n" +
- "import org.dmg.pmml.Field;\n" +
- "\n" +
- "public class Stub {\n" +
- "\n" +
- " private List> fields;\n" +
- "\n" +
- " public void bye() {\n" +
- " DataField targetDataField = this.fields.stream()\n" +
- " .filter(DataField.class::isInstance)\n" +
- " .map(DataField.class::cast)\n" +
- " .filter(field -> Objects.equals(getTargetFieldName(), field.getName().getValue()))\n" +
- " .findFirst().orElse(null);\n" +
- " }\n" +
- " public String getTargetFieldName() {\n" +
- " return \"targetDataFieldName\";\n" +
- " }\n" +
- "}";
- String variableDeclaration = "DataField targetDataField = ";
- J.VariableDeclarations toTest = getVariableDeclarationsFromClassSource(classTested, variableDeclaration)
- .orElseThrow(() -> new RuntimeException("Failed to find J.VariableDeclarations DataField targetDataField = "));
- assertThat(toTest).isNotNull();
- ExecutionContext executionContext = getExecutionContext(null);
- J.VariableDeclarations retrieved = jpmmlVisitor.visitVariableDeclarations(toTest, executionContext);
- String expected = "DataField targetDataField = this.fields.stream()\n" +
- " .filter(DataField.class::isInstance)\n" +
- " .map(DataField.class::cast)\n" +
- " .filter(field -> Objects.equals(getTargetFieldName(),field.getName()))\n" +
- " .findFirst().orElse(null)";
- assertThat(retrieved).isNotNull()
- .hasToString(expected);
- }
-
- @Test
- public void visitVariableDeclarations_FieldName() {
- String classTested = "package com.yourorg;\n" +
- "\n" +
- "import org.dmg.pmml.FieldName;\n" +
- "\n" +
- "class Stub {\n" +
- " public String hello() {\n" +
- " FieldName fieldName = FieldName.create(\"OUTPUT_\");\n" +
- " return \"Hello from com.yourorg.FooBar!\";\n" +
- " }\n" +
- "}";
- String variableDeclaration = "FieldName fieldName = FieldName.create(\"OUTPUT_\")";
- J.VariableDeclarations toTest = getVariableDeclarationsFromClassSource(classTested, variableDeclaration)
- .orElseThrow(() -> new RuntimeException("Failed to find J.VariableDeclarations FieldName fieldName = FieldName.create(\"OUTPUT_\")"));
- assertThat(toTest)
- .isNotNull();
- ExecutionContext executionContext = getExecutionContext(null);
- J.VariableDeclarations retrieved = jpmmlVisitor.visitVariableDeclarations(toTest, executionContext);
- String expected = "String fieldName =\"OUTPUT_\"";
- assertThat(retrieved)
- .isNotNull()
- .hasToString(expected);
- }
-
- @Test
- public void visitVariableDeclarations_CategoricalPredictorGetName() {
- String classTested = "package com.yourorg;\n" +
- "\n" +
- "import org.dmg.pmml.FieldName;\n" +
- "import org.dmg.pmml.regression.CategoricalPredictor;\n" +
- "\n" +
- "class Stub {\n" +
- " public String hello(CategoricalPredictor categoricalPredictor) {\n" +
- " FieldName fieldName = categoricalPredictor.getName();\n" +
- " return \"Hello from com.yourorg.FooBar!\";\n" +
- " }\n" +
- "}";
- String variableDeclaration = "FieldName fieldName = categoricalPredictor.getName()";
- J.VariableDeclarations toTest = getVariableDeclarationsFromClassSource(classTested, variableDeclaration)
- .orElseThrow(() -> new RuntimeException("Failed to find J.VariableDeclarations FieldName fieldName = categoricalPredictor.getName()"));
- assertThat(toTest)
- .isNotNull();
- ExecutionContext executionContext = getExecutionContext(null);
- J.VariableDeclarations retrieved = jpmmlVisitor.visitVariableDeclarations(toTest, executionContext);
- String expected = "String fieldName = categoricalPredictor.getField()";
- assertThat(retrieved)
- .isNotNull()
- .hasToString(expected);
- }
-
- @Test
- public void visitVariableDeclarations_NumericPredictorGetName() {
- String classTested = "package com.yourorg;\n" +
- "\n" +
- "import org.dmg.pmml.FieldName;\n" +
- "import org.dmg.pmml.regression.NumericPredictor;\n" +
- "\n" +
- "class Stub {\n" +
- " public String hello(NumericPredictor numericPredictor) {\n" +
- " FieldName fieldName = numericPredictor.getName();\n" +
- " return \"Hello from com.yourorg.FooBar!\";\n" +
- " }\n" +
- "}";
- String variableDeclaration = "FieldName fieldName = numericPredictor.getName()";
- J.VariableDeclarations toTest = getVariableDeclarationsFromClassSource(classTested, variableDeclaration)
- .orElseThrow(() -> new RuntimeException("Failed to find J.VariableDeclarations FieldName fieldName = FieldName.create(\"OUTPUT_\")"));
- assertThat(toTest)
- .isNotNull();
- ExecutionContext executionContext = getExecutionContext(null);
- J.VariableDeclarations retrieved = jpmmlVisitor.visitVariableDeclarations(toTest, executionContext);
- String expected = "String fieldName = numericPredictor.getField()";
- assertThat(retrieved)
- .isNotNull()
- .hasToString(expected);
- }
-
- @Test
- public void hasFieldNameImport_true() {
- String classTested = "package com.yourorg;\n" +
- "import org.dmg.pmml.FieldName;\n" +
- "import java.util.List;\n" +
- "class FooBar {\n" +
- "};";
- J.CompilationUnit toTest = getCompilationUnitFromClassSource(classTested);
- assertThat(jpmmlVisitor.hasFieldNameImport(toTest))
- .isTrue();
- }
-
- @Test
- public void hasFieldNameImport_false() {
- String classTested = "package com.yourorg;\n" +
- "import java.util.List;\n" +
- "import org.dmg.pmml.DataField;\n" +
- "class FooBar {\n" +
- "};";
- J.CompilationUnit toTest = getCompilationUnitFromClassSource(classTested);
- assertThat(jpmmlVisitor.hasFieldNameImport(toTest))
- .isFalse();
- }
-
- @Test
- public void isFieldNameImport_true() {
- String classTested = "package com.yourorg;\n" +
- "import org.dmg.pmml.FieldName;\n" +
- "class FooBar {\n" +
- "};";
- J.Import toTest = getImportsFromClassSource(classTested).get(0);
- assertThat(jpmmlVisitor.isFieldNameImport(toTest))
- .isTrue();
- }
-
- @Test
- public void isFieldNameImport_false() {
- String classTested = "package com.yourorg;\n" +
- "import java.util.List;\n" +
- "class FooBar {\n" +
- "};";
- J.Import toTest = getImportsFromClassSource(classTested).get(0);
- assertThat(jpmmlVisitor.isFieldNameImport(toTest))
- .isFalse();
- }
-
- @Test
- public void addMissingMethod_Add() {
- String classTested = "package com.yourorg;\n" +
- "\n" +
- "\n" +
- "class Stub {\n" +
- " public void hello() {\n" +
- " System.out.println(\"Hello\");\n" +
- " }\n" +
- "}";
- String className = "Stub";
- J.CompilationUnit cu = getCompilationUnitFromClassSource(classTested);
- J.ClassDeclaration toTest = getClassDeclarationFromCompilationUnit(cu, className)
- .orElseThrow(() -> new RuntimeException("Failed to find J.ClassDeclaration Stub"));
- Cursor cursor = new Cursor(jpmmlVisitor.getCursor(), cu);
- JavaTemplate requireMiningSchemaTemplate = JavaTemplate.builder(() -> cursor,
- " public boolean requireMiningSchema() {\n" +
- " return null;\n" +
- " }\n")
- .build();
- J.ClassDeclaration retrieved = jpmmlVisitor.addMissingMethod(toTest, "requireMiningSchema", requireMiningSchemaTemplate);
- assertThat(retrieved)
- .isEqualTo(toTest);
- assertThat(jpmmlVisitor.methodExists(retrieved, "requireMiningSchema"))
- .isTrue();
- }
-
- @Test
- public void addMissingMethod_NotAdd() {
- String classTested = "package com.yourorg;\n" +
- "\n" +
- "\n" +
- "class Stub {\n" +
- " public void hello() {\n" +
- " System.out.println(\"Hello\");\n" +
- " }\n" +
- "}";
- String className = "Stub";
- J.ClassDeclaration toTest = getClassDeclarationFromClassSource(classTested, className)
- .orElseThrow(() -> new RuntimeException("Failed to find J.ClassDeclaration Stub"));
- assertThat(jpmmlVisitor.addMissingMethod(toTest, "hello", null))
- .isEqualTo(toTest);
- }
-
- @Test
- public void methodExists_true() {
- String classTested = "package com.yourorg;\n" +
- "\n" +
- "\n" +
- "class Stub {\n" +
- " public void hello() {\n" +
- " System.out.println(\"Hello\");\n" +
- " }\n" +
- "}";
- String className = "Stub";
- J.ClassDeclaration toTest = getClassDeclarationFromClassSource(classTested, className)
- .orElseThrow(() -> new RuntimeException("Failed to find J.ClassDeclaration Stub"));
- assertThat(jpmmlVisitor.methodExists(toTest, "hello"))
- .isTrue();
- }
-
- @Test
- public void methodExists_false() {
- String classTested = "package com.yourorg;\n" +
- "\n" +
- "\n" +
- "class Stub {\n" +
- " public void hello() {\n" +
- " System.out.println(\"Hello\");\n" +
- " }\n" +
- "}";
- String className = "Stub";
- J.ClassDeclaration toTest = getClassDeclarationFromClassSource(classTested, className)
- .orElseThrow(() -> new RuntimeException("Failed to find J.ClassDeclaration Stub"));
- assertThat(jpmmlVisitor.methodExists(toTest, "notHello"))
- .isFalse();
- }
-
- @Test
- public void replaceOriginalToTargetInstantiation_replaced() {
- String classTested = "package com.yourorg;\n" +
- "\n" +
- "import org.dmg.pmml.ScoreDistribution;\n" +
- "\n" +
- "public class Stub {\n" +
- "\n" +
- " public String hello() {\n" +
- " ScoreDistribution scoreDistribution = new ScoreDistribution();\n" +
- " return \"Hello from com.yourorg.FooLol!\";\n" +
- " }\n" +
- "\n" +
- "}";
- String classInstantiated = "org.dmg.pmml.ScoreDistribution";
- J.NewClass toTest = getNewClassFromClassSource(classTested, classInstantiated)
- .orElseThrow(() -> new RuntimeException("Failed to find J.NewClass org.dmg.pmml.ScoreDistribution"));
- assertThat(toTest)
- .isNotNull();
- J.NewClass retrieved = jpmmlVisitor.replaceOriginalToTargetInstantiation(toTest);
- String expected = "new ComplexScoreDistribution()";
- assertThat(retrieved)
- .isNotNull()
- .isInstanceOf(J.NewClass.class)
- .hasToString(expected);
- }
-
- @Test
- public void replaceOriginalToTargetInstantiation_notReplaced() {
- String classTested = "package com.yourorg;\n" +
- "import org.dmg.pmml.DataField;\n" +
- "class FooBar {\n" +
- "static void method() {\n" +
- " DataField dataField = new DataField();\n" +
- "}\n" +
- "}";
- String instantiatedClass = "org.dmg.pmml.DataField";
- J.NewClass toTest = getNewClassFromClassSource(classTested, instantiatedClass)
- .orElseThrow(() -> new RuntimeException("Failed to find J.NewClass org.dmg.pmml.DataField"));
- assertThat(toTest)
- .isNotNull();
- Expression retrieved = jpmmlVisitor.replaceOriginalToTargetInstantiation(toTest);
- assertThat(retrieved)
- .isNotNull()
- .isEqualTo(toTest);
- }
-
- @Test
- public void replaceInstantiationListRemoved_replaced() {
- String classTested = "package com.yourorg;\n" +
- "import java.util.List;\n" +
- "import org.dmg.pmml.DataDictionary;\n" +
- "import org.dmg.pmml.DataField;\n" +
- "class FooBar {\n" +
- "static void method(List dataFields) {\n" +
- "DataDictionary dataDictionary = new DataDictionary(dataFields);\n" +
- "}\n" +
- "}";
- String instantiatedClass = "org.dmg.pmml.DataDictionary";
- J.NewClass toTest = getNewClassFromClassSource(classTested, instantiatedClass)
- .orElseThrow(() -> new RuntimeException("Failed to find J.NewClass org.dmg.pmml.DataDictionary"));
- assertThat(toTest)
- .isNotNull();
- Expression retrieved = jpmmlVisitor.replaceInstantiationListRemoved(toTest);
- String expected = "new DataDictionary().addDataFields(dataFields.toArray(new org.dmg.pmml.DataField[0]))";
- assertThat(retrieved)
- .isNotNull()
- .isInstanceOf(J.MethodInvocation.class)
- .hasToString(expected);
- }
-
- @Test
- public void replaceInstantiationListRemoved_notReplaced() {
- String classTested = "package com.yourorg;\n" +
- "import org.dmg.pmml.ScoreDistribution;\n" +
- "class FooBar {\n" +
- "static void method() {\n" +
- " ScoreDistribution scoreDistribution = new ScoreDistribution();\n" +
- "}\n" +
- "}";
- String instantiatedClass = "org.dmg.pmml.ScoreDistribution";
- J.NewClass toTest = getNewClassFromClassSource(classTested, instantiatedClass)
- .orElseThrow(() -> new RuntimeException("Failed to find J.NewClass org.dmg.pmml.DataDictionary"));
- assertThat(toTest)
- .isNotNull();
- Expression retrieved = jpmmlVisitor.replaceInstantiationListRemoved(toTest);
- assertThat(retrieved)
- .isNotNull()
- .isEqualTo(toTest);
- }
-
- @Test
- public void getRemovedListTuple_present() {
- String classTested = "package com.yourorg;\n" +
- "import java.util.List;\n" +
- "import org.dmg.pmml.DataDictionary;\n" +
- "import org.dmg.pmml.DataField;\n" +
- "class FooBar {\n" +
- "static void method(List dataFields) {\n" +
- "DataDictionary dataDictionary = new DataDictionary(dataFields);\n" +
- "}\n" +
- "}";
- String instantiatedClass = "org.dmg.pmml.DataDictionary";
- J.NewClass toTest = getNewClassFromClassSource(classTested, instantiatedClass)
- .orElseThrow(() -> new RuntimeException("Failed to find J.NewClass org.dmg.pmml.DataDictionary"));
- assertThat(toTest)
- .isNotNull();
- assertThat(jpmmlVisitor.getRemovedListTuple(toTest))
- .isPresent();
- }
-
- @Test
- public void getRemovedListTuple_notPresent() {
- String classTested = "package com.yourorg;\n" +
- "import org.dmg.pmml.ScoreDistribution;\n" +
- "class FooBar {\n" +
- "static void method() {\n" +
- " ScoreDistribution scoreDistribution = new ScoreDistribution();\n" +
- "}\n" +
- "}";
- String instantiatedClass = "org.dmg.pmml.ScoreDistribution";
- J.NewClass toTest = getNewClassFromClassSource(classTested, instantiatedClass)
- .orElseThrow(() -> new RuntimeException("Failed to find J.NewClass org.dmg.pmml.ScoreDistribution"));
- assertThat(toTest)
- .isNotNull();
- assertThat(jpmmlVisitor.getRemovedListTuple(toTest))
- .isNotPresent();
- }
-
- @Test
- public void isFieldNameCreate_true() {
- String classTested = "package com.yourorg;\n" +
- "\n" +
- "import org.dmg.pmml.FieldName;\n" +
- "\n" +
- "class Stub {\n" +
- " public void hello() {\n" +
- " System.out.println(FieldName.create(\"OUTPUT_\"));\n" +
- " }\n" +
- "}";
- String expressionTested = "FieldName.create";
- J.MethodInvocation toTest = getMethodInvocationFromClassSource(classTested, expressionTested)
- .orElseThrow(() -> new RuntimeException("Failed to find J.MethodInvocation FieldName.create(\"OUTPUT_\")"));
- assertThat(toTest)
- .isNotNull();
- assertThat(jpmmlVisitor.isFieldNameCreate(toTest))
- .isTrue();
- }
-
- @Test
- public void isFieldNameCreate_false() {
- String classTested = "package com.yourorg;\n" +
- "\n" +
- "import org.dmg.pmml.FieldName;\n" +
- "\n" +
- "class Stub {\n" +
- " public void hello() {\n" +
- " System.out.println(FieldName.create(\"OUTPUT_\"));\n" +
- " }\n" +
- "}";
- String expressionTested = "System.out.println";
- J.MethodInvocation toTest = getMethodInvocationFromClassSource(classTested, expressionTested)
- .orElseThrow(() -> new RuntimeException("Failed to find J.MethodInvocation System.out.println(FieldName.create(\"OUTPUT_\"))"));
- assertThat(toTest)
- .isNotNull();
- assertThat(jpmmlVisitor.isFieldNameCreate(toTest))
- .isFalse();
- }
-
- @Test
- public void hasFieldNameParameter_true() {
- String classTested = "package com.yourorg;\n" +
- "\n" +
- "import org.dmg.pmml.FieldName;\n" +
- "import org.dmg.pmml.DataField;\n" +
- "import org.dmg.pmml.DerivedField;\n" +
- "import java.util.Objects;\n" +
- "\n" +
- "class Stub {\n" +
- " public void hello(DataField dataField) {\n" +
- " DerivedField toReturn = new DerivedField();\n" +
- " toReturn.setName(FieldName.create(\"DER_\" + dataField.getName().getValue()));\n" +
- " }\n" +
- "}";
- String methodInvocation = "toReturn.setName";
- J.MethodInvocation toTest = getMethodInvocationFromClassSource(classTested, methodInvocation)
- .orElseThrow(() -> new RuntimeException("Failed to toReturn.setName"));
- assertThat(jpmmlVisitor.hasFieldNameParameter(toTest))
- .isTrue();
- }
-
- @Test
- public void hasFieldNameParameter_false() {
- String classTested = "package com.yourorg;\n" +
- "\n" +
- "import org.dmg.pmml.FieldName;\n" +
- "import org.dmg.pmml.DataField;\n" +
- "import java.util.Objects;\n" +
- "\n" +
- "class Stub {\n" +
- " public void hello(DataField field) {\n" +
- " Objects.equals(null, field.getName().getValue());\n" +
- " }\n" +
- "}";
- String methodInvocation = "Objects.equals";
- J.MethodInvocation toTest = getMethodInvocationFromClassSource(classTested, methodInvocation)
- .orElseThrow(() -> new RuntimeException("Failed to find Objects.equals"));
- assertThat(jpmmlVisitor.hasFieldNameParameter(toTest))
- .isFalse();
- classTested = "package com.yourorg;\n" +
- "\n" +
- "import org.dmg.pmml.FieldName;\n" +
- "import java.util.Objects;\n" +
- "\n" +
- "class Stub {\n" +
- " public void hello(FieldName fieldName) {\n" +
- " Objects.equals(null, fieldName.getValue());\n" +
- " }\n" +
- "}";
- toTest = getMethodInvocationFromClassSource(classTested, methodInvocation)
- .orElseThrow(() -> new RuntimeException("Failed to find J.MethodInvocation numericPredictor.getName()"));
- assertThat(jpmmlVisitor.hasFieldNameParameter(toTest))
- .isFalse();
- }
-
- @Test
- public void isFieldNameGetNameToGetFieldMapped_true() {
- String classTested = "package com.yourorg;\n" +
- "\n" +
- "import org.dmg.pmml.FieldName;\n" +
- "import org.dmg.pmml.regression.CategoricalPredictor;\n" +
- "\n" +
- "class Stub {\n" +
- " public String hello(CategoricalPredictor categoricalPredictor) {\n" +
- " FieldName fieldName = categoricalPredictor.getName();\n" +
- " return \"Hello from com.yourorg.FooBar!\";\n" +
- " }\n" +
- "}";
- String methodInvocation = "categoricalPredictor.getName";
- J.MethodInvocation toTest = getMethodInvocationFromClassSource(classTested, methodInvocation)
- .orElseThrow(() -> new RuntimeException("Failed to find J.MethodInvocation categoricalPredictor.getName()"));
- assertThat(jpmmlVisitor.isFieldNameGetNameToGetFieldMapped(toTest)).isTrue();
- classTested ="package com.yourorg;\n" +
- "\n" +
- "import org.dmg.pmml.FieldName;\n" +
- "import org.dmg.pmml.regression.NumericPredictor;\n" +
- "\n" +
- "class Stub {\n" +
- " public String hello(NumericPredictor numericPredictor) {\n" +
- " FieldName fieldName = numericPredictor.getName();\n" +
- " return \"Hello from com.yourorg.FooBar!\";\n" +
- " }\n" +
- "}";
- methodInvocation = "numericPredictor.getName";
- toTest = getMethodInvocationFromClassSource(classTested, methodInvocation)
- .orElseThrow(() -> new RuntimeException("Failed to find J.MethodInvocation numericPredictor.getName()"));
- assertThat(jpmmlVisitor.isFieldNameGetNameToGetFieldMapped(toTest)).isTrue();
- }
-
- @Test
- public void isFieldNameGetNameToGetFieldMapped_false() {
- String classTested = "package com.yourorg;\n" +
- "\n" +
- "import org.dmg.pmml.FieldName;\n" +
- "import org.dmg.pmml.DataField;\n" +
- "\n" +
- "class Stub {\n" +
- " public String hello(DataField dataField) {\n" +
- " FieldName fieldName = dataField.getName();\n" +
- " return \"Hello from com.yourorg.FooBar!\";\n" +
- " }\n" +
- "}";
- String methodInvocation = "dataField.getName";
- J.MethodInvocation toTest = getMethodInvocationFromClassSource(classTested, methodInvocation)
- .orElseThrow(() -> new RuntimeException("Failed to find J.MethodInvocation dataField.getName()"));
- assertThat(jpmmlVisitor.isFieldNameGetNameToGetFieldMapped(toTest)).isFalse();
- }
-
- @Test
- public void useFieldNameGetValue_true() {
- String classTested = "package com.yourorg;\n" +
- "\n" +
- "import org.dmg.pmml.DataField;\n" +
- "\n" +
- "class Stub {\n" +
- " public String hello(DataField field) {\n" +
- " System.out.println(field.getName().getValue());\n" +
- " return \"Hello from com.yourorg.FooBar!\";\n" +
- " }\n" +
- "}";
- String methodInvocation = "field.getName().getValue";
- J.MethodInvocation toTest = getMethodInvocationFromClassSource(classTested, methodInvocation)
- .orElseThrow(() -> new RuntimeException("Failed to find J.MethodInvocation field.getName().getValue()"));
- assertThat(jpmmlVisitor.useFieldNameGetValue(toTest)).isTrue();
- classTested = "package com.yourorg;\n" +
- "\n" +
- "import org.dmg.pmml.FieldName;\n" +
- "\n" +
- "class Stub {\n" +
- " public String hello(FieldName field) {\n" +
- " System.out.println(field.getValue());\n" +
- " return \"Hello from com.yourorg.FooBar!\";\n" +
- " }\n" +
- "}";
- methodInvocation = "field.getValue";
- toTest = getMethodInvocationFromClassSource(classTested, methodInvocation)
- .orElseThrow(() -> new RuntimeException("Failed to find J.MethodInvocation field.getValue()"));
- assertThat(jpmmlVisitor.useFieldNameGetValue(toTest)).isTrue();
- }
-
- @Test
- public void useFieldNameGetValue_false() {
- String classTested = "package com.yourorg;\n" +
- "\n" +
- "import org.dmg.pmml.DataField;\n" +
- "\n" +
- "class Stub {\n" +
- " public String hello(DataField field) {\n" +
- " System.out.println(field.getName().getValue());\n" +
- " return \"Hello from com.yourorg.FooBar!\";\n" +
- " }\n" +
- "}";
- String methodInvocation = "System.out.println";
- J.MethodInvocation toTest = getMethodInvocationFromClassSource(classTested, methodInvocation)
- .orElseThrow(() -> new RuntimeException("Failed to find J.MethodInvocation System.out.println()"));
- assertThat(jpmmlVisitor.useFieldNameGetValue(toTest)).isFalse();
- }
-
- @Test
- public void toMigrate_False() {
- String classTested = "package com.yourorg;\n" +
- "import java.util.List;\n" +
- "import java.util.Map;\n" +
- "class FooBar {\n" +
- "};";
- List toTest = getImportsFromClassSource(classTested);
- assertThat(jpmmlVisitor.toMigrate(toTest))
- .isFalse();
- assertThat(toTest).hasSize(2);
- }
-
- @Test
- public void toMigrate_True() {
- String classTested = "package com.yourorg;\n" +
- "import java.util.List;\n" +
- "import org.dmg.pmml.FieldName;\n" +
- "class FooBar {\n" +
- "};";
- List toTest = getImportsFromClassSource(classTested);
- assertThat(jpmmlVisitor.toMigrate(toTest))
- .isTrue();
- classTested = "package com.yourorg;\n" +
- "import java.util.List;\n" +
- "import org.jpmml.model.inlinetable.InputCell;\n" +
- "class FooBar {\n" +
- "};";
- toTest = getImportsFromClassSource(classTested);
- assertThat(jpmmlVisitor.toMigrate(toTest))
- .isTrue();
- }
-
- @Test
- public void updateMethodToTargetInstantiatedType() {
- JavaType.Method toTest = new JavaType.Method(null, 1025, jpmmlVisitor.originalInstantiatedType, "toArray",
- jpmmlVisitor.originalInstantiatedType,
- Collections.emptyList(),
- Collections.emptyList(), null, null);
- JavaType.Method retrieved = jpmmlVisitor.updateMethodToTargetInstantiatedType(toTest);
- assertThat(retrieved.getDeclaringType()).isEqualTo(jpmmlVisitor.targetInstantiatedType);
- assertThat(retrieved.getReturnType()).isEqualTo(jpmmlVisitor.targetInstantiatedType);
- }
-
- @Test
- public void updateTypeTreeToTargetInstantiatedType() {
- String classTested = "package com.yourorg;\n" +
- "\n" +
- "import org.dmg.pmml.ScoreDistribution;\n" +
- "\n" +
- "public class Stub {\n" +
- "\n" +
- " public void hello() {\n" +
- " ScoreDistribution scoreDistribution = new ScoreDistribution();\n" +
- " }\n" +
- "\n" +
- "}";
- String classInstantiated = "org.dmg.pmml.ScoreDistribution";
- J.NewClass toTest = getNewClassFromClassSource(classTested, classInstantiated)
- .orElseThrow(() -> new RuntimeException("Failed to find J.NewClass org.dmg.pmml.ScoreDistribution"));
- assertThat(toTest)
- .isNotNull();
- TypeTree retrieved = jpmmlVisitor.updateTypeTreeToTargetInstantiatedType(toTest);
- assertThat(retrieved)
- .isNotNull()
- .isInstanceOf(J.Identifier.class);
- assertThat(retrieved.getType()).isEqualTo(jpmmlVisitor.targetInstantiatedType);
- assertThat(((J.Identifier) retrieved).getSimpleName()).isEqualTo(((JavaType.ShallowClass) jpmmlVisitor.targetInstantiatedType).getClassName());
- }
-
- @Test
- public void removedListaTuple_getJMethod() {
- JPMMLVisitor.RemovedListTuple removedListTuple = new JPMMLVisitor.RemovedListTuple("addDataFields", JavaType.buildType("org.dmg.pmml.DataField"));
- String classTested = "package com.yourorg;\n" +
- "import java.util.List;\n" +
- "import org.dmg.pmml.DataDictionary;\n" +
- "import org.dmg.pmml.DataField;\n" +
- "class FooBar {\n" +
- "static void method(List dataFields) {\n" +
- "DataDictionary dataDictionary = new DataDictionary(dataFields);\n" +
- "}\n" +
- "}";
- String classInstantiated = "org.dmg.pmml.DataDictionary";
- J.NewClass toTest = getNewClassFromClassSource(classTested, classInstantiated)
- .orElseThrow(() -> new RuntimeException("Failed to find J.NewClass org.dmg.pmml.DataDictionary"));
- J.MethodInvocation retrieved = removedListTuple.getJMethod(toTest);
- String expected = "new DataDictionary().addDataFields(dataFields.toArray(new org.dmg.pmml.DataField[0]))";
- assertThat(retrieved)
- .isNotNull()
- .hasToString(expected);
-
- }
-}
\ No newline at end of file
diff --git a/kie-api/src/main/java/org/kie/api/event/process/ErrorEvent.java b/kie-api/src/main/java/org/kie/api/event/process/ErrorEvent.java
new file mode 100644
index 00000000000..af2cc4e0568
--- /dev/null
+++ b/kie-api/src/main/java/org/kie/api/event/process/ErrorEvent.java
@@ -0,0 +1,33 @@
+/**
+ * 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.api.event.process;
+
+import org.kie.api.runtime.process.NodeInstance;
+
+/**
+ * An event when a error is thrown
+ */
+public interface ErrorEvent extends ProcessNodeEvent {
+ /**
+ * Error associated to the event
+ *
+ * @return exception
+ */
+ Exception getException();
+}
diff --git a/kie-api/src/main/java/org/kie/api/event/process/ProcessEventListener.java b/kie-api/src/main/java/org/kie/api/event/process/ProcessEventListener.java
index 4f27158b6b1..085f7a34a3b 100644
--- a/kie-api/src/main/java/org/kie/api/event/process/ProcessEventListener.java
+++ b/kie-api/src/main/java/org/kie/api/event/process/ProcessEventListener.java
@@ -116,4 +116,10 @@ default void onSignal(SignalEvent event) {}
* @param event
*/
default void onMessage(MessageEvent event) {}
+
+ /**
+ * This listener method is invoked when an error is captured
+ * @param event
+ */
+ default void onError (ErrorEvent event) {}
}
diff --git a/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/DMNType.java b/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/DMNType.java
index 6bc053ec491..c6357966389 100644
--- a/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/DMNType.java
+++ b/kie-dmn/kie-dmn-api/src/main/java/org/kie/dmn/api/core/DMNType.java
@@ -100,6 +100,11 @@
* This is reflected in this DMN type {@link #getAllowedValues()}.
*
* It is important to note that attribute can only be present when the type is specified by reference.
+ *
typeConstraints
+ * As per the DMN specification, the {@link ItemDefinition#getTypeConstraint()} ()} attribute lists the possible values or ranges of values in the base type that are allowed in this ItemDefinition.
+ * This is reflected in this DMN type {@link #getTypeConstraint()}.
+ *
+ * It is important to note that attribute can only be present when the type is specified by reference.
*
getFields
* Only when a type is specified by composition, {@link #getFields()} will return the collection of the fields which constitutes the composite type.
*
@@ -204,7 +209,7 @@ public interface DMNType
DMNType clone();
/**
- * Definition of `instance of` accordingly to FEEL specifications Table 49.
+ * Definition of `instance of` accordingly to FEEL specifications Table 61.
* @param o
* @return if o is instance of the type represented by this type. If the parameter is null, returns false.
*/
@@ -212,10 +217,16 @@ public interface DMNType
/**
* Check if the value passed as parameter can be assigned to this type.
+ * It checks
+ * 1. type itself
+ * 2. allowedValues
+ * 3. typeConstraint
* @param value
* @return if value can be assigned to the type represented by this type. If the parameter is null, returns true.
*/
boolean isAssignableValue(Object value);
List getAllowedValues();
+
+ List getTypeConstraint();
}
diff --git a/kie-dmn/kie-dmn-core/pom.xml b/kie-dmn/kie-dmn-core/pom.xml
index cd5b62edf9d..092bb3931b1 100644
--- a/kie-dmn/kie-dmn-core/pom.xml
+++ b/kie-dmn/kie-dmn-core/pom.xml
@@ -55,6 +55,13 @@
teststest
+
+ org.kie
+ kie-dmn-test-resources
+ ${project.version}
+ tests
+ test
+
@@ -179,6 +186,12 @@
teststest
+
+ org.kie
+ kie-dmn-test-resources
+ tests
+ test
+ io.smallryejandex
diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNContextEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNContextEvaluator.java
index 9e710d761f6..4fbb5c0c649 100644
--- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNContextEvaluator.java
+++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNContextEvaluator.java
@@ -19,7 +19,6 @@
package org.kie.dmn.core.ast;
import java.util.ArrayList;
-import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
@@ -45,6 +44,8 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import static org.kie.dmn.core.util.CoerceUtil.coerceValue;
+
public class DMNContextEvaluator
implements DMNExpressionEvaluator {
private static final Logger logger = LoggerFactory.getLogger( DMNContextEvaluator.class );
@@ -98,14 +99,7 @@ public EvaluatorResult evaluate(DMNRuntimeEventManager eventManager, DMNResult d
}
EvaluatorResult er = ed.getEvaluator().evaluate( eventManager, result );
if ( er.getResultType() == ResultType.SUCCESS ) {
- Object value = er.getResult();
- if( ! ed.getType().isCollection() && value instanceof Collection &&
- ((Collection)value).size()==1 ) {
- // spec defines that "a=[a]", i.e., singleton collections should be treated as the single element
- // and vice-versa
- value = ((Collection)value).toArray()[0];
- }
-
+ Object value = coerceValue(ed.getType(), er.getResult());
if (((DMNRuntimeImpl) eventManager.getRuntime()).performRuntimeTypeCheck(result.getModel())) {
if (!(ed.getContextEntry().getExpression() instanceof FunctionDefinition)) {
// checking directly the result type...
diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNFunctionDefinitionEvaluator.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNFunctionDefinitionEvaluator.java
index ebb45e7e288..c7d6469aaca 100644
--- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNFunctionDefinitionEvaluator.java
+++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/ast/DMNFunctionDefinitionEvaluator.java
@@ -48,6 +48,8 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import static org.kie.dmn.core.util.CoerceUtil.coerceValue;
+
public class DMNFunctionDefinitionEvaluator
implements DMNExpressionEvaluator {
private static final Logger logger = LoggerFactory.getLogger( DMNFunctionDefinitionEvaluator.class );
@@ -157,8 +159,9 @@ public Object invoke(EvaluationContext ctx, Object[] params) {
closureContext.getAll().forEach(dmnContext::set);
for( int i = 0; i < params.length; i++ ) {
final String paramName = parameters.get(i).name;
- if ((!performRuntimeTypeCheck) || parameters.get(i).type.isAssignableValue(params[i])) {
- ctx.setValue(paramName, params[i]);
+ Object coercedObject = coerceValue(parameters.get(i).type, params[i]);
+ if ((!performRuntimeTypeCheck) || parameters.get(i).type.isAssignableValue(coercedObject)) {
+ ctx.setValue(paramName, coercedObject);
} else {
ctx.setValue(paramName, null);
MsgUtil.reportMessage(logger,
diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNCompilerImpl.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNCompilerImpl.java
index 364b5933f85..640a5c002af 100644
--- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNCompilerImpl.java
+++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNCompilerImpl.java
@@ -33,7 +33,6 @@
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
-import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
@@ -42,7 +41,7 @@
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
-import javax.xml.XMLConstants;
+
import javax.xml.namespace.QName;
import org.drools.io.FileSystemResource;
@@ -76,6 +75,7 @@
import org.kie.dmn.core.pmml.DMNImportPMMLInfo;
import org.kie.dmn.core.util.Msg;
import org.kie.dmn.core.util.MsgUtil;
+import org.kie.dmn.core.util.NamespaceUtil;
import org.kie.dmn.feel.lang.FEELProfile;
import org.kie.dmn.feel.lang.Type;
import org.kie.dmn.feel.lang.types.AliasFEELType;
@@ -106,6 +106,8 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import static org.kie.dmn.core.compiler.UnnamedImportUtils.processMergedModel;
+
public class DMNCompilerImpl implements DMNCompiler {
private static final Logger logger = LoggerFactory.getLogger( DMNCompilerImpl.class );
@@ -211,7 +213,7 @@ public DMNModel compile(Definitions dmndefs, Collection dmnModels, Res
DMNFEELHelper feel = new DMNFEELHelper(cc.getRootClassLoader(), helperFEELProfiles);
DMNCompilerContext ctx = new DMNCompilerContext(feel);
ctx.setRelativeResolver(relativeResolver);
-
+ List toMerge = new ArrayList<>();
if (!dmndefs.getImport().isEmpty()) {
for (Import i : dmndefs.getImport()) {
if (ImportDMNResolverUtil.whichImportType(i) == ImportType.DMN) {
@@ -230,8 +232,15 @@ public DMNModel compile(Definitions dmndefs, Collection dmnModels, Res
}, Function.identity());
if (located != null) {
String iAlias = Optional.ofNullable(i.getName()).orElse(located.getName());
- model.setImportAliasForNS(iAlias, located.getNamespace(), located.getName());
- importFromModel(model, located, iAlias);
+ // incubator-kie-issues#852: The idea is to not treat the anonymous models as import, but to "merge" them
+ // with original one,
+ // because otherwise we would have to deal with clashing name aliases, or similar issues
+ if (iAlias != null && !iAlias.isEmpty()) {
+ model.setImportAliasForNS(iAlias, located.getNamespace(), located.getName());
+ importFromModel(model, located, iAlias);
+ } else {
+ toMerge.add(located);
+ }
}
} else if (ImportDMNResolverUtil.whichImportType(i) == ImportType.PMML) {
processPMMLImport(model, i, relativeResolver);
@@ -249,6 +258,7 @@ public DMNModel compile(Definitions dmndefs, Collection dmnModels, Res
}
}
+ toMerge.forEach(mergedModel -> processMergedModel(model, (DMNModelImpl) mergedModel));
processItemDefinitions(ctx, model, dmndefs);
processDrgElements(ctx, model, dmndefs);
return model;
@@ -600,10 +610,11 @@ private DMNType buildTypeDef(DMNCompilerContext ctx, DMNModelImpl dmnModel, DMNN
type = (BaseDMNTypeImpl) resolveTypeRef(dmnModel, itemDef, itemDef, itemDef.getTypeRef());
if ( type != null ) {
UnaryTests allowedValuesStr = itemDef.getAllowedValues();
+ UnaryTests typeConstraintStr = itemDef.getTypeConstraint();
// we only want to clone the type definition if it is a top level type (not a field in a composite type)
// or if it changes the metadata for the base type
- if (topLevel == null || allowedValuesStr != null || itemDef.isIsCollection() != type.isCollection()) {
+ if (topLevel == null || allowedValuesStr != null || typeConstraintStr != null || itemDef.isIsCollection() != type.isCollection()) {
// we have to clone this type definition into a new one
String name = itemDef.getName();
@@ -616,18 +627,11 @@ private DMNType buildTypeDef(DMNCompilerContext ctx, DMNModelImpl dmnModel, DMNN
baseFEELType = new AliasFEELType(itemDef.getName(), (BuiltInType) baseFEELType);
}
- List av = null;
- if ( allowedValuesStr != null ) {
- av = ctx.getFeelHelper().evaluateUnaryTests(
- ctx,
- allowedValuesStr.getText(),
- dmnModel,
- itemDef,
- Msg.ERR_COMPILING_ALLOWED_VALUES_LIST_ON_ITEM_DEF,
- allowedValuesStr.getText(),
- node.getName()
- );
- }
+ List allowedValues = getUnaryTests(allowedValuesStr, ctx, dmnModel, node, itemDef,
+ Msg.ERR_COMPILING_ALLOWED_VALUES_LIST_ON_ITEM_DEF);
+ List typeConstraint = getUnaryTests(typeConstraintStr, ctx, dmnModel, node, itemDef,
+ Msg.ERR_COMPILING_TYPE_CONSTRAINT_LIST_ON_ITEM_DEF);
+
boolean isCollection = itemDef.isIsCollection();
if (isCollection) {
@@ -638,7 +642,8 @@ private DMNType buildTypeDef(DMNCompilerContext ctx, DMNModelImpl dmnModel, DMNN
CompositeTypeImpl compositeTypeImpl = (CompositeTypeImpl) type;
type = new CompositeTypeImpl(namespace, name, id, isCollection, compositeTypeImpl.getFields(), baseType, baseFEELType);
} else if (type instanceof SimpleTypeImpl) {
- type = new SimpleTypeImpl(namespace, name, id, isCollection, av, baseType, baseFEELType);
+ type = new SimpleTypeImpl(namespace, name, id, isCollection, allowedValues, typeConstraint,
+ baseType, baseFEELType);
}
if (topLevel != null) {
type.setBelongingType(topLevel);
@@ -702,7 +707,8 @@ private DMNType buildTypeDef(DMNCompilerContext ctx, DMNModelImpl dmnModel, DMNN
}
} else {
BaseDMNTypeImpl unknown = (BaseDMNTypeImpl) resolveTypeRef(dmnModel, itemDef, itemDef, null);
- type = new SimpleTypeImpl(dmnModel.getNamespace(), itemDef.getName(), itemDef.getId(), itemDef.isIsCollection(), null, unknown, unknown.getFeelType());
+ type = new SimpleTypeImpl(dmnModel.getNamespace(), itemDef.getName(), itemDef.getId(),
+ itemDef.isIsCollection(), null, null, unknown, unknown.getFeelType());
if (topLevel == null) {
DMNType registered = dmnModel.getTypeRegistry().registerType(type);
if (registered != type) {
@@ -722,6 +728,23 @@ private DMNType buildTypeDef(DMNCompilerContext ctx, DMNModelImpl dmnModel, DMNN
return type;
}
+ private List getUnaryTests(UnaryTests unaryTestsToRead, DMNCompilerContext ctx, DMNModelImpl dmnModel,
+ DMNNode node, ItemDefinition itemDef, Msg.Message2 message) {
+ List toReturn = null;
+ if (unaryTestsToRead != null) {
+ toReturn = ctx.getFeelHelper().evaluateUnaryTests(
+ ctx,
+ unaryTestsToRead.getText(),
+ dmnModel,
+ itemDef,
+ message,
+ unaryTestsToRead.getText(),
+ node.getName()
+ );
+ }
+ return toReturn;
+ }
+
private static boolean isFunctionItem(ItemDefinition itemDef) {
return !(itemDef instanceof org.kie.dmn.model.v1_1.KieDMNModelInstrumentedBase) && !(itemDef instanceof org.kie.dmn.model.v1_2.KieDMNModelInstrumentedBase) && itemDef.getFunctionItem() != null;
}
@@ -732,7 +755,7 @@ private static boolean isFunctionItem(ItemDefinition itemDef) {
*/
public DMNType resolveTypeRef(DMNModelImpl dmnModel, NamedElement model, DMNModelInstrumentedBase localElement, QName typeRef) {
if ( typeRef != null ) {
- QName nsAndName = getNamespaceAndName(localElement, dmnModel.getImportAliasesForNS(), typeRef, dmnModel.getNamespace());
+ QName nsAndName = NamespaceUtil.getNamespaceAndName(localElement, dmnModel.getImportAliasesForNS(), typeRef, dmnModel.getNamespace());
DMNType type = dmnModel.getTypeRegistry().resolveType(nsAndName.getNamespaceURI(), nsAndName.getLocalPart());
if (type == null && localElement.getURIFEEL().equals(nsAndName.getNamespaceURI())) {
@@ -792,52 +815,6 @@ DMNType resolveTypeRefUsingString(DMNModelImpl dmnModel, NamedElement model, DMN
return resolveTypeRef(dmnModel, model, localElement, parseQNameString(typeRef));
}
- /**
- * Given a typeRef in the form of prefix:localname or importalias.localname, resolves namespace and localname appropriately.
- * Example: feel:string would be resolved as http://www.omg.org/spec/FEEL/20140401, string.
- * Example: myimport.tPerson assuming an external model namespace as "http://drools.org" would be resolved as http://drools.org, tPerson.
- * @param localElement the local element is used to determine the namespace from the prefix if present, as in the form prefix:localname
- * @param importAliases the map of import aliases is used to determine the namespace, as in the form importalias.localname
- * @param typeRef the typeRef to be resolved.
- * @return
- */
- public static QName getNamespaceAndName(DMNModelInstrumentedBase localElement, Map importAliases, QName typeRef, String modelNamespace) {
- if (localElement instanceof org.kie.dmn.model.v1_1.KieDMNModelInstrumentedBase) {
- if (!typeRef.getPrefix().equals(XMLConstants.DEFAULT_NS_PREFIX)) {
- return new QName(localElement.getNamespaceURI(typeRef.getPrefix()), typeRef.getLocalPart());
- } else {
- for (Entry alias : importAliases.entrySet()) {
- String prefix = alias.getKey() + ".";
- if (typeRef.getLocalPart().startsWith(prefix)) {
- return new QName(alias.getValue().getNamespaceURI(), typeRef.getLocalPart().replace(prefix, ""));
- }
- }
- return new QName(localElement.getNamespaceURI(typeRef.getPrefix()), typeRef.getLocalPart());
- }
- } else { // DMN v1.2 onwards:
- for (BuiltInType bi : DMNTypeRegistryV12.ITEMDEF_TYPEREF_FEEL_BUILTIN) {
- for (String biName : bi.getNames()) {
- if (biName.equals(typeRef.getLocalPart())) {
- return new QName(localElement.getURIFEEL(), typeRef.getLocalPart());
- }
- }
- }
- for (Entry alias : importAliases.entrySet()) {
- String prefix = alias.getKey() + ".";
- if (typeRef.getLocalPart().startsWith(prefix)) {
- return new QName(alias.getValue().getNamespaceURI(), typeRef.getLocalPart().replace(prefix, ""));
- }
- }
- for (String nsKey : localElement.recurseNsKeys()) {
- String prefix = nsKey + ".";
- if (typeRef.getLocalPart().startsWith(prefix)) {
- return new QName(localElement.getNamespaceURI(nsKey), typeRef.getLocalPart().replace(prefix, ""));
- }
- }
- return new QName(modelNamespace, typeRef.getLocalPart());
- }
- }
-
public DMNCompilerConfiguration getDmnCompilerConfig() {
return this.dmnCompilerConfig;
}
diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNEvaluatorCompiler.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNEvaluatorCompiler.java
index ef0940f036d..185a963f298 100644
--- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNEvaluatorCompiler.java
+++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNEvaluatorCompiler.java
@@ -61,6 +61,7 @@
import org.kie.dmn.core.pmml.PMMLModelInfo;
import org.kie.dmn.core.util.Msg;
import org.kie.dmn.core.util.MsgUtil;
+import org.kie.dmn.core.util.NamespaceUtil;
import org.kie.dmn.feel.FEEL;
import org.kie.dmn.feel.lang.CompiledExpression;
import org.kie.dmn.feel.lang.impl.RootExecutionFrame;
@@ -601,7 +602,7 @@ protected DMNExpressionEvaluator compileDecisionTable(DMNCompilerContext ctx, DM
index );
} else if ( ic.getInputExpression().getTypeRef() != null ) {
QName inputExpressionTypeRef = ic.getInputExpression().getTypeRef();
- QName resolvedInputExpressionTypeRef = DMNCompilerImpl.getNamespaceAndName(ic.getInputExpression(), model.getImportAliasesForNS(), inputExpressionTypeRef, model.getNamespace());
+ QName resolvedInputExpressionTypeRef = NamespaceUtil.getNamespaceAndName(ic.getInputExpression(), model.getImportAliasesForNS(), inputExpressionTypeRef, model.getNamespace());
BaseDMNTypeImpl typeRef = (BaseDMNTypeImpl) model.getTypeRegistry().resolveType(resolvedInputExpressionTypeRef.getNamespaceURI(), resolvedInputExpressionTypeRef.getLocalPart());
inputType = typeRef;
if (inputType == null) {
@@ -764,7 +765,7 @@ public static BaseDMNTypeImpl inferTypeRef( DMNModelImpl model, DecisionTable dt
BaseDMNTypeImpl typeRef = (BaseDMNTypeImpl) model.getTypeRegistry().unknown();
if ( oc.getTypeRef() != null ) {
QName outputExpressionTypeRef = oc.getTypeRef();
- QName resolvedOutputExpressionTypeRef = DMNCompilerImpl.getNamespaceAndName(oc, model.getImportAliasesForNS(), outputExpressionTypeRef, model.getNamespace());
+ QName resolvedOutputExpressionTypeRef = NamespaceUtil.getNamespaceAndName(oc, model.getImportAliasesForNS(), outputExpressionTypeRef, model.getNamespace());
typeRef = (BaseDMNTypeImpl) model.getTypeRegistry().resolveType(resolvedOutputExpressionTypeRef.getNamespaceURI(), resolvedOutputExpressionTypeRef.getLocalPart());
if( typeRef == null ) {
typeRef = (BaseDMNTypeImpl) model.getTypeRegistry().unknown();
@@ -773,7 +774,7 @@ public static BaseDMNTypeImpl inferTypeRef( DMNModelImpl model, DecisionTable dt
QName inferredTypeRef = recurseUpToInferTypeRef(model, oc, dt);
// if inferredTypeRef is null, a std err will have been reported
if (inferredTypeRef != null) {
- QName resolvedInferredTypeRef = DMNCompilerImpl.getNamespaceAndName(oc, model.getImportAliasesForNS(), inferredTypeRef, model.getNamespace());
+ QName resolvedInferredTypeRef = NamespaceUtil.getNamespaceAndName(oc, model.getImportAliasesForNS(), inferredTypeRef, model.getNamespace());
typeRef = (BaseDMNTypeImpl) model.getTypeRegistry().resolveType(resolvedInferredTypeRef.getNamespaceURI(), resolvedInferredTypeRef.getLocalPart());
}
}
diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNFEELHelper.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNFEELHelper.java
index c66a673a779..c90326bdde8 100644
--- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNFEELHelper.java
+++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNFEELHelper.java
@@ -27,6 +27,10 @@
import java.util.Map;
import java.util.Queue;
+import javax.xml.namespace.QName;
+
+import com.github.javaparser.ast.CompilationUnit;
+import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import org.antlr.v4.runtime.CommonToken;
import org.kie.dmn.api.core.DMNContext;
import org.kie.dmn.api.core.DMNMessage;
@@ -37,6 +41,7 @@
import org.kie.dmn.core.impl.DMNModelImpl;
import org.kie.dmn.core.util.Msg;
import org.kie.dmn.core.util.MsgUtil;
+import org.kie.dmn.core.util.NamespaceUtil;
import org.kie.dmn.feel.FEEL;
import org.kie.dmn.feel.codegen.feel11.ProcessedUnaryTest;
import org.kie.dmn.feel.lang.CompiledExpression;
@@ -53,11 +58,10 @@
import org.kie.dmn.feel.runtime.events.UnknownVariableErrorEvent;
import org.kie.dmn.feel.util.ClassLoaderUtil;
import org.kie.dmn.model.api.DMNElement;
+import org.kie.dmn.model.api.ItemDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.github.javaparser.ast.CompilationUnit;
-import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
public class DMNFEELHelper {
@@ -109,6 +113,10 @@ public static boolean valueMatchesInUnaryTests(List unaryTests, Objec
for ( UnaryTest t : unaryTests ) {
try {
+ // allow usage of ? as place-holder inside UnaryTest
+ if (!ctx.isDefined("?")) {
+ ctx.setValue("?", value);
+ }
Boolean applyT = t.apply( ctx, value );
// the unary test above can actually return null, so we have to handle it here
if ( applyT == null ) {
@@ -172,6 +180,24 @@ public List evaluateUnaryTests(DMNCompilerContext ctx, String unaryTe
for ( Map.Entry entry : ctx.getVariables().entrySet() ) {
variableTypes.put( entry.getKey(), ((BaseDMNTypeImpl) entry.getValue()).getFeelType() );
}
+ // allow usage of ? as place-holder inside UnaryTest
+ if (!variableTypes.containsKey("?") && element instanceof ItemDefinition itemDef) {
+ String nameSpace;
+ String name;
+ if (itemDef.isIsCollection()) {
+ nameSpace = model.getTypeRegistry().feelNS();
+ name = "list";
+ } else {
+ QName typeRef = itemDef.getTypeRef();
+ QName nsAndName = NamespaceUtil.getNamespaceAndName(element, model.getImportAliasesForNS(), typeRef,
+ model.getNamespace());
+ nameSpace = nsAndName.getNamespaceURI();
+ name = nsAndName.getLocalPart();
+ }
+ BaseDMNTypeImpl toSet = (BaseDMNTypeImpl) model.getTypeRegistry().resolveType(nameSpace, name);
+ variableTypes.put("?", toSet.getFeelType());
+ }
+
result = feel.evaluateUnaryTests( unaryTests, variableTypes );
} catch( Throwable t ) {
logger.error( "Error evaluating unary tests. Error will be reported in the model.", t );
diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNTypeRegistry.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNTypeRegistry.java
index b422f984897..dc7e378f7c3 100644
--- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNTypeRegistry.java
+++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNTypeRegistry.java
@@ -18,6 +18,8 @@
*/
package org.kie.dmn.core.compiler;
+import java.util.Map;
+
import org.kie.dmn.api.core.DMNType;
import org.kie.dmn.feel.lang.types.FEELTypeRegistry;
@@ -25,8 +27,12 @@ public interface DMNTypeRegistry extends FEELTypeRegistry {
DMNType unknown();
+ Map> getTypes();
+
DMNType registerType(DMNType type);
DMNType resolveType(String namespace, String name);
+ String feelNS();
+
}
diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNTypeRegistryAbstract.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNTypeRegistryAbstract.java
index 18eeda7118b..a902e7b0b11 100644
--- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNTypeRegistryAbstract.java
+++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNTypeRegistryAbstract.java
@@ -45,7 +45,6 @@ public abstract class DMNTypeRegistryAbstract implements DMNTypeRegistry, FEELTy
protected ScopeImpl feelTypesScope = new ScopeImpl(); // no parent scope, intentional.
protected Map feelTypesScopeChildLU = new HashMap<>();
- protected abstract String feelNS();
public DMNTypeRegistryAbstract(Map aliases) {
this.aliases = aliases;
@@ -65,11 +64,11 @@ public DMNTypeRegistryAbstract(Map aliases) {
// already added, skip it
continue;
} else if( type == BuiltInType.LIST ) {
- feelPrimitiveType = new SimpleTypeImpl(feelNamespace, name, null, false, null, unknown(), type);
+ feelPrimitiveType = new SimpleTypeImpl(feelNamespace, name, null, false, null, null, unknown(), type);
} else if( type == BuiltInType.CONTEXT ) {
feelPrimitiveType = new CompositeTypeImpl( feelNamespace, name, null, false, Collections.emptyMap(), null, type );
} else {
- feelPrimitiveType = new SimpleTypeImpl( feelNamespace, name, null, false, null, null, type );
+ feelPrimitiveType = new SimpleTypeImpl( feelNamespace, name, null, false, null, null, null, type );
}
feelTypes.put( name, feelPrimitiveType );
feelTypesScope.define(new TypeSymbol(name, type));
@@ -93,6 +92,11 @@ public Type resolveFEELType(List qns) {
}
}
+ @Override
+ public Map> getTypes() {
+ return types;
+ }
+
protected void registerAsFEELType(DMNType dmnType) {
Optional optAliasKey = keyfromNS(dmnType.getNamespace());
Type feelType = ((BaseDMNTypeImpl) dmnType).getFeelType();
diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNTypeRegistryV11.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNTypeRegistryV11.java
index c70b10c67e5..cee46ab7672 100644
--- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNTypeRegistryV11.java
+++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNTypeRegistryV11.java
@@ -34,14 +34,11 @@ public DMNTypeRegistryV11(Map aliases) {
}
@Override
- protected String feelNS() {
+ public String feelNS() {
return KieDMNModelInstrumentedBase.URI_FEEL;
}
- private static final DMNType UNKNOWN = new SimpleTypeImpl(KieDMNModelInstrumentedBase.URI_FEEL,
- BuiltInType.UNKNOWN.getName(),
- null, true, null, null,
- BuiltInType.UNKNOWN );
+ private static final DMNType UNKNOWN = SimpleTypeImpl.UNKNOWN_DMNTYPE(KieDMNModelInstrumentedBase.URI_FEEL);
@Override
public DMNType unknown() {
diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNTypeRegistryV12.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNTypeRegistryV12.java
index e3c8dbdc62d..f146d2e1a2d 100644
--- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNTypeRegistryV12.java
+++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNTypeRegistryV12.java
@@ -32,10 +32,7 @@
public class DMNTypeRegistryV12 extends DMNTypeRegistryAbstract {
- private static final DMNType UNKNOWN = new SimpleTypeImpl(KieDMNModelInstrumentedBase.URI_FEEL,
- BuiltInType.UNKNOWN.getName(),
- null, true, null, null,
- BuiltInType.UNKNOWN );
+ private static final DMNType UNKNOWN = SimpleTypeImpl.UNKNOWN_DMNTYPE(KieDMNModelInstrumentedBase.URI_FEEL);
public DMNTypeRegistryV12() {
super(Collections.emptyMap());
@@ -67,7 +64,7 @@ public DMNType unknown() {
BuiltInType.CONTEXT));
@Override
- protected String feelNS() {
+ public String feelNS() {
return KieDMNModelInstrumentedBase.URI_FEEL;
}
diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNTypeRegistryV13.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNTypeRegistryV13.java
index efc927bd0dd..45c0ed87f8f 100644
--- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNTypeRegistryV13.java
+++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNTypeRegistryV13.java
@@ -24,15 +24,11 @@
import org.kie.dmn.api.core.DMNType;
import org.kie.dmn.core.impl.SimpleTypeImpl;
-import org.kie.dmn.feel.lang.types.BuiltInType;
import org.kie.dmn.model.v1_3.KieDMNModelInstrumentedBase;
public class DMNTypeRegistryV13 extends DMNTypeRegistryAbstract {
- private static final DMNType UNKNOWN = new SimpleTypeImpl(KieDMNModelInstrumentedBase.URI_FEEL,
- BuiltInType.UNKNOWN.getName(),
- null, true, null, null,
- BuiltInType.UNKNOWN );
+ private static final DMNType UNKNOWN = SimpleTypeImpl.UNKNOWN_DMNTYPE(KieDMNModelInstrumentedBase.URI_FEEL);
public DMNTypeRegistryV13(Map aliases) {
super(aliases);
@@ -44,7 +40,7 @@ public DMNType unknown() {
}
@Override
- protected String feelNS() {
+ public String feelNS() {
return KieDMNModelInstrumentedBase.URI_FEEL;
}
}
diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNTypeRegistryV14.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNTypeRegistryV14.java
index ba7d655b222..a39b5aeb421 100644
--- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNTypeRegistryV14.java
+++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNTypeRegistryV14.java
@@ -24,15 +24,11 @@
import org.kie.dmn.api.core.DMNType;
import org.kie.dmn.core.impl.SimpleTypeImpl;
-import org.kie.dmn.feel.lang.types.BuiltInType;
import org.kie.dmn.model.v1_4.KieDMNModelInstrumentedBase;
public class DMNTypeRegistryV14 extends DMNTypeRegistryAbstract {
- private static final DMNType UNKNOWN = new SimpleTypeImpl(KieDMNModelInstrumentedBase.URI_FEEL,
- BuiltInType.UNKNOWN.getName(),
- null, true, null, null,
- BuiltInType.UNKNOWN );
+ private static final DMNType UNKNOWN = SimpleTypeImpl.UNKNOWN_DMNTYPE(KieDMNModelInstrumentedBase.URI_FEEL);
public DMNTypeRegistryV14(Map aliases) {
super(aliases);
@@ -44,7 +40,7 @@ public DMNType unknown() {
}
@Override
- protected String feelNS() {
+ public String feelNS() {
return KieDMNModelInstrumentedBase.URI_FEEL;
}
}
diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNTypeRegistryV15.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNTypeRegistryV15.java
index 9c17a476005..332fe992b9d 100644
--- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNTypeRegistryV15.java
+++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DMNTypeRegistryV15.java
@@ -20,7 +20,6 @@
import org.kie.dmn.api.core.DMNType;
import org.kie.dmn.core.impl.SimpleTypeImpl;
-import org.kie.dmn.feel.lang.types.BuiltInType;
import org.kie.dmn.model.v1_5.KieDMNModelInstrumentedBase;
import javax.xml.namespace.QName;
@@ -28,10 +27,8 @@
public class DMNTypeRegistryV15 extends DMNTypeRegistryAbstract {
- private static final DMNType UNKNOWN = new SimpleTypeImpl(KieDMNModelInstrumentedBase.URI_FEEL,
- BuiltInType.UNKNOWN.getName(),
- null, true, null, null,
- BuiltInType.UNKNOWN );
+ private static final DMNType UNKNOWN = SimpleTypeImpl.UNKNOWN_DMNTYPE(KieDMNModelInstrumentedBase.URI_FEEL);
+
public DMNTypeRegistryV15(Map aliases) {
super(aliases);
@@ -43,7 +40,7 @@ public DMNType unknown() {
}
@Override
- protected String feelNS() {
+ public String feelNS() {
return KieDMNModelInstrumentedBase.URI_FEEL;
}
}
diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DecisionCompiler.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DecisionCompiler.java
index 26bfc58b0bd..62c68d50628 100644
--- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DecisionCompiler.java
+++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DecisionCompiler.java
@@ -38,6 +38,8 @@
import org.kie.dmn.model.api.DRGElement;
import org.kie.dmn.model.api.Decision;
+import static org.kie.dmn.core.compiler.UnnamedImportUtils.isInUnnamedImport;
+
public class DecisionCompiler implements DRGElementCompiler {
@Override
public boolean accept(DRGElement de) {
@@ -96,6 +98,9 @@ public static void loadInCtx(DMNBaseNode node, DMNCompilerContext ctx, DMNModelI
if (dep.getModelNamespace().equals(model.getNamespace())) {
// for BKMs might need to create a DMNType for "functions" and replace the type here by that
ctx.setVariable(dep.getName(), depType);
+ } else if (isInUnnamedImport(dep, model)) {
+ // the dependency is an unnamed import
+ ctx.setVariable(dep.getName(), depType);
} else {
// then the dependency is an imported dependency.
Optional alias = model.getImportAliasFor(dep.getModelNamespace(), dep.getModelName());
@@ -109,4 +114,5 @@ public static void loadInCtx(DMNBaseNode node, DMNCompilerContext ctx, DMNModelI
ctx.setVariable(importedType.getKey(), importedType.getValue());
}
}
+
}
\ No newline at end of file
diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DecisionServiceCompiler.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DecisionServiceCompiler.java
index be0e2d9fec1..9e21f0e6997 100644
--- a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DecisionServiceCompiler.java
+++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/DecisionServiceCompiler.java
@@ -43,6 +43,7 @@
import org.kie.dmn.core.impl.SimpleFnTypeImpl;
import org.kie.dmn.core.util.Msg;
import org.kie.dmn.core.util.MsgUtil;
+import org.kie.dmn.core.util.NamespaceUtil;
import org.kie.dmn.model.api.DMNElementReference;
import org.kie.dmn.model.api.DRGElement;
import org.kie.dmn.model.api.DecisionService;
@@ -285,7 +286,7 @@ private void checkFnConsistency(DMNModelImpl model, DecisionServiceNodeImpl ni,
fdReturnType);
}
} else if (ni.getDecisionService().getOutputDecision().size() > 1) {
- final Function lookupFn = (in) -> DMNCompilerImpl.getNamespaceAndName(ni.getDecisionService(), model.getImportAliasesForNS(), in, model.getNamespace());
+ final Function lookupFn = (in) -> NamespaceUtil.getNamespaceAndName(ni.getDecisionService(), model.getImportAliasesForNS(), in, model.getNamespace());
LinkedHashMap fdComposite = new LinkedHashMap<>();
for (DecisionNode dn : outputDecisions) {
fdComposite.put(dn.getName(), lookupFn.apply(dn.getDecision().getVariable().getTypeRef()));
diff --git a/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/UnnamedImportUtils.java b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/UnnamedImportUtils.java
new file mode 100644
index 00000000000..3f22b334e07
--- /dev/null
+++ b/kie-dmn/kie-dmn-core/src/main/java/org/kie/dmn/core/compiler/UnnamedImportUtils.java
@@ -0,0 +1,76 @@
+/**
+ * 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
+ *