aboutsummaryrefslogtreecommitdiffstats
path: root/feature-session-persistence
diff options
context:
space:
mode:
Diffstat (limited to 'feature-session-persistence')
-rw-r--r--feature-session-persistence/.gitignore1
-rw-r--r--feature-session-persistence/pom.xml172
-rw-r--r--feature-session-persistence/src/assembly/assemble_zip.xml76
-rw-r--r--feature-session-persistence/src/main/feature/config/feature-session-persistence.properties30
-rw-r--r--feature-session-persistence/src/main/feature/db/sessionpersistence/sql/18020-sessionpersistence.upgrade.sql54
-rw-r--r--feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/DroolsPersistenceProperties.java38
-rw-r--r--feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/DroolsSession.java42
-rw-r--r--feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/DroolsSessionConnector.java37
-rw-r--r--feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/DroolsSessionEntity.java82
-rw-r--r--feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/EntityMgrTrans.java143
-rw-r--r--feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/JpaDroolsSessionConnector.java108
-rw-r--r--feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/PersistenceFeature.java942
-rw-r--r--feature-session-persistence/src/main/resources/META-INF/persistence.xml73
-rw-r--r--feature-session-persistence/src/main/resources/META-INF/services/org.onap.policy.drools.core.PolicySessionFeatureApi1
-rw-r--r--feature-session-persistence/src/main/resources/META-INF/services/org.onap.policy.drools.features.PolicyEngineFeatureApi1
-rw-r--r--feature-session-persistence/src/test/java/org/onap/policy/drools/persistence/DroolsSessionEntityTest.java179
-rw-r--r--feature-session-persistence/src/test/java/org/onap/policy/drools/persistence/EntityMgrTransTest.java562
-rw-r--r--feature-session-persistence/src/test/java/org/onap/policy/drools/persistence/GenSchema.java59
-rw-r--r--feature-session-persistence/src/test/java/org/onap/policy/drools/persistence/JpaDroolsSessionConnectorTest.java197
-rw-r--r--feature-session-persistence/src/test/java/org/onap/policy/drools/persistence/PersistenceFeatureTest.java1392
-rw-r--r--feature-session-persistence/src/test/resources/META-INF/persistence.xml38
-rw-r--r--feature-session-persistence/src/test/resources/feature-session-persistence.properties28
-rw-r--r--feature-session-persistence/src/test/resources/logback-test.xml49
23 files changed, 0 insertions, 4304 deletions
diff --git a/feature-session-persistence/.gitignore b/feature-session-persistence/.gitignore
deleted file mode 100644
index b83d2226..00000000
--- a/feature-session-persistence/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-/target/
diff --git a/feature-session-persistence/pom.xml b/feature-session-persistence/pom.xml
deleted file mode 100644
index b3662a77..00000000
--- a/feature-session-persistence/pom.xml
+++ /dev/null
@@ -1,172 +0,0 @@
-<!--
- ============LICENSE_START=======================================================
- ONAP Policy Engine - Drools PDP
- ================================================================================
- Copyright (C) 2017-2018, 2020-2021 AT&T Intellectual Property. All rights reserved.
- Modifications Copyright (C) 2020 Nordix Foundation.
- ================================================================================
- Licensed 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.
- ============LICENSE_END=========================================================
- -->
-
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
-
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.onap.policy.drools-pdp</groupId>
- <artifactId>drools-pdp</artifactId>
- <version>1.10.1-SNAPSHOT</version>
- </parent>
-
- <artifactId>feature-session-persistence</artifactId>
-
- <name>feature-session-persistence</name>
- <description>Separately loadable feature module with session persistence code</description>
-
- <properties>
- </properties>
-
- <build>
- <plugins>
- <plugin>
- <artifactId>maven-assembly-plugin</artifactId>
- <executions>
- <execution>
- <id>zipfile</id>
- <goals>
- <goal>single</goal>
- </goals>
- <phase>package</phase>
- <configuration>
- <attach>true</attach>
- <finalName>${project.artifactId}-${project.version}</finalName>
- <descriptors>
- <descriptor>src/assembly/assemble_zip.xml</descriptor>
- </descriptors>
- <appendAssemblyId>false</appendAssemblyId>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-dependency-plugin</artifactId>
- <executions>
- <execution>
- <id>copy-dependencies</id>
- <goals>
- <goal>copy-dependencies</goal>
- </goals>
- <phase>prepare-package</phase>
- <configuration>
- <transitive>false</transitive>
- <outputDirectory>${project.build.directory}/assembly/lib</outputDirectory>
- <overWriteReleases>false</overWriteReleases>
- <overWriteSnapshots>true</overWriteSnapshots>
- <overWriteIfNewer>true</overWriteIfNewer>
- <useRepositoryLayout>false</useRepositoryLayout>
- <addParentPoms>false</addParentPoms>
- <copyPom>false</copyPom>
- <includeScope>runtime</includeScope>
- <excludeScope>provided</excludeScope>
- <excludeTransitive>true</excludeTransitive>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
-
- <dependencies>
- <dependency>
- <groupId>org.onap.policy.drools-pdp</groupId>
- <artifactId>policy-core</artifactId>
- <version>${project.version}</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.onap.policy.drools-pdp</groupId>
- <artifactId>policy-management</artifactId>
- <version>${project.version}</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.onap.policy.common</groupId>
- <artifactId>utils</artifactId>
- <version>${policy.common.version}</version>
- </dependency>
- <dependency>
- <groupId>org.powermock</groupId>
- <artifactId>powermock-api-mockito2</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.jboss.jbossts</groupId>
- <artifactId>jbossjta</artifactId>
- <version>4.16.6.Final</version>
- <exclusions>
- <exclusion>
- <artifactId>jboss-servlet-api_3.0_spec</artifactId>
- <groupId>org.jboss.spec.javax.servlet</groupId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>com.h2database</groupId>
- <artifactId>h2</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.hibernate</groupId>
- <artifactId>hibernate-core</artifactId>
- <scope>provided</scope>
- <!--
- Exclude this because it's incompatible with eclipselink, which already
- includes the same classes.
- -->
- <exclusions>
- <exclusion>
- <groupId>javax.persistence</groupId>
- <artifactId>javax.persistence-api</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>org.hibernate.common</groupId>
- <artifactId>hibernate-commons-annotations</artifactId>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-dbcp2</artifactId>
- <version>2.8.0</version>
- </dependency>
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-pool2</artifactId>
- <version>2.8.0</version>
- </dependency>
-
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.assertj</groupId>
- <artifactId>assertj-core</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
-</project>
diff --git a/feature-session-persistence/src/assembly/assemble_zip.xml b/feature-session-persistence/src/assembly/assemble_zip.xml
deleted file mode 100644
index 8a315960..00000000
--- a/feature-session-persistence/src/assembly/assemble_zip.xml
+++ /dev/null
@@ -1,76 +0,0 @@
-<!--
- ============LICENSE_START=======================================================
- feature-session-persistence
- ================================================================================
- Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- ================================================================================
- Licensed 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.
- ============LICENSE_END=========================================================
- -->
-
-<!-- Defines how we build the .zip file which is our distribution. -->
-
-<assembly
- xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
- <id>feature-session-persistence</id>
- <formats>
- <format>zip</format>
- </formats>
-
- <!-- we want "system" and related files right at the root level as this
- file is suppose to be unzip on top of a karaf distro. -->
- <includeBaseDirectory>false</includeBaseDirectory>
-
- <fileSets>
- <fileSet>
- <directory>target</directory>
- <outputDirectory>lib/feature</outputDirectory>
- <includes>
- <include>feature-session-persistence-${project.version}.jar</include>
- </includes>
- </fileSet>
- <fileSet>
- <directory>target/assembly/lib</directory>
- <outputDirectory>lib/dependencies</outputDirectory>
- <includes>
- <include>*.jar</include>
- </includes>
- </fileSet>
- <fileSet>
- <directory>src/main/feature/config</directory>
- <outputDirectory>config</outputDirectory>
- <fileMode>0644</fileMode>
- <excludes/>
- </fileSet>
- <fileSet>
- <directory>src/main/feature/bin</directory>
- <outputDirectory>bin</outputDirectory>
- <fileMode>0744</fileMode>
- <excludes/>
- </fileSet>
- <fileSet>
- <directory>src/main/feature/db</directory>
- <outputDirectory>db</outputDirectory>
- <fileMode>0744</fileMode>
- <excludes/>
- </fileSet>
- <fileSet>
- <directory>src/main/feature/install</directory>
- <outputDirectory>install</outputDirectory>
- <fileMode>0744</fileMode>
- <excludes/>
- </fileSet>
- </fileSets>
-</assembly>
diff --git a/feature-session-persistence/src/main/feature/config/feature-session-persistence.properties b/feature-session-persistence/src/main/feature/config/feature-session-persistence.properties
deleted file mode 100644
index 50e0618b..00000000
--- a/feature-session-persistence/src/main/feature/config/feature-session-persistence.properties
+++ /dev/null
@@ -1,30 +0,0 @@
-###
-# ============LICENSE_START=======================================================
-# feature-session-persistence
-# ================================================================================
-# Copyright (C) 2017, 2019, 2021 AT&T Intellectual Property. All rights reserved.
-# ================================================================================
-# Licensed 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.
-# ============LICENSE_END=========================================================
-###
-
-eclipselink.target-database=MySQL
-javax.persistence.jdbc.driver= org.mariadb.jdbc.Driver
-javax.persistence.jdbc.url=jdbc:mariadb://${envd:SQL_HOST}:${envd:SQL_PORT:3306}/sessionpersistence
-javax.persistence.jdbc.user=${envd:SQL_USER}
-javax.persistence.jdbc.password=${envd:SQL_PASSWORD}
-
-#Seconds timeout - 15 minutes
-persistence.sessioninfo.timeout=900
-
-persistence.objectstore.dir=features/session-persistence/jta
diff --git a/feature-session-persistence/src/main/feature/db/sessionpersistence/sql/18020-sessionpersistence.upgrade.sql b/feature-session-persistence/src/main/feature/db/sessionpersistence/sql/18020-sessionpersistence.upgrade.sql
deleted file mode 100644
index 6cb0299f..00000000
--- a/feature-session-persistence/src/main/feature/db/sessionpersistence/sql/18020-sessionpersistence.upgrade.sql
+++ /dev/null
@@ -1,54 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * feature-session-persistence
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed 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.
- * ============LICENSE_END=========================================================
- */
-
-set foreign_key_checks=0;
-
-CREATE TABLE if not exists sessionpersistence.DROOLSSESSIONENTITY
-(
-sessionName VARCHAR(255) NOT NULL,
-sessionId BIGINT NOT NULL,
-createdDate TIMESTAMP NOT NULL,
-updatedDate TIMESTAMP NOT NULL,
-PRIMARY KEY (sessionName)
-);
-
-CREATE TABLE if not exists sessionpersistence.SESSIONINFO
-(
-ID BIGINT NOT NULL AUTO_INCREMENT,
-LASTMODIFICATIONDATE TIMESTAMP,
-RULESBYTEARRAY MEDIUMBLOB,
-STARTDATE TIMESTAMP default current_timestamp,
-OPTLOCK INTEGER,
-PRIMARY KEY (ID)
-);
-
-CREATE TABLE if not exists sessionpersistence.WORKITEMINFO
-(
-WORKITEMID BIGINT NOT NULL AUTO_INCREMENT,
-CREATIONDATE TIMESTAMP default current_timestamp,
-`NAME` VARCHAR(500),
-PROCESSINSTANCEID BIGINT,
-STATE BIGINT,
-OPTLOCK INTEGER,
-WORKITEMBYTEARRAY BLOB,
-PRIMARY KEY (WORKITEMID)
-);
-
-set foreign_key_checks=1; \ No newline at end of file
diff --git a/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/DroolsPersistenceProperties.java b/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/DroolsPersistenceProperties.java
deleted file mode 100644
index ab85864f..00000000
--- a/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/DroolsPersistenceProperties.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * feature-session-persistence
- * ================================================================================
- * Copyright (C) 2017-2018, 2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.drools.persistence;
-
-import lombok.AccessLevel;
-import lombok.NoArgsConstructor;
-import org.eclipse.persistence.config.PersistenceUnitProperties;
-
-@NoArgsConstructor(access = AccessLevel.PRIVATE)
-public final class DroolsPersistenceProperties {
- /*
- * feature-session-persistence.properties parameter key values
- */
- public static final String DB_DRIVER = PersistenceUnitProperties.JDBC_DRIVER;
- public static final String DB_URL = PersistenceUnitProperties.JDBC_URL;
- public static final String DB_USER = PersistenceUnitProperties.JDBC_USER;
- public static final String DB_PWD = PersistenceUnitProperties.JDBC_PASSWORD;
- public static final String DB_SESSIONINFO_TIMEOUT = "persistence.sessioninfo.timeout";
- public static final String JTA_OBJECTSTORE_DIR = "persistence.objectstore.dir";
-}
diff --git a/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/DroolsSession.java b/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/DroolsSession.java
deleted file mode 100644
index 3b3c942d..00000000
--- a/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/DroolsSession.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * feature-session-persistence
- * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.drools.persistence;
-
-import java.util.Date;
-
-public interface DroolsSession {
-
- String getSessionName();
-
- void setSessionName(String sessionName);
-
- long getSessionId();
-
- void setSessionId(long sessionId);
-
- Date getCreatedDate();
-
- void setCreatedDate(Date createdDate);
-
- Date getUpdatedDate();
-
- void setUpdatedDate(Date updatedDate);
-}
diff --git a/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/DroolsSessionConnector.java b/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/DroolsSessionConnector.java
deleted file mode 100644
index 4656f9fd..00000000
--- a/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/DroolsSessionConnector.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * feature-session-persistence
- * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.drools.persistence;
-
-public interface DroolsSessionConnector {
- /**
- * Gets a session by PDP id and name.
- * @param sessName session name
- * @return a session, or {@code null} if it is not found
- */
- DroolsSession get(String sessName);
-
- /**
- * Replaces a session, adding it if it does not exist.
- * @param sess session to be replaced
- */
- void replace(DroolsSession sess);
-
-}
diff --git a/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/DroolsSessionEntity.java b/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/DroolsSessionEntity.java
deleted file mode 100644
index 9ac68567..00000000
--- a/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/DroolsSessionEntity.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * feature-session-persistence
- * ================================================================================
- * Copyright (C) 2017-2018, 2020-2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.drools.persistence;
-
-import java.io.Serializable;
-import java.util.Date;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.Id;
-import javax.persistence.PrePersist;
-import javax.persistence.PreUpdate;
-import javax.persistence.Temporal;
-import javax.persistence.TemporalType;
-import lombok.EqualsAndHashCode;
-import lombok.Getter;
-import lombok.NoArgsConstructor;
-import lombok.Setter;
-
-@Entity
-@Getter
-@Setter
-@EqualsAndHashCode(onlyExplicitlyIncluded = true)
-@NoArgsConstructor
-public class DroolsSessionEntity implements Serializable, DroolsSession {
-
- private static final long serialVersionUID = -5495057038819948709L;
-
- @Id
- @Column(name = "sessionName", nullable = false)
- @EqualsAndHashCode.Include
- private String sessionName = "-1";
-
- @Column(name = "sessionId", nullable = false)
- private long sessionId = -1L;
-
- @Temporal(TemporalType.TIMESTAMP)
- @Column(name = "createdDate", nullable = false)
- private Date createdDate;
-
- @Temporal(TemporalType.TIMESTAMP)
- @Column(name = "updatedDate", nullable = false)
- private Date updatedDate;
-
- public DroolsSessionEntity(String sessionName, long sessionId) {
- this.sessionName = sessionName;
- this.sessionId = sessionId;
- }
-
- @PrePersist
- public void prePersist() {
- this.createdDate = new Date();
- this.updatedDate = new Date();
- }
-
- @PreUpdate
- public void preUpdate() {
- this.updatedDate = new Date();
- }
-
- @Override
- public String toString() {
- return "{name=" + getSessionName() + ", id=" + getSessionId() + "}";
- }
-}
diff --git a/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/EntityMgrTrans.java b/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/EntityMgrTrans.java
deleted file mode 100644
index 7103c47c..00000000
--- a/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/EntityMgrTrans.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * feature-session-persistence
- * ================================================================================
- * Copyright (C) 2017-2018, 2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.drools.persistence;
-
-import javax.persistence.EntityManager;
-import javax.transaction.HeuristicMixedException;
-import javax.transaction.HeuristicRollbackException;
-import javax.transaction.NotSupportedException;
-import javax.transaction.RollbackException;
-import javax.transaction.Status;
-import javax.transaction.SystemException;
-import javax.transaction.UserTransaction;
-import lombok.AccessLevel;
-import lombok.Getter;
-import lombok.Setter;
-import org.onap.policy.common.utils.jpa.EntityMgrCloser;
-
-/**
- * Wrapper for an <i>EntityManager</i> that creates a JTA transaction that is auto-rolled
- * back when closed. Note: commit() and rollback() actions do nothing if a transaction was
- * already in progress when this object was constructed.
- */
-public class EntityMgrTrans extends EntityMgrCloser {
-
- /**
- * Transaction to be rolled back.
- */
- @Getter(AccessLevel.PROTECTED)
- @Setter(AccessLevel.PROTECTED)
- private static UserTransaction userTrans = com.arjuna.ats.jta.UserTransaction.userTransaction();
-
- /**
- * {@code True} if a transaction had already been started before this object was
- * constructed, {@code false} otherwise.
- */
- private boolean transInProgress;
-
- /**
- * Constructor.
- *
- * @param em entity for which a transaction is to be begun
- */
- public EntityMgrTrans(EntityManager em) {
- super(em);
-
- try {
- transInProgress = (userTrans.getStatus() == Status.STATUS_ACTIVE);
- if (!transInProgress) {
- userTrans.begin();
- }
-
- em.joinTransaction();
-
- } catch (RuntimeException | NotSupportedException | SystemException e) {
- em.close();
- throw new EntityMgrException(e);
- }
- }
-
- /**
- * Commits the transaction.
- */
- public void commit() {
- if (transInProgress) {
- return;
- }
-
- try {
- userTrans.commit();
-
- } catch (SecurityException | IllegalStateException | RollbackException | HeuristicMixedException
- | HeuristicRollbackException | SystemException e) {
-
- throw new EntityMgrException(e);
- }
- }
-
- /**
- * Rolls back the transaction.
- */
- public void rollback() {
- if (transInProgress) {
- return;
- }
-
- try {
- userTrans.rollback();
-
- } catch (IllegalStateException | SecurityException | SystemException e) {
- throw new EntityMgrException(e);
- }
- }
-
- @Override
- public void close() {
- try {
- if (!transInProgress && userTrans.getStatus() == Status.STATUS_ACTIVE) {
- userTrans.rollback();
- }
-
- } catch (IllegalStateException | SecurityException | SystemException e) {
- throw new EntityMgrException(e);
-
- } finally {
- super.close();
- }
- }
-
- /**
- * Runtime exceptions generated by this class. Wraps exceptions generated by delegated
- * operations, particularly when they are not, themselves, Runtime exceptions.
- */
- public static class EntityMgrException extends RuntimeException {
- private static final long serialVersionUID = 1L;
-
- /**
- * Constructor.
- *
- * @param ex exception to be wrapped
- */
- public EntityMgrException(Exception ex) {
- super(ex);
- }
- }
-}
diff --git a/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/JpaDroolsSessionConnector.java b/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/JpaDroolsSessionConnector.java
deleted file mode 100644
index 14c72708..00000000
--- a/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/JpaDroolsSessionConnector.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * feature-session-persistence
- * ================================================================================
- * Copyright (C) 2017-2018, 2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.drools.persistence;
-
-import javax.persistence.EntityManager;
-import javax.persistence.EntityManagerFactory;
-import lombok.AllArgsConstructor;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-@AllArgsConstructor
-public class JpaDroolsSessionConnector implements DroolsSessionConnector {
-
- private static Logger logger = LoggerFactory.getLogger(JpaDroolsSessionConnector.class);
-
- private final EntityManagerFactory emf;
-
- @Override
- public DroolsSession get(String sessName) {
-
- var em = emf.createEntityManager();
- DroolsSessionEntity entity = null;
-
- try (var trans = new EntityMgrTrans(em)) {
-
- entity = em.find(DroolsSessionEntity.class, sessName);
- if (entity != null) {
- em.refresh(entity);
- }
-
- trans.commit();
- }
-
- return entity;
- }
-
- @Override
- public void replace(DroolsSession sess) {
- String sessName = sess.getSessionName();
-
- logger.info("replace: Entering and manually updating session name= {}", sessName);
-
- var em = emf.createEntityManager();
-
- try (var trans = new EntityMgrTrans(em)) {
-
- if (!update(em, sess)) {
- add(em, sess);
- }
-
- trans.commit();
- }
-
- logger.info("replace: Exiting");
- }
-
- /**
- * Adds a session to the persistent store.
- *
- * @param em entity manager
- * @param sess session to be added
- */
- private void add(EntityManager em, DroolsSession sess) {
- logger.info("add: Inserting session id={}", sess.getSessionId());
-
- var ent = new DroolsSessionEntity(sess.getSessionName(), sess.getSessionId());
-
- em.persist(ent);
- }
-
- /**
- * Updates a session, if it exists within the persistent store.
- *
- * @param em entity manager
- * @param sess session data to be persisted
- * @return {@code true} if a record was updated, {@code false} if it was not found
- */
- private boolean update(EntityManager em, DroolsSession sess) {
-
- DroolsSessionEntity session = em.find(DroolsSessionEntity.class, sess.getSessionName());
- if (session == null) {
- return false;
- }
-
- logger.info("update: Updating session id to {}", sess.getSessionId());
- session.setSessionId(sess.getSessionId());
-
- return true;
- }
-}
diff --git a/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/PersistenceFeature.java b/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/PersistenceFeature.java
deleted file mode 100644
index a929c712..00000000
--- a/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/PersistenceFeature.java
+++ /dev/null
@@ -1,942 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * feature-session-persistence
- * ================================================================================
- * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.drools.persistence;
-
-import java.io.IOException;
-import java.sql.PreparedStatement;
-import java.sql.SQLException;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.Persistence;
-import javax.transaction.TransactionManager;
-import javax.transaction.TransactionSynchronizationRegistry;
-import javax.transaction.UserTransaction;
-import org.apache.commons.dbcp2.BasicDataSource;
-import org.apache.commons.dbcp2.BasicDataSourceFactory;
-import org.hibernate.cfg.AvailableSettings;
-import org.kie.api.KieServices;
-import org.kie.api.runtime.Environment;
-import org.kie.api.runtime.EnvironmentName;
-import org.kie.api.runtime.KieSession;
-import org.kie.api.runtime.KieSessionConfiguration;
-import org.onap.policy.drools.core.PolicyContainer;
-import org.onap.policy.drools.core.PolicySession;
-import org.onap.policy.drools.core.PolicySessionFeatureApi;
-import org.onap.policy.drools.features.PolicyEngineFeatureApi;
-import org.onap.policy.drools.system.PolicyController;
-import org.onap.policy.drools.system.PolicyControllerConstants;
-import org.onap.policy.drools.system.PolicyEngine;
-import org.onap.policy.drools.utils.PropertyUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * If this feature is supported, there is a single instance of it. It adds persistence to Drools
- * sessions. In addition, if an active-standby feature exists, then that is used to determine the
- * active and last-active PDP. If it does not exist, then the current host name is used as the PDP
- * id.
- *
- * <p>The bulk of the code here was once in other classes, such as 'PolicyContainer' and 'Main'. It
- * was moved here as part of making this a separate optional feature.
- */
-public class PersistenceFeature implements PolicySessionFeatureApi, PolicyEngineFeatureApi {
-
- private static final Logger logger = LoggerFactory.getLogger(PersistenceFeature.class);
-
- /** KieService factory. */
- private KieServices kieSvcFact;
-
- /** Persistence properties. */
- private Properties persistProps;
-
- /** Whether or not the SessionInfo records should be cleaned out. */
- private boolean sessInfoCleaned;
-
- /** SessionInfo timeout, in milli-seconds, as read from
- * {@link #persistProps}. */
- private long sessionInfoTimeoutMs;
-
- /** Object used to serialize cleanup of sessioninfo table. */
- private Object cleanupLock = new Object();
-
- /**
- * Lookup the adjunct for this feature that is associated with the specified PolicyContainer. If
- * not found, create one.
- *
- * @param policyContainer the container whose adjunct we are looking up, and possibly creating
- * @return the associated 'ContainerAdjunct' instance, which may be new
- */
- private ContainerAdjunct getContainerAdjunct(PolicyContainer policyContainer) {
-
- Object rval = policyContainer.getAdjunct(this);
-
- if (!(rval instanceof ContainerAdjunct)) {
- // adjunct does not exist, or has the wrong type (should never
- // happen)
- rval = new ContainerAdjunct(policyContainer);
- policyContainer.setAdjunct(this, rval);
- }
-
- return (ContainerAdjunct) rval;
- }
-
- /**
- * {@inheritDoc}.
- **/
- @Override
- public int getSequenceNumber() {
- return 1;
- }
-
- /**
- * {@inheritDoc}.
- **/
- @Override
- public void globalInit(String[] args, String configDir) {
-
- kieSvcFact = getKieServices();
-
- try {
- persistProps = loadProperties(configDir + "/feature-session-persistence.properties");
-
- } catch (IOException e1) {
- logger.error("initializePersistence: ", e1);
- }
-
- sessionInfoTimeoutMs = getPersistenceTimeout();
- }
-
- /**
- * Creates a persistent KieSession, loading it from the persistent store, or creating one, if it
- * does not exist yet.
- */
- @Override
- public KieSession activatePolicySession(
- PolicyContainer policyContainer, String name, String kieBaseName) {
-
- if (isPersistenceEnabled(policyContainer, name)) {
- cleanUpSessionInfo();
-
- return getContainerAdjunct(policyContainer).newPersistentKieSession(name, kieBaseName);
- }
-
- return null;
- }
-
- /**
- * {@inheritDoc}.
- **/
- @Override
- public PolicySession.ThreadModel selectThreadModel(PolicySession session) {
-
- var policyContainer = session.getContainer();
- if (isPersistenceEnabled(policyContainer, session.getName())) {
- return new PersistentThreadModel(session, getProperties(policyContainer));
- }
- return null;
- }
-
- /**
- * {@inheritDoc}.
- **/
- @Override
- public void disposeKieSession(PolicySession policySession) {
-
- ContainerAdjunct contAdj =
- (ContainerAdjunct) policySession.getContainer().getAdjunct(this);
- if (contAdj != null) {
- contAdj.disposeKieSession(policySession.getName());
- }
- }
-
- /**
- * {@inheritDoc}.
- **/
- @Override
- public void destroyKieSession(PolicySession policySession) {
-
- ContainerAdjunct contAdj =
- (ContainerAdjunct) policySession.getContainer().getAdjunct(this);
- if (contAdj != null) {
- contAdj.destroyKieSession(policySession.getName());
- }
- }
-
- /**
- * {@inheritDoc}.
- **/
- @Override
- public boolean afterStart(PolicyEngine engine) {
- return false;
- }
-
- /**
- * {@inheritDoc}.
- **/
- @Override
- public boolean beforeStart(PolicyEngine engine) {
- return cleanup();
- }
-
- /**
- * {@inheritDoc}.
- **/
- @Override
- public boolean beforeActivate(PolicyEngine engine) {
- return cleanup();
- }
-
- private boolean cleanup() {
- synchronized (cleanupLock) {
- sessInfoCleaned = false;
- }
-
- return false;
- }
-
- /**
- * {@inheritDoc}.
- **/
- @Override
- public boolean afterActivate(PolicyEngine engine) {
- return false;
- }
-
- /* ============================================================ */
-
- /**
- * Gets the persistence timeout value for sessioninfo records.
- *
- * @return the timeout value, in milli-seconds, or {@code -1} if it is unspecified or invalid
- */
- private long getPersistenceTimeout() {
- String timeoutString = null;
-
- try {
- timeoutString = persistProps.getProperty(DroolsPersistenceProperties.DB_SESSIONINFO_TIMEOUT);
-
- if (timeoutString != null) {
- // timeout parameter is specified
- return Long.valueOf(timeoutString) * 1000;
- }
-
- } catch (NumberFormatException e) {
- logger.error(
- "Invalid value for Drools persistence property persistence.sessioninfo.timeout: {}",
- timeoutString,
- e);
- }
-
- return -1;
- }
-
- /* ============================================================ */
-
- /**
- * Each instance of this class is a logical extension of a 'PolicyContainer' instance. Its
- * reference is stored in the 'adjuncts' table within the 'PolicyContainer', and will be
- * garbage-collected with the container.
- */
- protected class ContainerAdjunct {
- /** 'PolicyContainer' instance that this adjunct is extending. */
- private PolicyContainer policyContainer;
-
- /** Maps a KIE session name to its data source. */
- private Map<String, DsEmf> name2ds = new HashMap<>();
-
- /**
- * Constructor - initialize a new 'ContainerAdjunct'.
- *
- * @param policyContainer the 'PolicyContainer' instance this adjunct is extending
- */
- private ContainerAdjunct(PolicyContainer policyContainer) {
- this.policyContainer = policyContainer;
- }
-
- /**
- * Create a new persistent KieSession. If there is already a corresponding entry in the
- * database, it is used to initialize the KieSession. If not, a completely new session is
- * created.
- *
- * @param name the name of the KieSession (which is also the name of the associated
- * PolicySession)
- * @param kieBaseName the name of the 'KieBase' instance containing this session
- * @return a new KieSession with persistence enabled
- */
- private KieSession newPersistentKieSession(String name, String kieBaseName) {
-
- configureSysProps();
-
- BasicDataSource ds = makeDataSource(getDataSourceProperties());
- var dsemf = new DsEmf(ds);
-
- try {
- EntityManagerFactory emf = dsemf.emf;
- DroolsSessionConnector conn = makeJpaConnector(emf);
-
- long desiredSessionId = getSessionId(conn, name);
-
- logger.info(
- "\n\nThis controller is primary... coming up with session {} \n\n", desiredSessionId);
-
- // session does not exist -- attempt to create one
- logger.info(
- "getPolicySession:session does not exist -- attempt to create one with name {}", name);
-
- var env = kieSvcFact.newEnvironment();
-
- configureKieEnv(env, emf);
-
- var kieConf = kieSvcFact.newKieSessionConfiguration();
-
- KieSession kieSession =
- (desiredSessionId >= 0
- ? loadKieSession(kieBaseName, desiredSessionId, env, kieConf)
- : null);
-
- if (kieSession == null) {
- // loadKieSession() returned null or desiredSessionId < 0
- logger.info(
- "LOADING We cannot load session {}. Going to create a new one", desiredSessionId);
-
- kieSession = newKieSession(kieBaseName, env);
- }
-
- replaceSession(conn, name, kieSession);
-
- name2ds.put(name, dsemf);
-
- return kieSession;
-
- } catch (RuntimeException e) {
- dsemf.close();
- throw e;
- }
- }
-
- /**
- * Loads an existing KieSession from the persistent store.
- *
- * @param kieBaseName the name of the 'KieBase' instance containing this session
- * @param desiredSessionId id of the desired KieSession
- * @param env Kie Environment for the session
- * @param kieConf Kie Configuration for the session
- * @return the persistent session, or {@code null} if it could not be loaded
- */
- private KieSession loadKieSession(
- String kieBaseName, long desiredSessionId, Environment env, KieSessionConfiguration kieConf) {
- try {
- var kieSession =
- kieSvcFact
- .getStoreServices()
- .loadKieSession(
- desiredSessionId,
- policyContainer.getKieContainer().getKieBase(kieBaseName),
- kieConf,
- env);
-
- logger.info("LOADING Loaded session {}", desiredSessionId);
-
- return kieSession;
-
- } catch (Exception e) {
- logger.error("loadKieSession error: ", e);
- return null;
- }
- }
-
- /**
- * Creates a new, persistent KieSession.
- *
- * @param kieBaseName the name of the 'KieBase' instance containing this session
- * @param env Kie Environment for the session
- * @return a new, persistent session
- */
- private KieSession newKieSession(String kieBaseName, Environment env) {
- var kieSession =
- kieSvcFact
- .getStoreServices()
- .newKieSession(policyContainer.getKieContainer().getKieBase(kieBaseName), null, env);
-
- logger.info("LOADING CREATED {}", kieSession.getIdentifier());
-
- return kieSession;
- }
-
- /**
- * Closes the data source associated with a session.
- *
- * @param name name of the session being destroyed
- */
- private void destroyKieSession(String name) {
- closeDataSource(name);
- }
-
- /**
- * Closes the data source associated with a session.
- *
- * @param name name of the session being disposed of
- */
- private void disposeKieSession(String name) {
- closeDataSource(name);
- }
-
- /**
- * Closes the data source associated with a session.
- *
- * @param name name of the session whose data source is to be closed
- */
- private void closeDataSource(String name) {
- DsEmf ds = name2ds.remove(name);
- if (ds != null) {
- ds.close();
- }
- }
-
- /** Configures java system properties for JPA/JTA. */
- private void configureSysProps() {
- System.setProperty("com.arjuna.ats.arjuna.coordinator.defaultTimeout", "60");
- System.setProperty(
- "com.arjuna.ats.arjuna.objectstore.objectStoreDir",
- persistProps.getProperty(DroolsPersistenceProperties.JTA_OBJECTSTORE_DIR));
- System.setProperty(
- "ObjectStoreEnvironmentBean.objectStoreDir",
- persistProps.getProperty(DroolsPersistenceProperties.JTA_OBJECTSTORE_DIR));
- }
-
- /**
- * Configures a Kie Environment.
- *
- * @param env environment to be configured
- * @param emf entity manager factory
- */
- private void configureKieEnv(Environment env, EntityManagerFactory emf) {
- env.set(EnvironmentName.ENTITY_MANAGER_FACTORY, emf);
- env.set(EnvironmentName.TRANSACTION, getUserTrans());
- env.set(EnvironmentName.TRANSACTION_SYNCHRONIZATION_REGISTRY, getTransSyncReg());
- env.set(EnvironmentName.TRANSACTION_MANAGER, getTransMgr());
- }
-
- /**
- * Gets a session's ID from the persistent store.
- *
- * @param conn persistence connector
- * @param sessnm name of the session
- * @return the session's id, or {@code -1} if the session is not found
- */
- private long getSessionId(DroolsSessionConnector conn, String sessnm) {
- DroolsSession sess = conn.get(sessnm);
- return sess != null ? sess.getSessionId() : -1;
- }
-
- /**
- * Replaces a session within the persistent store, if it exists. Adds it otherwise.
- *
- * @param conn persistence connector
- * @param sessnm name of session to be updated
- * @param kieSession new session information
- */
- private void replaceSession(DroolsSessionConnector conn, String sessnm, KieSession kieSession) {
-
- var sess = new DroolsSessionEntity();
-
- sess.setSessionName(sessnm);
- sess.setSessionId(kieSession.getIdentifier());
-
- conn.replace(sess);
- }
- }
-
- /* ============================================================ */
-
- /**
- * Gets the data source properties.
- *
- * @return the data source properties
- */
- private Properties getDataSourceProperties() {
- var props = new Properties();
- props.put("driverClassName", persistProps.getProperty(DroolsPersistenceProperties.DB_DRIVER));
- props.put("url", persistProps.getProperty(DroolsPersistenceProperties.DB_URL));
- props.put("username", persistProps.getProperty(DroolsPersistenceProperties.DB_USER));
- props.put("password", persistProps.getProperty(DroolsPersistenceProperties.DB_PWD));
- props.put("maxActive", "3");
- props.put("maxIdle", "1");
- props.put("maxWait", "120000");
- props.put("whenExhaustedAction", "2");
- props.put("testOnBorrow", "false");
- props.put("poolPreparedStatements", "true");
-
- return props;
- }
-
- /**
- * Removes "old" Drools 'sessioninfo' records, so they aren't used to restore data to Drools
- * sessions. This also has the useful side-effect of removing abandoned records as well.
- */
- private void cleanUpSessionInfo() {
-
- synchronized (cleanupLock) {
- if (sessInfoCleaned) {
- logger.info("Clean up of sessioninfo table: already done");
- return;
- }
-
- if (sessionInfoTimeoutMs < 0) {
- logger.info("Clean up of sessioninfo table: no timeout specified");
- return;
- }
-
- // now do the record deletion
- try (BasicDataSource ds = makeDataSource(getDataSourceProperties());
- var connection = ds.getConnection();
- PreparedStatement statement =
- connection.prepareStatement(
- "DELETE FROM sessioninfo WHERE timestampdiff(second,lastmodificationdate,now()) > ?")) {
-
- connection.setAutoCommit(true);
-
- statement.setLong(1, sessionInfoTimeoutMs / 1000);
-
- int count = statement.executeUpdate();
- logger.info("Cleaning up sessioninfo table -- {} records removed", count);
-
- } catch (SQLException e) {
- logger.error("Clean up of sessioninfo table failed", e);
- }
-
- // delete DroolsSessionEntity where sessionId not in (sessinfo.xxx)?
-
- sessInfoCleaned = true;
- }
- }
-
- /**
- * Determine whether persistence is enabled for a specific container.
- *
- * @param container container to be checked
- * @param sessionName name of the session to be checked
- * @return {@code true} if persistence is enabled for this container, and {@code false} if not
- */
- private boolean isPersistenceEnabled(PolicyContainer container, String sessionName) {
- var properties = getProperties(container);
- var rval = false;
-
- if (properties != null) {
- // fetch the 'type' property
- String type = getProperty(properties, sessionName, "type");
- rval = "auto".equals(type) || "native".equals(type);
- }
-
- return rval;
- }
-
- /**
- * Determine the controller properties associated with the policy container.
- *
- * @param container container whose properties are to be retrieved
- * @return the container's properties, or {@code null} if not found
- */
- private Properties getProperties(PolicyContainer container) {
- try {
- return getPolicyController(container).getProperties();
- } catch (IllegalArgumentException e) {
- logger.error("getProperties exception: ", e);
- return null;
- }
- }
-
- /**
- * Fetch the persistence property associated with a session. The name may have the form:
- *
- * <ul>
- * <li>persistence.SESSION-NAME.PROPERTY
- * <li>persistence.PROPERTY
- * </ul>
- *
- * @param properties properties from which the value is to be retrieved
- * @param sessionName session name of interest
- * @param property property name of interest
- * @return the property value, or {@code null} if not found
- */
- private String getProperty(Properties properties, String sessionName, String property) {
- String value = properties.getProperty("persistence." + sessionName + "." + property);
- if (value == null) {
- value = properties.getProperty("persistence." + property);
- }
-
- return value;
- }
-
- /* ============================================================ */
-
- /**
- * This 'ThreadModel' variant periodically calls 'KieSession.fireAllRules()', because the
- * 'fireUntilHalt' method isn't compatible with persistence.
- */
- public class PersistentThreadModel implements Runnable, PolicySession.ThreadModel {
-
- /** Session associated with this persistent thread. */
- private final PolicySession session;
-
- /** The session thread. */
- private final Thread thread;
-
- /** Used to indicate that processing should stop. */
- private final CountDownLatch stopped = new CountDownLatch(1);
-
- /** Minimum time, in milli-seconds, that the thread should sleep before firing rules again. */
- long minSleepTime = 100;
-
- /**
- * Maximum time, in milli-seconds, that the thread should sleep before firing rules again. This
- * is a "half" time, so that we can multiply it by two without overflowing the word size.
- */
- long halfMaxSleepTime = 5000L / 2L;
-
- /**
- * Constructor - initialize variables and create thread.
- *
- * @param session the 'PolicySession' instance
- * @param properties may contain additional session properties
- */
- public PersistentThreadModel(PolicySession session, Properties properties) {
- this.session = session;
- this.thread = new Thread(this, getThreadName());
-
- if (properties == null) {
- return;
- }
-
- // extract 'minSleepTime' and/or 'maxSleepTime'
- String name = session.getName();
-
- // fetch 'minSleepTime' value, and update if defined
- var sleepTimeString = getProperty(properties, name, "minSleepTime");
- if (sleepTimeString != null) {
- try {
- minSleepTime = Math.max(1, Integer.valueOf(sleepTimeString));
- } catch (Exception e) {
- logger.error("{}: Illegal value for 'minSleepTime'", sleepTimeString, e);
- }
- }
-
- // fetch 'maxSleepTime' value, and update if defined
- long maxSleepTime = 2 * halfMaxSleepTime;
- sleepTimeString = getProperty(properties, name, "maxSleepTime");
- if (sleepTimeString != null) {
- try {
- maxSleepTime = Math.max(1, Integer.valueOf(sleepTimeString));
- } catch (Exception e) {
- logger.error("{}: Illegal value for 'maxSleepTime'", sleepTimeString, e);
- }
- }
-
- // swap values if needed
- if (minSleepTime > maxSleepTime) {
- logger.error("minSleepTime({}) is greater than maxSleepTime({}) -- swapping", minSleepTime,
- maxSleepTime);
- long tmp = minSleepTime;
- minSleepTime = maxSleepTime;
- maxSleepTime = tmp;
- }
-
- halfMaxSleepTime = Math.max(1, maxSleepTime / 2);
- }
-
- /**
- * Get thread name.
- *
- * @return the String to use as the thread name */
- private String getThreadName() {
- return "Session " + session.getFullName() + " (persistent)";
- }
-
- /*=========================*/
- /* 'ThreadModel' interface */
- /*=========================*/
-
- /**
- * {@inheritDoc}.
- **/
- @Override
- public void start() {
- thread.start();
- }
-
- /**
- * {@inheritDoc}.
- **/
- @Override
- public void stop() {
- // tell the thread to stop
- stopped.countDown();
-
- // wait up to 10 seconds for the thread to stop
- try {
- thread.join(10000);
-
- } catch (InterruptedException e) {
- logger.error("stopThread exception: ", e);
- Thread.currentThread().interrupt();
- }
-
- // verify that it's done
- if (thread.isAlive()) {
- logger.error("stopThread: still running");
- }
- }
-
- /**
- * {@inheritDoc}.
- **/
- @Override
- public void updated() {
- // the container artifact has been updated -- adjust the thread name
- thread.setName(getThreadName());
- }
-
- /*======================*/
- /* 'Runnable' interface */
- /*======================*/
-
- /**
- * {@inheritDoc}.
- **/
- @Override
- public void run() {
- logger.info("PersistentThreadModel running");
-
- // set thread local variable
- session.setPolicySession();
-
- var kieSession = session.getKieSession();
- long sleepTime = 2 * halfMaxSleepTime;
-
- // We want to continue, despite any exceptions that occur
- // while rules are fired.
-
- var cont = true;
- while (cont) {
-
- try {
- if (kieSession.fireAllRules() > 0) {
- // some rules fired -- reduce poll delay
- sleepTime = Math.max(minSleepTime, sleepTime / 2);
- } else {
- // no rules fired -- increase poll delay
- sleepTime = 2 * Math.min(halfMaxSleepTime, sleepTime);
- }
-
- } catch (Exception | LinkageError e) {
- logger.error("Exception during kieSession.fireAllRules", e);
- }
-
- try {
- if (stopped.await(sleepTime, TimeUnit.MILLISECONDS)) {
- cont = false;
- }
-
- } catch (InterruptedException e) {
- logger.error("startThread exception: ", e);
- Thread.currentThread().interrupt();
- cont = false;
- }
- }
-
- session.removePolicySession();
- logger.info("PersistentThreadModel completed");
- }
- }
-
- /* ============================================================ */
-
- /** DataSource-EntityManagerFactory pair. */
- private class DsEmf {
- private BasicDataSource bds;
- private EntityManagerFactory emf;
-
- /**
- * Makes an entity manager factory for the given data source.
- *
- * @param bds pooled data source
- */
- public DsEmf(BasicDataSource bds) {
- try {
- Map<String, Object> props = new HashMap<>();
- props.put(AvailableSettings.JPA_JTA_DATASOURCE, bds);
-
- this.bds = bds;
- this.emf = makeEntMgrFact(props);
-
- } catch (RuntimeException e) {
- closeDataSource();
- throw e;
- }
- }
-
- /** Closes the entity manager factory and the data source. */
- public void close() {
- try {
- emf.close();
-
- } catch (RuntimeException e) {
- closeDataSource();
- throw e;
- }
-
- closeDataSource();
- }
-
- /** Closes the data source only. */
- private void closeDataSource() {
- try {
- bds.close();
-
- } catch (SQLException e) {
- throw new PersistenceFeatureException(e);
- }
- }
- }
-
- private static class SingletonRegistry {
- private static final TransactionSynchronizationRegistry transreg =
- new com.arjuna.ats.internal.jta.transaction.arjunacore
- .TransactionSynchronizationRegistryImple();
-
- private SingletonRegistry() {
- super();
- }
- }
-
- /* Factory for various items. Methods can be overridden for junit testing. */
-
- /**
- * Gets the transaction manager.
- *
- * @return the transaction manager
- */
- protected TransactionManager getTransMgr() {
- return com.arjuna.ats.jta.TransactionManager.transactionManager();
- }
-
- /**
- * Gets the user transaction.
- *
- * @return the user transaction
- */
- protected UserTransaction getUserTrans() {
- return com.arjuna.ats.jta.UserTransaction.userTransaction();
- }
-
- /**
- * Gets the transaction synchronization registry.
- *
- * @return the transaction synchronization registry
- */
- protected TransactionSynchronizationRegistry getTransSyncReg() {
- return SingletonRegistry.transreg;
- }
-
- /**
- * Gets the KIE services.
- *
- * @return the KIE services
- */
- protected KieServices getKieServices() {
- return KieServices.Factory.get();
- }
-
- /**
- * Loads properties from a file.
- *
- * @param filenm name of the file to load
- * @return properties, as loaded from the file
- * @throws IOException if an error occurs reading from the file
- */
- protected Properties loadProperties(String filenm) throws IOException {
- return PropertyUtil.getProperties(filenm);
- }
-
- /**
- * Makes a Data Source.
- *
- * @param dsProps data source properties
- * @return a new data source
- */
- protected BasicDataSource makeDataSource(Properties dsProps) {
- try {
- return BasicDataSourceFactory.createDataSource(dsProps);
-
- } catch (Exception e) {
- throw new PersistenceFeatureException(e);
- }
- }
-
- /**
- * Makes a new JPA connector for drools sessions.
- *
- * @param emf entity manager factory
- * @return a new JPA connector for drools sessions
- */
- protected DroolsSessionConnector makeJpaConnector(EntityManagerFactory emf) {
- return new JpaDroolsSessionConnector(emf);
- }
-
- /**
- * Makes a new entity manager factory.
- *
- * @param props properties with which the factory should be configured
- * @return a new entity manager factory
- */
- protected EntityManagerFactory makeEntMgrFact(Map<String, Object> props) {
- return Persistence.createEntityManagerFactory("onapsessionsPU", props);
- }
-
- /**
- * Gets the policy controller associated with a given policy container.
- *
- * @param container container whose controller is to be retrieved
- * @return the container's controller
- */
- protected PolicyController getPolicyController(PolicyContainer container) {
- return PolicyControllerConstants.getFactory().get(container.getGroupId(), container.getArtifactId());
- }
-
- /**
- * Runtime exceptions generated by this class. Wraps exceptions generated by delegated operations,
- * particularly when they are not, themselves, Runtime exceptions.
- */
- public static class PersistenceFeatureException extends RuntimeException {
- private static final long serialVersionUID = 1L;
-
- /**
- * Constructor.
- * */
- public PersistenceFeatureException(Exception ex) {
- super(ex);
- }
- }
-}
diff --git a/feature-session-persistence/src/main/resources/META-INF/persistence.xml b/feature-session-persistence/src/main/resources/META-INF/persistence.xml
deleted file mode 100644
index 661803a5..00000000
--- a/feature-session-persistence/src/main/resources/META-INF/persistence.xml
+++ /dev/null
@@ -1,73 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- ============LICENSE_START=======================================================
- policy-core
- ================================================================================
- Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
- ================================================================================
- Licensed 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.
- ============LICENSE_END=========================================================
- -->
-
-<persistence version="2.1"
- xmlns="http://xmlns.jcp.org/xml/ns/persistence"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
-
- <persistence-unit name="onapsessionsPU"
- transaction-type="JTA">
- <!-- Used for drools session data access -->
- <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
- <class>org.onap.policy.drools.persistence.DroolsSessionEntity</class>
- <class>org.drools.persistence.info.SessionInfo</class>
- <class>org.drools.persistence.info.WorkItemInfo</class>
- <properties>
- <property name="hibernate.dialect"
- value="org.hibernate.dialect.MariaDBDialect" />
- <property name="hibernate.max_fetch_depth"
- value="3" />
- <property name="hibernate.hbm2ddl.auto"
- value="update" />
- <property name="hibernate.show_sql" value="false" />
- <property
- name="hibernate.transaction.factory_class"
- value="org.hibernate.transaction.JTATransactionFactory" />
- <property
- name="hibernate.transaction.manager_lookup_class"
- value="org.hibernate.transaction.JBossTransactionManagerLookup" />
- </properties>
- </persistence-unit>
-
- <persistence-unit name="schemaDroolsPU"
- transaction-type="RESOURCE_LOCAL">
- <!-- Limited use for generating the DB and schema files for drools DB - uses eclipselink for convenience -->
- <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
- <class>org.onap.policy.drools.persistence.DroolsSessionEntity</class>
- <class>org.drools.persistence.info.SessionInfo</class>
- <class>org.drools.persistence.info.WorkItemInfo</class>
- <properties>
- <property name="hibernate.dialect"
- value="org.hibernate.dialect.MariaDBDialect" />
- <property
- name="javax.persistence.schema-generation.scripts.action"
- value="drop-and-create" />
- <property
- name="javax.persistence.schema-generation.scripts.create-target"
- value="sql/generatedCreateDrools.ddl" />
- <property
- name="javax.persistence.schema-generation.scripts.drop-target"
- value="sql/generatedDropDrools.ddl" />
- </properties>
- </persistence-unit>
-
-</persistence>
diff --git a/feature-session-persistence/src/main/resources/META-INF/services/org.onap.policy.drools.core.PolicySessionFeatureApi b/feature-session-persistence/src/main/resources/META-INF/services/org.onap.policy.drools.core.PolicySessionFeatureApi
deleted file mode 100644
index 26366fd3..00000000
--- a/feature-session-persistence/src/main/resources/META-INF/services/org.onap.policy.drools.core.PolicySessionFeatureApi
+++ /dev/null
@@ -1 +0,0 @@
-org.onap.policy.drools.persistence.PersistenceFeature
diff --git a/feature-session-persistence/src/main/resources/META-INF/services/org.onap.policy.drools.features.PolicyEngineFeatureApi b/feature-session-persistence/src/main/resources/META-INF/services/org.onap.policy.drools.features.PolicyEngineFeatureApi
deleted file mode 100644
index 26366fd3..00000000
--- a/feature-session-persistence/src/main/resources/META-INF/services/org.onap.policy.drools.features.PolicyEngineFeatureApi
+++ /dev/null
@@ -1 +0,0 @@
-org.onap.policy.drools.persistence.PersistenceFeature
diff --git a/feature-session-persistence/src/test/java/org/onap/policy/drools/persistence/DroolsSessionEntityTest.java b/feature-session-persistence/src/test/java/org/onap/policy/drools/persistence/DroolsSessionEntityTest.java
deleted file mode 100644
index bd979162..00000000
--- a/feature-session-persistence/src/test/java/org/onap/policy/drools/persistence/DroolsSessionEntityTest.java
+++ /dev/null
@@ -1,179 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * feature-session-persistence
- * ================================================================================
- * Copyright (C) 2017-2018, 2020-2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.drools.persistence;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-
-import java.util.Date;
-import org.junit.Test;
-
-public class DroolsSessionEntityTest {
-
- @Test
- public void testHashCode() {
- DroolsSessionEntity entity = makeEnt("mynameA", 1);
-
- DroolsSessionEntity e2 = makeEnt("mynameA", 2);
-
- // session id is not part of hash code
- assertEquals(entity.hashCode(), e2.hashCode());
-
- // diff sess name
- e2 = makeEnt("mynameB", 1);
- assertNotEquals(entity.hashCode(), e2.hashCode());
- }
-
- /** Ensures that hashCode() functions as expected when the getXxx methods are overridden. */
- @Test
- public void testHashCode_Subclass() {
- DroolsSessionEntity entity = makeEnt2("mynameA", 1);
-
- DroolsSessionEntity e2 = makeEnt("mynameA", 2);
-
- // session id is not part of hash code
- assertEquals(entity.hashCode(), e2.hashCode());
-
- // diff sess name
- e2 = makeEnt("mynameB", 1);
- assertNotEquals(entity.hashCode(), e2.hashCode());
- }
-
- @Test
- public void testGetSessionName_testSetSessionName() {
- DroolsSessionEntity entity = makeEnt("mynameZ", 1);
-
- assertEquals("mynameZ", entity.getSessionName());
-
- entity.setSessionName("another");
- assertEquals("another", entity.getSessionName());
-
- // others unchanged
- assertEquals(1, entity.getSessionId());
- }
-
- @Test
- public void testGetSessionId_testSetSessionId() {
- DroolsSessionEntity entity = makeEnt("mynameA", 1);
-
- assertEquals(1, entity.getSessionId());
-
- entity.setSessionId(20);
- assertEquals(20, entity.getSessionId());
-
- // others unchanged
- assertEquals("mynameA", entity.getSessionName());
- }
-
- @Test
- public void testGetCreatedDate_testSetCreatedDate_testGetUpdatedDate_testSetUpdatedDate() {
- DroolsSessionEntity entity = new DroolsSessionEntity();
-
- Date crtdt = new Date(System.currentTimeMillis() - 100);
- entity.setCreatedDate(crtdt);
-
- Date updt = new Date(System.currentTimeMillis() - 200);
- entity.setUpdatedDate(updt);
-
- assertEquals(crtdt, entity.getCreatedDate());
- assertEquals(updt, entity.getUpdatedDate());
- }
-
- @Test
- public void testEqualsObject() {
- DroolsSessionEntity entity = makeEnt("mynameA", 1);
-
- // diff object type
- assertNotEquals(entity, "hello");
-
- // reflexive
- assertEquals(entity, entity);
-
- DroolsSessionEntity e2 = makeEnt("mynameA", 2);
-
- // session id is not part of hash code
- assertEquals(entity, e2);
- assertEquals(entity, e2);
-
- // diff sess name
- e2 = makeEnt("mynameB", 1);
- assertNotEquals(entity, e2);
- assertNotEquals(entity, e2);
- }
-
- /** Ensures that equals() functions as expected when the getXxx methods are overridden. */
- @Test
- public void testEqualsObject_Subclass() {
- DroolsSessionEntity entity = makeEnt2("mynameA", 1);
-
- // reflexive
- assertEquals(entity, entity);
-
- DroolsSessionEntity e2 = makeEnt("mynameA", 2);
-
- // session id is not part of hash code
- assertEquals(entity, e2);
- assertEquals(entity, e2);
-
- // diff sess name
- e2 = makeEnt("mynameB", 1);
- assertNotEquals(entity, e2);
- assertNotEquals(entity, e2);
- }
-
- @Test
- public void testToString() {
- DroolsSessionEntity entity = makeEnt("mynameA", 23);
-
- assertEquals("{name=mynameA, id=23}", entity.toString());
- }
-
- /**
- * Makes a session Entity. The parameters are stored into the Entity object via the setXxx
- * methods.
- *
- * @param sessnm session name
- * @param sessid session id
- * @return a new session Entity
- */
- private DroolsSessionEntity makeEnt(String sessnm, long sessid) {
-
- DroolsSessionEntity entity = new DroolsSessionEntity();
-
- entity.setSessionName(sessnm);
- entity.setSessionId(sessid);
-
- return entity;
- }
-
- /**
- * Makes a session Entity that overrides the getXxx methods. The parameters that are provided are
- * returned by the overridden methods, but they are <i>not</i> stored into the Entity object via
- * the setXxx methods.
- *
- * @param sessnm session name
- * @param sessid session id
- * @return a new session Entity
- */
- private DroolsSessionEntity makeEnt2(String sessnm, long sessid) {
- return new DroolsSessionEntity(sessnm, sessid);
- }
-}
diff --git a/feature-session-persistence/src/test/java/org/onap/policy/drools/persistence/EntityMgrTransTest.java b/feature-session-persistence/src/test/java/org/onap/policy/drools/persistence/EntityMgrTransTest.java
deleted file mode 100644
index fb0d1102..00000000
--- a/feature-session-persistence/src/test/java/org/onap/policy/drools/persistence/EntityMgrTransTest.java
+++ /dev/null
@@ -1,562 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * feature-session-persistence
- * ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.drools.persistence;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-import static org.mockito.Mockito.doThrow;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import java.util.HashMap;
-import java.util.Map;
-import javax.persistence.EntityManager;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.Persistence;
-import javax.transaction.HeuristicMixedException;
-import javax.transaction.HeuristicRollbackException;
-import javax.transaction.NotSupportedException;
-import javax.transaction.RollbackException;
-import javax.transaction.Status;
-import javax.transaction.SystemException;
-import javax.transaction.UserTransaction;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.onap.policy.drools.persistence.EntityMgrTrans.EntityMgrException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class EntityMgrTransTest {
-
- private static final Logger logger = LoggerFactory.getLogger(PersistenceFeatureTest.class);
-
- private static UserTransaction savetrans;
-
- private UserTransaction trans;
- private EntityManager mgr;
-
- /**
- * Configure properties for JTA.
- */
- @BeforeClass
- public static void setUpBeforeClass() {
- System.setProperty("com.arjuna.ats.arjuna.objectstore.objectStoreDir", "target/tm");
- System.setProperty("ObjectStoreEnvironmentBean.objectStoreDir", "target/tm");
-
- savetrans = EntityMgrTrans.getUserTrans();
- }
-
- @AfterClass
- public static void tearDownAfterClass() {
- EntityMgrTrans.setUserTrans(savetrans);
- }
-
- /**
- * Creates a mock transaction and entity manager. Resets the "userTrans" field of the
- * class under test.
- *
- * @throws Exception if an error occurs
- */
- @Before
- public void setUp() throws Exception {
- trans = mock(UserTransaction.class);
- mgr = mock(EntityManager.class);
-
- when(trans.getStatus()).thenReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE);
-
- EntityMgrTrans.setUserTrans(trans);
- }
-
- /**
- * Verifies that the constructor starts a transaction, but does not do anything extra
- * before being closed.
- *
- * @throws Exception if an error occurs
- */
- @Test
- public void testEntityMgrTrans_Inactive() throws Exception {
- final EntityMgrTrans emt = new EntityMgrTrans(mgr);
-
- // verify that transaction was started
- verify(trans).begin();
- verify(mgr).joinTransaction();
-
- // verify not closed, committed, or rolled back yet
- verify(trans, never()).commit();
- verify(trans, never()).rollback();
- verify(mgr, never()).close();
-
- emt.close();
- }
-
- /**
- * Verifies that the constructor does not start a transaction, because one is already
- * active.
- *
- * @throws Exception if an error occurs
- */
- @Test
- public void testEntityMgrTrans_Active() throws Exception {
-
- when(trans.getStatus()).thenReturn(Status.STATUS_ACTIVE);
-
- final EntityMgrTrans emt = new EntityMgrTrans(mgr);
-
- // verify that transaction was not re-started started
- verify(trans, never()).begin();
-
- // verify that transaction was joined
- verify(mgr).joinTransaction();
-
- // verify not closed, committed, or rolled back yet
- verify(trans, never()).commit();
- verify(trans, never()).rollback();
- verify(mgr, never()).close();
-
- emt.close();
- }
-
- @Test(expected = EntityMgrException.class)
- public void testEntityMgrTrans_RtEx() throws Exception {
-
- doThrow(new IllegalArgumentException("expected exception")).when(trans).begin();
-
- try (EntityMgrTrans emt = new EntityMgrTrans(mgr)) {
- // Empty
- }
- }
-
- @Test(expected = EntityMgrException.class)
- public void testEntityMgrTrans_NotSuppEx() throws Exception {
-
- doThrow(new NotSupportedException("expected exception")).when(trans).begin();
-
- try (EntityMgrTrans emt = new EntityMgrTrans(mgr)) {
- // Empty
- }
- }
-
- @Test(expected = EntityMgrException.class)
- public void testEntityMgrTrans_SysEx() throws Exception {
-
- doThrow(new SystemException("expected exception")).when(trans).begin();
-
- try (EntityMgrTrans emt = new EntityMgrTrans(mgr)) {
- // Empty
- }
- }
-
- /**
- * Verifies that the transaction is not rolled back, but the manager is closed when a
- * transaction is already active.
- */
- @Test
- public void testClose_Active() throws Exception {
- when(trans.getStatus()).thenReturn(Status.STATUS_ACTIVE);
-
- EntityMgrTrans emt = new EntityMgrTrans(mgr);
- emt.close();
-
- // closed and rolled back, but not committed
- verify(trans, never()).commit();
- verify(trans, never()).rollback();
- verify(mgr).close();
- }
-
- /**
- * Verifies that the transaction is rolled back and the manager is closed when a
- * transaction is begun by the constructor.
- */
- @Test
- public void testClose_Begun() throws Exception {
- EntityMgrTrans emt = new EntityMgrTrans(mgr);
-
- emt.close();
-
- // closed and rolled back, but not committed
- verify(trans, never()).commit();
- verify(trans).rollback();
- verify(mgr).close();
- }
-
- /**
- * Verifies that the manager is closed, but that the transaction is <i>not</i> rolled
- * back when no transaction is active.
- */
- @Test
- public void testClose_Inactive() throws Exception {
- when(trans.getStatus()).thenReturn(Status.STATUS_NO_TRANSACTION);
-
- EntityMgrTrans emt = new EntityMgrTrans(mgr);
-
- emt.close();
-
- // closed, but not committed or rolled back
- verify(mgr).close();
- verify(trans, never()).commit();
- verify(trans, never()).rollback();
- }
-
- @Test(expected = EntityMgrException.class)
- public void testClose_IllStateEx() throws Exception {
-
- doThrow(new IllegalStateException("expected exception")).when(trans).rollback();
-
- try (EntityMgrTrans emt = new EntityMgrTrans(mgr)) {
- // Empty
- }
- }
-
- @Test(expected = EntityMgrException.class)
- public void testClose_SecEx() throws Exception {
-
- doThrow(new SecurityException("expected exception")).when(trans).rollback();
-
- try (EntityMgrTrans emt = new EntityMgrTrans(mgr)) {
- // Empty
- }
- }
-
- @Test(expected = EntityMgrException.class)
- public void testClose_SysEx() throws Exception {
-
- doThrow(new SystemException("expected exception")).when(trans).rollback();
-
- try (EntityMgrTrans emt = new EntityMgrTrans(mgr)) {
- // Empty
- }
- }
-
- /**
- * Verifies that the manager is closed and the transaction rolled back when "try"
- * block exits normally and a transaction is active.
- */
- @Test
- public void testClose_TryWithoutExcept_Active() throws Exception {
- try (EntityMgrTrans emt = new EntityMgrTrans(mgr)) {
- // Empty
- }
-
- // closed and rolled back, but not committed
- verify(trans, never()).commit();
- verify(trans).rollback();
- verify(mgr).close();
- }
-
- /**
- * Verifies that the manager is closed, but that the transaction is <i>not</i> rolled
- * back when "try" block exits normally and no transaction is active.
- */
- @Test
- public void testClose_TryWithoutExcept_Inactive() throws Exception {
-
- when(trans.getStatus()).thenReturn(Status.STATUS_NO_TRANSACTION);
-
- try (EntityMgrTrans emt = new EntityMgrTrans(mgr)) {
- // Empty
- }
-
- // closed, but not rolled back or committed
- verify(trans, never()).commit();
- verify(trans, never()).rollback();
- verify(mgr).close();
- }
-
- /**
- * Verifies that the manager is closed and the transaction rolled back when "try"
- * block throws an exception and a transaction is active.
- */
- @Test
- public void testClose_TryWithExcept_Active() throws Exception {
- try {
- try (EntityMgrTrans emt = new EntityMgrTrans(mgr)) {
- throw new SystemException("expected exception");
- }
-
- } catch (Exception e) {
- logger.trace("expected exception", e);
- }
-
- // closed and rolled back, but not committed
- verify(trans, never()).commit();
- verify(trans).rollback();
- verify(mgr).close();
- }
-
- /**
- * Verifies that the manager is closed, but that the transaction is <i>not</i> rolled
- * back when "try" block throws an exception and no transaction is active.
- */
- @Test
- public void testClose_TryWithExcept_Inactive() throws Exception {
-
- when(trans.getStatus()).thenReturn(Status.STATUS_NO_TRANSACTION);
-
- try {
- try (EntityMgrTrans emt = new EntityMgrTrans(mgr)) {
- throw new SystemException("expected exception");
- }
-
- } catch (Exception e) {
- logger.trace("expected exception", e);
- }
-
- // closed, but not rolled back or committed
- verify(trans, never()).commit();
- verify(trans, never()).rollback();
- verify(mgr).close();
- }
-
- /**
- * Verifies that commit() only commits, and that the subsequent close() does not
- * re-commit.
- */
- @Test
- public void testCommit() throws Exception {
- EntityMgrTrans emt = new EntityMgrTrans(mgr);
-
- emt.commit();
-
- when(trans.getStatus()).thenReturn(Status.STATUS_COMMITTED);
-
- // committed, but not closed or rolled back
- verify(trans).commit();
- verify(trans, never()).rollback();
- verify(mgr, never()).close();
-
- // closed, but not re-committed
- emt.close();
-
- verify(trans, times(1)).commit();
- verify(mgr).close();
- }
-
- /**
- * Verifies that commit() does nothing, and that the subsequent close() does not
- * re-commit when a transaction is already active.
- */
- @Test
- public void testCommit_Active() throws Exception {
- when(trans.getStatus()).thenReturn(Status.STATUS_ACTIVE);
-
- EntityMgrTrans emt = new EntityMgrTrans(mgr);
-
- emt.commit();
-
- // nothing happened yet
- verify(trans, never()).commit();
- verify(trans, never()).rollback();
- verify(mgr, never()).close();
-
- // closed, but not re-committed
- emt.close();
-
- // still no commit or rollback
- verify(trans, never()).commit();
- verify(trans, never()).rollback();
- verify(mgr).close();
- }
-
- @Test(expected = EntityMgrException.class)
- public void testCommit_SecEx() throws Exception {
-
- doThrow(new SecurityException("expected exception")).when(trans).commit();
-
- try (EntityMgrTrans emt = new EntityMgrTrans(mgr)) {
- emt.commit();
- }
- }
-
- @Test(expected = EntityMgrException.class)
- public void testCommit_IllStateEx() throws Exception {
-
- doThrow(new IllegalStateException("expected exception")).when(trans).commit();
-
- try (EntityMgrTrans emt = new EntityMgrTrans(mgr)) {
- emt.commit();
- }
- }
-
- @Test(expected = EntityMgrException.class)
- public void testCommit_RbEx() throws Exception {
-
- doThrow(new RollbackException("expected exception")).when(trans).commit();
-
- try (EntityMgrTrans emt = new EntityMgrTrans(mgr)) {
- emt.commit();
- }
- }
-
- @Test(expected = EntityMgrException.class)
- public void testCommit_HmEx() throws Exception {
-
- doThrow(new HeuristicMixedException("expected exception")).when(trans).commit();
-
- try (EntityMgrTrans emt = new EntityMgrTrans(mgr)) {
- emt.commit();
- }
- }
-
- @Test(expected = EntityMgrException.class)
- public void testCommit_HrbEx() throws Exception {
-
- doThrow(new HeuristicRollbackException("expected exception")).when(trans).commit();
-
- try (EntityMgrTrans emt = new EntityMgrTrans(mgr)) {
- emt.commit();
- }
- }
-
- @Test(expected = EntityMgrException.class)
- public void testCommit_SysEx() throws Exception {
-
- doThrow(new SystemException("expected exception")).when(trans).commit();
-
- try (EntityMgrTrans emt = new EntityMgrTrans(mgr)) {
- emt.commit();
- }
- }
-
- /**
- * Verifies that rollback() only rolls back, and that the subsequent close() does not
- * re-roll back.
- */
- @Test
- public void testRollback() throws Exception {
- EntityMgrTrans emt = new EntityMgrTrans(mgr);
-
- emt.rollback();
-
- when(trans.getStatus()).thenReturn(Status.STATUS_ROLLEDBACK);
-
- // rolled back, but not closed or committed
- verify(trans, never()).commit();
- verify(trans).rollback();
- verify(mgr, never()).close();
-
- // closed, but not re-rolled back
- emt.close();
-
- // still no commit or rollback
- verify(trans, never()).commit();
- verify(trans).rollback();
- verify(mgr).close();
- }
-
- /**
- * Verifies that rollback() does nothing, and that the subsequent close() does not
- * re-roll back when a transaction is already active.
- */
- @Test
- public void testRollback_Active() throws Exception {
- when(trans.getStatus()).thenReturn(Status.STATUS_ACTIVE);
- EntityMgrTrans emt = new EntityMgrTrans(mgr);
-
- emt.rollback();
-
- // nothing happens
- verify(trans, never()).commit();
- verify(trans, never()).rollback();
- verify(mgr, never()).close();
-
- emt.close();
-
- // still no commit or rollback
- verify(trans, never()).commit();
- verify(trans, never()).rollback();
- verify(mgr).close();
- }
-
- @Test(expected = EntityMgrException.class)
- public void testRollback_IllStateEx() throws Exception {
-
- doThrow(new IllegalStateException("expected exception")).when(trans).rollback();
-
- try (EntityMgrTrans emt = new EntityMgrTrans(mgr)) {
- emt.rollback();
- }
- }
-
- @Test(expected = EntityMgrException.class)
- public void testRollback_SecEx() throws Exception {
-
- doThrow(new SecurityException("expected exception")).when(trans).rollback();
-
- try (EntityMgrTrans emt = new EntityMgrTrans(mgr)) {
- emt.rollback();
- }
- }
-
- @Test(expected = EntityMgrException.class)
- public void testRollback_SysEx() throws Exception {
-
- doThrow(new SystemException("expected exception")).when(trans).rollback();
-
- try (EntityMgrTrans emt = new EntityMgrTrans(mgr)) {
- emt.rollback();
- }
- }
-
- @Test
- public void testEntityMgrException() {
- SecurityException secex = new SecurityException("expected exception");
- EntityMgrException ex = new EntityMgrException(secex);
-
- assertEquals(secex, ex.getCause());
-
- }
-
- /**
- * Tests using real (i.e., not mocked) Persistence classes.
- */
- @Test
- public void testReal() {
- EntityMgrTrans.setUserTrans(savetrans);
-
- Map<String, Object> propMap = new HashMap<>();
-
- propMap.put("javax.persistence.jdbc.driver", "org.h2.Driver");
- propMap.put("javax.persistence.jdbc.url", "jdbc:h2:mem:EntityMgrTransTest");
-
- EntityManagerFactory emf = Persistence.createEntityManagerFactory("junitDroolsSessionEntityPU", propMap);
-
- try (EntityMgrTrans trans1 = new EntityMgrTrans(emf.createEntityManager())) {
-
- // nest a transaction - should still be OK
-
- try (EntityMgrTrans trans2 = new EntityMgrTrans(emf.createEntityManager())) {
- // Empty
- }
-
- } catch (Exception e) {
- logger.info("persistence error", e);
- emf.close();
- fail("persistence error");
- }
-
- emf.close();
- }
-}
diff --git a/feature-session-persistence/src/test/java/org/onap/policy/drools/persistence/GenSchema.java b/feature-session-persistence/src/test/java/org/onap/policy/drools/persistence/GenSchema.java
deleted file mode 100644
index 31fcfa84..00000000
--- a/feature-session-persistence/src/test/java/org/onap/policy/drools/persistence/GenSchema.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * feature-session-persistence
- * ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.drools.persistence;
-
-import java.util.HashMap;
-import java.util.Map;
-import javax.persistence.Persistence;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/** Generates the schema DDL files. */
-public class GenSchema {
-
- private static final Logger logger = LoggerFactory.getLogger(PersistenceFeatureTest.class);
-
- /**
- * Opens the EMF, which generates the schema, as a side-effect.
- *
- * @throws Exception exception
- */
- private GenSchema() throws Exception {
- Map<String, Object> propMap = new HashMap<>();
-
- propMap.put("javax.persistence.jdbc.driver", "org.h2.Driver");
- propMap.put("javax.persistence.jdbc.url", "jdbc:h2:mem:JpaDroolsSessionConnectorTest");
-
- Persistence.createEntityManagerFactory("schemaDroolsPU", propMap).close();
- }
-
- /**
- * This is is provided as a utility for producing a basic ddl schema file in the sql directory.
- */
- public static void main(String[] args) {
- try {
- new GenSchema();
-
- } catch (Exception e) {
- logger.error("failed to generate schema", e);
- }
- }
-}
diff --git a/feature-session-persistence/src/test/java/org/onap/policy/drools/persistence/JpaDroolsSessionConnectorTest.java b/feature-session-persistence/src/test/java/org/onap/policy/drools/persistence/JpaDroolsSessionConnectorTest.java
deleted file mode 100644
index c1fe08a1..00000000
--- a/feature-session-persistence/src/test/java/org/onap/policy/drools/persistence/JpaDroolsSessionConnectorTest.java
+++ /dev/null
@@ -1,197 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * feature-session-persistence
- * ================================================================================
- * Copyright (C) 2017-2018, 2020 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.drools.persistence;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.doThrow;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-import java.util.HashMap;
-import java.util.Map;
-import javax.persistence.EntityManager;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.EntityTransaction;
-import javax.persistence.Persistence;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-public class JpaDroolsSessionConnectorTest {
-
- private EntityManagerFactory emf;
- private JpaDroolsSessionConnector conn;
-
- @BeforeClass
- public static void setUpBeforeClass() {
- System.setProperty("com.arjuna.ats.arjuna.objectstore.objectStoreDir", "target/tm");
- System.setProperty("ObjectStoreEnvironmentBean.objectStoreDir", "target/tm");
- }
-
- /**
- * Setup.
- *
- * @throws Exception exception
- */
- @Before
- public void setUp() throws Exception {
- Map<String, Object> propMap = new HashMap<>();
-
- propMap.put("javax.persistence.jdbc.driver", "org.h2.Driver");
- propMap.put("javax.persistence.jdbc.url", "jdbc:h2:mem:JpaDroolsSessionConnectorTest");
-
- emf = Persistence.createEntityManagerFactory("junitDroolsSessionEntityPU", propMap);
-
- conn = new JpaDroolsSessionConnector(emf);
- }
-
- @After
- public void tearDown() {
- // this will cause the memory db to be dropped
- emf.close();
- }
-
- @Test
- public void testGet() {
- /*
- * Load up the DB with some data.
- */
-
- addSession("nameA", 10);
- addSession("nameY", 20);
-
- /*
- * Now test the functionality.
- */
-
- // not found
- assertNull(conn.get("unknown"));
-
- assertEquals("{name=nameA, id=10}", conn.get("nameA").toString());
-
- assertEquals("{name=nameY, id=20}", conn.get("nameY").toString());
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testGet_NewEx() {
- EntityManagerFactory emf = mock(EntityManagerFactory.class);
- EntityManager em = mock(EntityManager.class);
-
- when(emf.createEntityManager()).thenReturn(em);
- when(em.find(any(), any())).thenThrow(new IllegalArgumentException("expected exception"));
-
- conn = new JpaDroolsSessionConnector(emf);
- conn.get("xyz");
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testGet_FindEx() {
- EntityManagerFactory emf = mock(EntityManagerFactory.class);
- EntityManager em = mock(EntityManager.class);
- EntityTransaction tr = mock(EntityTransaction.class);
-
- when(emf.createEntityManager()).thenReturn(em);
- when(em.getTransaction()).thenReturn(tr);
- when(em.find(any(), any())).thenThrow(new IllegalArgumentException("expected exception"));
-
- new JpaDroolsSessionConnector(emf).get("xyz");
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testGet_FindEx_CloseEx() {
- EntityManagerFactory emf = mock(EntityManagerFactory.class);
- EntityManager em = mock(EntityManager.class);
- EntityTransaction tr = mock(EntityTransaction.class);
-
- when(emf.createEntityManager()).thenReturn(em);
- when(em.getTransaction()).thenReturn(tr);
- when(em.find(any(), any())).thenThrow(new IllegalArgumentException("expected exception"));
- doThrow(new IllegalArgumentException("expected exception #2")).when(em).close();
-
- new JpaDroolsSessionConnector(emf).get("xyz");
- }
-
- @Test
- public void testReplace_Existing() {
- addSession("nameA", 10);
-
- DroolsSessionEntity sess = new DroolsSessionEntity("nameA", 30);
-
- conn.replace(sess);
-
- // id should be changed
- assertEquals(sess.toString(), conn.get("nameA").toString());
- }
-
- @Test
- public void testReplace_New() {
- DroolsSessionEntity sess = new DroolsSessionEntity("nameA", 30);
-
- conn.replace(sess);
-
- assertEquals(sess.toString(), conn.get("nameA").toString());
- }
-
- @Test
- public void testAdd() {
- DroolsSessionEntity sess = new DroolsSessionEntity("nameA", 30);
-
- conn.replace(sess);
-
- assertEquals(sess.toString(), conn.get("nameA").toString());
- }
-
- @Test
- public void testUpdate() {
- addSession("nameA", 10);
-
- DroolsSessionEntity sess = new DroolsSessionEntity("nameA", 30);
-
- conn.replace(sess);
-
- // id should be changed
- assertEquals("{name=nameA, id=30}", conn.get("nameA").toString());
- }
-
- /**
- * Adds a session to the DB.
- *
- * @param sessnm session name
- * @param sessid session id
- */
- private void addSession(String sessnm, int sessid) {
- EntityManager em = emf.createEntityManager();
-
- try (EntityMgrTrans trans = new EntityMgrTrans(em)) {
- DroolsSessionEntity ent = new DroolsSessionEntity();
-
- ent.setSessionName(sessnm);
- ent.setSessionId(sessid);
-
- em.persist(ent);
-
- trans.commit();
- }
- }
-}
diff --git a/feature-session-persistence/src/test/java/org/onap/policy/drools/persistence/PersistenceFeatureTest.java b/feature-session-persistence/src/test/java/org/onap/policy/drools/persistence/PersistenceFeatureTest.java
deleted file mode 100644
index 4450b8c8..00000000
--- a/feature-session-persistence/src/test/java/org/onap/policy/drools/persistence/PersistenceFeatureTest.java
+++ /dev/null
@@ -1,1392 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * feature-session-persistence
- * ================================================================================
- * Copyright (C) 2017-2018, 2020-2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.drools.persistence;
-
-import static org.assertj.core.api.Assertions.assertThatCode;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyLong;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.Mockito.doThrow;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.IOException;
-import java.sql.Connection;
-import java.sql.DriverManager;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Timestamp;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import javax.persistence.EntityManager;
-import javax.persistence.EntityManagerFactory;
-import javax.transaction.TransactionManager;
-import javax.transaction.TransactionSynchronizationRegistry;
-import javax.transaction.UserTransaction;
-import org.apache.commons.dbcp2.BasicDataSource;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.kie.api.KieBase;
-import org.kie.api.KieServices;
-import org.kie.api.persistence.jpa.KieStoreServices;
-import org.kie.api.runtime.Environment;
-import org.kie.api.runtime.EnvironmentName;
-import org.kie.api.runtime.KieContainer;
-import org.kie.api.runtime.KieSession;
-import org.kie.api.runtime.KieSessionConfiguration;
-import org.mockito.ArgumentCaptor;
-import org.onap.policy.drools.core.PolicyContainer;
-import org.onap.policy.drools.core.PolicySession;
-import org.onap.policy.drools.core.PolicySession.ThreadModel;
-import org.onap.policy.drools.persistence.PersistenceFeature.PersistenceFeatureException;
-import org.onap.policy.drools.persistence.PersistenceFeature.PersistentThreadModel;
-import org.onap.policy.drools.system.PolicyController;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class PersistenceFeatureTest {
-
- private static final String MY_KIE_BASE = "mybase";
-
- private static final String MY_SESS_NAME = "myname";
-
- private static final String MISSING_EXCEPTION = "missing exception";
-
- private static final String EXPECTED = "expected exception";
-
- private static final Logger logger = LoggerFactory.getLogger(PersistenceFeatureTest.class);
-
- private static final String JDBC_DRIVER = "fake.driver";
- private static final String JDBC_URL = "fake.url";
- private static final String JDBC_USER = "fake.user";
- private static final String JDBC_PASSWD = "fake.password";
- private static final String JTA_OSDIR = "target";
- private static final String SRC_TEST_RESOURCES = "src/test/resources";
-
- private static Properties stdprops;
-
- private JpaDroolsSessionConnector jpa;
- private DroolsSession sess;
- private KieSession kiesess;
- private BasicDataSource bds;
- private EntityManagerFactory emf;
- private Connection conn;
- private Properties props;
- private KieServices kiesvc;
- private Environment kieenv;
- private KieSessionConfiguration kiecfg;
- private KieBase kiebase;
- private KieStoreServices kiestore;
- private TransactionManager transmgr;
- private UserTransaction usertrans;
- private TransactionSynchronizationRegistry transreg;
- private PolicyController polctlr;
- private PolicyContainer polcont;
- private PolicySession polsess;
- private int emfCount;
- private int jpaCount;
- private String propName;
-
- private PersistenceFeature feat;
-
- /**
- * Setup before class.
- *
- * @throws Exception exception
- */
- @BeforeClass
- public static void setUpBeforeClass() throws Exception {
- stdprops = new Properties();
-
- stdprops.put(DroolsPersistenceProperties.DB_DRIVER, JDBC_DRIVER);
- stdprops.put(DroolsPersistenceProperties.DB_URL, JDBC_URL);
- stdprops.put(DroolsPersistenceProperties.DB_USER, JDBC_USER);
- stdprops.put(DroolsPersistenceProperties.DB_PWD, JDBC_PASSWD);
- stdprops.put(DroolsPersistenceProperties.JTA_OBJECTSTORE_DIR, JTA_OSDIR);
- stdprops.put(DroolsPersistenceProperties.DB_SESSIONINFO_TIMEOUT, "50");
-
- System.setProperty("com.arjuna.ats.arjuna.objectstore.objectStoreDir", "target/tm");
- System.setProperty("ObjectStoreEnvironmentBean.objectStoreDir", "target/tm");
- }
-
- /**
- * Setup.
- *
- * @throws Exception exception
- */
- @Before
- public void setUp() throws Exception {
- jpa = mock(JpaDroolsSessionConnector.class);
- sess = mock(DroolsSession.class);
- bds = mock(BasicDataSource.class);
- emf = mock(EntityManagerFactory.class);
- kiesess = mock(KieSession.class);
- conn = null;
- props = new Properties();
- kiesvc = mock(KieServices.class);
- kieenv = mock(Environment.class);
- kiecfg = mock(KieSessionConfiguration.class);
- kiebase = mock(KieBase.class);
- kiestore = mock(KieStoreServices.class);
- transmgr = mock(TransactionManager.class);
- usertrans = mock(UserTransaction.class);
- transreg = mock(TransactionSynchronizationRegistry.class);
- polcont = mock(PolicyContainer.class);
- polctlr = mock(PolicyController.class);
- polsess = mock(PolicySession.class);
- emfCount = 0;
- jpaCount = 0;
- propName = null;
-
- feat = new PersistenceFeatureImpl();
-
- props.putAll(stdprops);
-
- System.setProperty("com.arjuna.ats.arjuna.objectstore.objectStoreDir", "target/tm");
- System.setProperty("ObjectStoreEnvironmentBean.objectStoreDir", "target/tm");
-
- when(kiesvc.newEnvironment()).thenReturn(kieenv);
- when(kiesvc.getStoreServices()).thenReturn(kiestore);
- when(kiesvc.newKieSessionConfiguration()).thenReturn(kiecfg);
-
- KieContainer kiecont = mock(KieContainer.class);
- when(polcont.getKieContainer()).thenReturn(kiecont);
-
- when(polsess.getContainer()).thenReturn(polcont);
-
- when(kiecont.getKieBase(anyString())).thenReturn(kiebase);
- }
-
- /**
- * Tear down.
- */
- @After
- public void tearDown() {
- // this will cause the in-memory test DB to be dropped
- if (conn != null) {
- try {
- conn.close();
- } catch (SQLException e) {
- logger.warn("failed to close connection", e);
- }
- }
-
- if (emf != null) {
- try {
- emf.close();
- } catch (IllegalArgumentException e) {
- logger.trace("ignored exception", e);
- }
- }
- }
-
- @Test
- public void testGetContainerAdjunct_New() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, true);
- mockDbConn(5);
-
- // force getContainerAdjunct() to be invoked
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
-
- ArgumentCaptor<PersistenceFeature.ContainerAdjunct> adjcap =
- ArgumentCaptor.forClass(PersistenceFeature.ContainerAdjunct.class);
-
- verify(polcont, times(1)).setAdjunct(any(), adjcap.capture());
-
- assertNotNull(adjcap.getValue());
- }
-
- @Test
- public void testGetContainerAdjunct_Existing() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, true);
- mockDbConn(5);
-
- // force getContainerAdjunct() to be invoked
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
-
- ArgumentCaptor<PersistenceFeature.ContainerAdjunct> adjcap =
- ArgumentCaptor.forClass(PersistenceFeature.ContainerAdjunct.class);
-
- verify(polcont, times(1)).setAdjunct(any(), adjcap.capture());
-
- // return adjunct on next call
- when(polcont.getAdjunct(any())).thenReturn(adjcap.getValue());
-
- // force getContainerAdjunct() to be invoked again
- setUpKie("myname2", 999L, true);
- mockDbConn(5);
- feat.activatePolicySession(polcont, "myname2", MY_KIE_BASE);
-
- // ensure it isn't invoked again
- verify(polcont, times(1)).setAdjunct(any(), any());
- }
-
- @Test
- public void testGetContainerAdjunct_WrongType() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, true);
- mockDbConn(5);
-
- // return false adjunct on next call
- when(polcont.getAdjunct(any())).thenReturn("not-a-real-adjunct");
-
- // force getContainerAdjunct() to be invoked
- setUpKie("myname2", 999L, true);
- mockDbConn(5);
- feat.activatePolicySession(polcont, "myname2", MY_KIE_BASE);
-
- ArgumentCaptor<PersistenceFeature.ContainerAdjunct> adjcap =
- ArgumentCaptor.forClass(PersistenceFeature.ContainerAdjunct.class);
-
- verify(polcont, times(1)).setAdjunct(any(), adjcap.capture());
-
- assertNotNull(adjcap.getValue());
- }
-
- @Test
- public void testGetSequenceNumber() {
- assertEquals(1, feat.getSequenceNumber());
- }
-
- @Test
- public void testGlobalInit() throws Exception {
-
- feat.globalInit(null, SRC_TEST_RESOURCES);
-
- // verify that various factory methods were invoked
- assertEquals("src/test/resources/feature-session-persistence.properties", propName);
- }
-
- @Test(expected = NullPointerException.class)
- public void testGlobalInitIoEx() throws Exception {
-
- feat = new PersistenceFeatureImpl() {
- @Override
- protected Properties loadProperties(String filenm) throws IOException {
- throw new IOException(EXPECTED);
- }
- };
-
- feat.globalInit(null, SRC_TEST_RESOURCES);
- }
-
- @Test
- public void testActivatePolicySession() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, true);
- final PreparedStatement ps = mockDbConn(5);
-
- feat.beforeActivate(null);
-
- KieSession session = feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
-
- verify(kiestore).loadKieSession(anyLong(), any(), any(), any());
- verify(kiestore, never()).newKieSession(any(), any(), any());
-
- assertEquals(session, kiesess);
-
- verify(ps).executeUpdate();
-
- verify(kieenv, times(4)).set(anyString(), any());
-
- verify(jpa).get(MY_SESS_NAME);
- verify(jpa).replace(any());
- }
-
- @Test
- public void testActivatePolicySession_NoPersistence() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, true);
- final PreparedStatement ps = mockDbConn(5);
-
- props.remove("persistence.type");
-
- feat.beforeStart(null);
-
- assertNull(feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE));
-
- verify(ps, never()).executeUpdate();
- verify(kiestore, never()).loadKieSession(anyLong(), any(), any(), any());
- verify(kiestore, never()).newKieSession(any(), any(), any());
- }
-
- /** Verifies that a new KIE session is created when there is no existing session entity. */
- @Test
- public void testActivatePolicySession_New() throws Exception {
- setUpKie("noName", 999L, true);
- mockDbConn(5);
-
- KieSession session = feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
-
- verify(kiestore, never()).loadKieSession(anyLong(), any(), any(), any());
- verify(kiestore).newKieSession(any(), any(), any());
-
- assertEquals(session, kiesess);
-
- verify(kieenv, times(4)).set(anyString(), any());
-
- verify(jpa).get(MY_SESS_NAME);
- verify(jpa).replace(any());
- }
-
- /**
- * Verifies that a new KIE session is created when there KIE fails to load an existing session.
- */
- @Test
- public void testActivatePolicySession_LoadFailed() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, false);
- mockDbConn(5);
-
- KieSession session = feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
-
- verify(kiestore).loadKieSession(anyLong(), any(), any(), any());
- verify(kiestore).newKieSession(any(), any(), any());
-
- assertEquals(session, kiesess);
-
- verify(kieenv, times(4)).set(anyString(), any());
-
- verify(jpa).get(MY_SESS_NAME);
-
- ArgumentCaptor<DroolsSession> drools = ArgumentCaptor.forClass(DroolsSession.class);
- verify(jpa).replace(drools.capture());
-
- assertEquals(MY_SESS_NAME, drools.getValue().getSessionName());
- assertEquals(100L, drools.getValue().getSessionId());
- }
-
- @Test
- public void testLoadDataSource() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, false);
- mockDbConn(5);
-
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
-
- assertEquals(1, emfCount);
- }
-
- @Test
- public void testConfigureSysProps() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, false);
- mockDbConn(5);
-
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
-
- assertEquals("60", System.getProperty("com.arjuna.ats.arjuna.coordinator.defaultTimeout"));
- assertEquals(JTA_OSDIR, System.getProperty("com.arjuna.ats.arjuna.objectstore.objectStoreDir"));
- assertEquals(JTA_OSDIR, System.getProperty("ObjectStoreEnvironmentBean.objectStoreDir"));
- }
-
- @Test
- public void testConfigureKieEnv() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, false);
- mockDbConn(5);
-
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
-
- verify(kieenv, times(4)).set(any(), any());
-
- verify(kieenv).set(EnvironmentName.ENTITY_MANAGER_FACTORY, emf);
- verify(kieenv).set(EnvironmentName.TRANSACTION, usertrans);
- verify(kieenv).set(EnvironmentName.TRANSACTION_MANAGER, transmgr);
- verify(kieenv).set(EnvironmentName.TRANSACTION_SYNCHRONIZATION_REGISTRY, transreg);
-
- verify(bds, times(1)).close();
- }
-
- @Test
- public void testConfigureKieEnv_RtEx() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, false);
- mockDbConn(5);
-
- feat = new PersistenceFeatureMockDb() {
- @Override
- protected UserTransaction getUserTrans() {
- throw new IllegalArgumentException(EXPECTED);
- }
- };
-
- feat.globalInit(null, SRC_TEST_RESOURCES);
-
- try {
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
- fail(MISSING_EXCEPTION);
-
- } catch (IllegalArgumentException ex) {
- logger.trace(EXPECTED, ex);
- }
-
- verify(bds, times(2)).close();
- }
-
- @Test
- public void testLoadKieSession() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, true);
- mockDbConn(5);
-
- KieSession session = feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
-
- verify(kiestore).loadKieSession(999L, kiebase, kiecfg, kieenv);
- verify(kiestore, never()).newKieSession(any(), any(), any());
-
- assertEquals(session, kiesess);
- }
-
- /*
- * Verifies that loadKieSession() returns null (thus causing newKieSession()
- * to be called) when an Exception occurs.
- */
- @Test
- public void testLoadKieSession_Ex() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, false);
- mockDbConn(5);
-
- when(kiestore.loadKieSession(anyLong(), any(), any(), any()))
- .thenThrow(new IllegalArgumentException(EXPECTED));
-
- KieSession session = feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
-
- verify(kiestore).loadKieSession(anyLong(), any(), any(), any());
- verify(kiestore).newKieSession(any(), any(), any());
-
- assertEquals(session, kiesess);
- }
-
- @Test
- public void testNewKieSession() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, false);
- mockDbConn(5);
-
- KieSession session = feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
-
- verify(kiestore).newKieSession(kiebase, null, kieenv);
-
- assertEquals(session, kiesess);
- }
-
- @Test
- public void testLoadDataSource_DiffSession() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, false);
- mockDbConn(5);
-
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
-
- ArgumentCaptor<PersistenceFeature.ContainerAdjunct> adjcap =
- ArgumentCaptor.forClass(PersistenceFeature.ContainerAdjunct.class);
-
- verify(polcont).setAdjunct(any(), adjcap.capture());
-
- when(polcont.getAdjunct(any())).thenReturn(adjcap.getValue());
-
- setUpKie("myname2", 999L, false);
- mockDbConn(5);
-
- // invoke it again
- feat.activatePolicySession(polcont, "myname2", MY_KIE_BASE);
-
- assertEquals(2, emfCount);
- }
-
- @Test
- public void testSelectThreadModel_Persistent() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, true);
-
- ThreadModel model = feat.selectThreadModel(polsess);
- assertNotNull(model);
- assertTrue(model instanceof PersistentThreadModel);
- }
-
- @Test
- public void testSelectThreadModel_NotPersistent() throws Exception {
- assertNull(feat.selectThreadModel(polsess));
- }
-
- @Test
- public void testSelectThreadModel_Start__Run_Update_Stop() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, true);
-
- ThreadModel model = feat.selectThreadModel(polsess);
- assertNotNull(model);
- assertTrue(model instanceof PersistentThreadModel);
-
- when(polsess.getKieSession()).thenReturn(kiesess);
-
- model.start();
- new CountDownLatch(1).await(10, TimeUnit.MILLISECONDS);
- model.updated();
- model.stop();
- }
-
- @Test
- public void testDisposeKieSession() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, false);
- mockDbConn(5);
-
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
-
- verify(emf, never()).close();
-
- final ArgumentCaptor<PersistenceFeature.ContainerAdjunct> adjcap =
- ArgumentCaptor.forClass(PersistenceFeature.ContainerAdjunct.class);
-
- verify(polcont).setAdjunct(any(), adjcap.capture());
-
- when(polcont.getAdjunct(any())).thenReturn(adjcap.getValue());
-
- feat.disposeKieSession(polsess);
-
- // call twice to ensure it isn't re-closed
- feat.disposeKieSession(polsess);
-
- verify(emf, times(1)).close();
- }
-
- @Test
- public void testDisposeKieSession_NoAdjunct() throws Exception {
- feat.globalInit(null, SRC_TEST_RESOURCES);
-
- assertThatCode(() -> feat.disposeKieSession(polsess)).doesNotThrowAnyException();
- }
-
- @Test
- public void testDisposeKieSession_NoPersistence() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, false);
- mockDbConn(5);
-
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
-
- verify(emf, never()).close();
-
- final ArgumentCaptor<PersistenceFeature.ContainerAdjunct> adjcap =
- ArgumentCaptor.forClass(PersistenceFeature.ContainerAdjunct.class);
-
- verify(polcont).setAdjunct(any(), adjcap.capture());
-
- when(polcont.getAdjunct(any())).thenReturn(adjcap.getValue());
-
- // specify a session that was never loaded
- when(polsess.getName()).thenReturn("anotherName");
-
- feat.disposeKieSession(polsess);
-
- verify(emf, never()).close();
- }
-
- @Test
- public void testDestroyKieSession() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, false);
- mockDbConn(5);
-
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
-
- verify(emf, never()).close();
-
- final ArgumentCaptor<PersistenceFeature.ContainerAdjunct> adjcap =
- ArgumentCaptor.forClass(PersistenceFeature.ContainerAdjunct.class);
-
- verify(polcont).setAdjunct(any(), adjcap.capture());
-
- when(polcont.getAdjunct(any())).thenReturn(adjcap.getValue());
-
- feat.destroyKieSession(polsess);
-
- // call twice to ensure it isn't re-closed
- feat.destroyKieSession(polsess);
-
- verify(emf, times(1)).close();
- }
-
- @Test
- public void testDestroyKieSession_NoAdjunct() throws Exception {
- feat.globalInit(null, SRC_TEST_RESOURCES);
-
- assertThatCode(() -> feat.destroyKieSession(polsess)).doesNotThrowAnyException();
- }
-
- @Test
- public void testDestroyKieSession_NoPersistence() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, false);
- mockDbConn(5);
-
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
-
- verify(emf, never()).close();
-
- final ArgumentCaptor<PersistenceFeature.ContainerAdjunct> adjcap =
- ArgumentCaptor.forClass(PersistenceFeature.ContainerAdjunct.class);
-
- verify(polcont).setAdjunct(any(), adjcap.capture());
-
- when(polcont.getAdjunct(any())).thenReturn(adjcap.getValue());
-
- // specify a session that was never loaded
- when(polsess.getName()).thenReturn("anotherName");
-
- feat.destroyKieSession(polsess);
-
- verify(emf, never()).close();
- }
-
- @Test
- public void testAfterStart() {
- assertFalse(feat.afterStart(null));
- }
-
- @Test
- public void testBeforeStart() {
- assertFalse(feat.beforeStart(null));
- }
-
- @Test
- public void testBeforeShutdown() {
- assertFalse(feat.beforeShutdown(null));
- }
-
- @Test
- public void testAfterShutdown() {
- assertFalse(feat.afterShutdown(null));
- }
-
- @Test
- public void testBeforeConfigure() {
- assertFalse(feat.beforeConfigure(null, null));
- }
-
- @Test
- public void testAfterConfigure() {
- assertFalse(feat.afterConfigure(null));
- }
-
- @Test
- public void testBeforeActivate() {
- assertFalse(feat.beforeActivate(null));
- }
-
- @Test
- public void testAfterActivate() {
- assertFalse(feat.afterActivate(null));
- }
-
- @Test
- public void testBeforeDeactivate() {
- assertFalse(feat.beforeDeactivate(null));
- }
-
- @Test
- public void testAfterDeactivate() {
- assertFalse(feat.afterDeactivate(null));
- }
-
- @Test
- public void testBeforeStop() {
- assertFalse(feat.beforeStop(null));
- }
-
- @Test
- public void testAfterStop() {
- assertFalse(feat.afterStop(null));
- }
-
- @Test
- public void testBeforeLock() {
- assertFalse(feat.beforeLock(null));
- }
-
- @Test
- public void testAfterLock() {
- assertFalse(feat.afterLock(null));
- }
-
- @Test
- public void testBeforeUnlock() {
- assertFalse(feat.beforeUnlock(null));
- }
-
- @Test
- public void testAfterUnlock() {
- assertFalse(feat.afterUnlock(null));
- }
-
- @Test
- public void testGetPersistenceTimeout_Valid() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, true);
- final PreparedStatement statement = mockDbConn(5);
-
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
-
- verify(statement).executeUpdate();
- }
-
- @Test
- public void testGetPersistenceTimeout_Missing() throws Exception {
-
- props.remove(DroolsPersistenceProperties.DB_SESSIONINFO_TIMEOUT);
-
- setUpKie(MY_SESS_NAME, 999L, true);
- final PreparedStatement statement = mockDbConn(0);
-
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
-
- verify(statement, never()).executeUpdate();
- }
-
- @Test
- public void testGetPersistenceTimeout_Invalid() throws Exception {
- props.setProperty(DroolsPersistenceProperties.DB_SESSIONINFO_TIMEOUT, "abc");
-
- setUpKie(MY_SESS_NAME, 999L, true);
- final PreparedStatement s = mockDbConn(0);
-
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
-
- verify(s, never()).executeUpdate();
- }
-
- @Test
- public void testCleanUpSessionInfo() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, true);
-
- // use a real DB so we can verify that the "delete" works correctly
- feat = new PartialFeature();
-
- makeSessionInfoTbl(20000);
-
- // create mock entity manager for use by JPA connector
- EntityManager em = mock(EntityManager.class);
- when(emf.createEntityManager()).thenReturn(em);
-
- feat.globalInit(null, SRC_TEST_RESOURCES);
-
- feat.beforeStart(null);
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
-
- assertEquals("[1, 4, 5]", getSessions().toString());
- }
-
- @Test
- public void testCleanUpSessionInfo_WithBeforeStart() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, true);
- final PreparedStatement statement = mockDbConn(0);
-
- // reset
- feat.beforeStart(null);
-
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
- verify(statement, times(1)).executeUpdate();
-
- // should not clean-up again
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
- verify(statement, times(1)).executeUpdate();
-
- // reset
- feat.beforeStart(null);
-
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
- verify(statement, times(2)).executeUpdate();
-
- // should not clean-up again
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
- verify(statement, times(2)).executeUpdate();
- }
-
- @Test
- public void testCleanUpSessionInfo_WithBeforeActivate() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, true);
- final PreparedStatement statement = mockDbConn(0);
-
- // reset
- feat.beforeActivate(null);
-
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
- verify(statement, times(1)).executeUpdate();
-
- // should not clean-up again
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
- verify(statement, times(1)).executeUpdate();
-
- // reset
- feat.beforeActivate(null);
-
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
- verify(statement, times(2)).executeUpdate();
-
- // should not clean-up again
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
- verify(statement, times(2)).executeUpdate();
- }
-
- @Test
- public void testCleanUpSessionInfo_NoTimeout() throws Exception {
-
- props.remove(DroolsPersistenceProperties.DB_SESSIONINFO_TIMEOUT);
-
- setUpKie(MY_SESS_NAME, 999L, true);
- final PreparedStatement statement = mockDbConn(0);
-
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
-
- verify(statement, never()).executeUpdate();
- }
-
- @Test
- public void testCleanUpSessionInfo_NoUrl() throws Exception {
- props.remove(DroolsPersistenceProperties.DB_URL);
-
- setUpKie(MY_SESS_NAME, 999L, true);
- final PreparedStatement statement = mockDbConn(0);
-
- try {
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
- fail(MISSING_EXCEPTION);
- } catch (RuntimeException e) {
- logger.trace(EXPECTED, e);
- }
-
- verify(statement, never()).executeUpdate();
- }
-
- @Test
- public void testCleanUpSessionInfo_NoUser() throws Exception {
- props.remove(DroolsPersistenceProperties.DB_USER);
-
- setUpKie(MY_SESS_NAME, 999L, true);
- final PreparedStatement statement = mockDbConn(0);
-
- try {
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
- fail(MISSING_EXCEPTION);
- } catch (RuntimeException e) {
- logger.trace(EXPECTED, e);
- }
-
- verify(statement, never()).executeUpdate();
- }
-
- @Test
- public void testCleanUpSessionInfo_NoPassword() throws Exception {
- props.remove(DroolsPersistenceProperties.DB_PWD);
-
- setUpKie(MY_SESS_NAME, 999L, true);
- final PreparedStatement statement = mockDbConn(0);
-
- try {
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
- fail(MISSING_EXCEPTION);
- } catch (RuntimeException e) {
- logger.trace(EXPECTED, e);
- }
-
- verify(statement, never()).executeUpdate();
- }
-
- @Test
- public void testCleanUpSessionInfo_SqlEx() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, true);
- final PreparedStatement statement = mockDbConn(-1);
-
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
-
- verify(statement).executeUpdate();
- }
-
- @Test
- public void testGetDroolsSessionConnector() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, true);
- mockDbConn(5);
-
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
-
- assertEquals(1, jpaCount);
- }
-
- @Test
- public void testReplaceSession() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, true);
- mockDbConn(5);
-
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
-
- final ArgumentCaptor<DroolsSession> sesscap = ArgumentCaptor.forClass(DroolsSession.class);
-
- verify(jpa).replace(sesscap.capture());
-
- assertEquals(MY_SESS_NAME, sesscap.getValue().getSessionName());
- assertEquals(999L, sesscap.getValue().getSessionId());
- }
-
- @Test
- public void testIsPersistenceEnabled_Auto() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, true);
- mockDbConn(5);
-
- props.setProperty("persistence.type", "auto");
-
- assertNotNull(feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE));
- }
-
- @Test
- public void testIsPersistenceEnabled_Native() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, true);
- mockDbConn(5);
-
- props.setProperty("persistence.type", "native");
-
- assertNotNull(feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE));
- }
-
- @Test
- public void testIsPersistenceEnabled_None() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, true);
- mockDbConn(5);
-
- props.remove("persistence.type");
-
- assertNull(feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE));
- }
-
- @Test
- public void testGetProperties_Ex() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, true);
- mockDbConn(5);
-
- feat = new PersistenceFeatureMockDb() {
- @Override
- protected PolicyController getPolicyController(PolicyContainer container) {
- throw new IllegalArgumentException(EXPECTED);
- }
- };
-
- assertNull(feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE));
- }
-
- @Test
- public void testGetProperty_Specific() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, true);
- mockDbConn(5);
-
- props.remove("persistence.type");
- props.setProperty("persistence.myname.type", "auto");
-
- assertNotNull(feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE));
- }
-
- @Test
- public void testGetProperty_Specific_None() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, true);
- mockDbConn(5);
-
- props.remove("persistence.type");
- props.setProperty("persistence.xxx.type", "auto");
-
- assertNull(feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE));
- }
-
- @Test
- public void testGetProperty_Both_SpecificOn() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, true);
- mockDbConn(5);
-
- props.setProperty("persistence.type", "other");
- props.setProperty("persistence.myname.type", "auto");
-
- assertNotNull(feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE));
- }
-
- @Test
- public void testGetProperty_Both_SpecificDisabledOff() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, true);
- mockDbConn(5);
-
- props.setProperty("persistence.type", "auto");
- props.setProperty("persistence.myname.type", "other");
-
- assertNull(feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE));
- }
-
- @Test
- public void testGetProperty_None() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, true);
- mockDbConn(5);
-
- props.remove("persistence.type");
-
- assertNull(feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE));
- }
-
- @Test
- public void testPersistenceFeatureException() {
- SecurityException secex = new SecurityException(EXPECTED);
- PersistenceFeatureException ex = new PersistenceFeatureException(secex);
-
- assertEquals(secex, ex.getCause());
- }
-
- @Test
- public void testDsEmf_RtEx() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, false);
- mockDbConn(5);
-
- feat = new PersistenceFeatureMockDb() {
- @Override
- protected EntityManagerFactory makeEntMgrFact(Map<String, Object> props) {
- throw new IllegalArgumentException(EXPECTED);
- }
- };
-
- feat.globalInit(null, SRC_TEST_RESOURCES);
-
- try {
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
- fail(MISSING_EXCEPTION);
-
- } catch (IllegalArgumentException ex) {
- logger.trace(EXPECTED, ex);
- }
-
- verify(bds, times(2)).close();
- }
-
- @Test
- public void testDsEmf_Close_RtEx() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, false);
- mockDbConn(5);
-
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
-
- ArgumentCaptor<PersistenceFeature.ContainerAdjunct> adjcap =
- ArgumentCaptor.forClass(PersistenceFeature.ContainerAdjunct.class);
-
- verify(polcont, times(1)).setAdjunct(any(), adjcap.capture());
-
- // return adjunct on next call
- when(polcont.getAdjunct(any())).thenReturn(adjcap.getValue());
-
- IllegalArgumentException exception = new IllegalArgumentException(EXPECTED);
- doThrow(exception).when(emf).close();
- assertThatCode(() -> feat.destroyKieSession(polsess)).isEqualTo(exception);
-
- verify(bds, times(2)).close();
- }
-
- @Test
- public void testDsEmf_CloseDataSource_RtEx() throws Exception {
- setUpKie(MY_SESS_NAME, 999L, false);
- mockDbConn(5);
-
- feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
-
- ArgumentCaptor<PersistenceFeature.ContainerAdjunct> adjcap =
- ArgumentCaptor.forClass(PersistenceFeature.ContainerAdjunct.class);
-
- verify(polcont, times(1)).setAdjunct(any(), adjcap.capture());
-
- // return adjunct on next call
- when(polcont.getAdjunct(any())).thenReturn(adjcap.getValue());
-
- SQLException cause = new SQLException(EXPECTED);
- doThrow(cause).when(bds).close();
- assertThatCode(() -> feat.destroyKieSession(polsess)).isInstanceOf(PersistenceFeatureException.class)
- .hasCause(cause);
- }
-
- /**
- * Gets an ordered list of ids of the current SessionInfo records.
- *
- * @return ordered list of SessInfo IDs
- * @throws SQLException sql exception
- * @throws IOException io exception
- */
- private List<Integer> getSessions() throws SQLException, IOException {
- attachDb();
-
- ArrayList<Integer> lst = new ArrayList<>(5);
-
- try (PreparedStatement stmt = conn.prepareStatement("SELECT id from sessioninfo order by id");
- ResultSet rs = stmt.executeQuery()) {
-
- while (rs.next()) {
- lst.add(rs.getInt(1));
- }
- }
-
- return lst;
- }
-
- /**
- * Sets up for doing invoking the newKieSession() method.
- *
- * @param sessnm name to which JPA should respond with a session
- * @param sessid session id to be returned by the session
- * @param loadOk {@code true} if loadKieSession() should return a value, {@code false} to return
- * null
- * @throws Exception exception
- */
- private void setUpKie(String sessnm, long sessid, boolean loadOk) throws Exception {
- props.setProperty("persistence.type", "auto");
-
- when(polctlr.getProperties()).thenReturn(props);
-
- when(jpa.get(sessnm)).thenReturn(sess);
-
- when(sess.getSessionId()).thenReturn(sessid);
-
- when(polsess.getContainer()).thenReturn(polcont);
- when(polsess.getName()).thenReturn(sessnm);
-
- if (loadOk) {
- when(kiesess.getIdentifier()).thenReturn(sessid);
- when(kiestore.loadKieSession(anyLong(), any(), any(), any())).thenReturn(kiesess);
-
- } else {
- // use an alternate id for the new session
- when(kiesess.getIdentifier()).thenReturn(100L);
- when(kiestore.loadKieSession(anyLong(), any(), any(), any())).thenReturn(null);
- }
-
- when(kiestore.newKieSession(any(), any(), any())).thenReturn(kiesess);
-
- feat = new PersistenceFeatureKie();
- feat.globalInit(null, SRC_TEST_RESOURCES);
- }
-
- /**
- * Creates the SessionInfo DB table and populates it with some data.
- *
- * @param expMs number of milli-seconds for expired sessioninfo records
- * @throws SQLException exception
- * @throws IOException exception
- */
- private void makeSessionInfoTbl(int expMs) throws SQLException, IOException {
-
- attachDb();
-
- try (PreparedStatement stmt =
- conn.prepareStatement("CREATE TABLE sessioninfo(id int, lastmodificationdate timestamp)")) {
-
- stmt.executeUpdate();
- }
-
- try (PreparedStatement stmt =
- conn.prepareStatement("INSERT into sessioninfo(id, lastmodificationdate) values(?, ?)")) {
-
- Timestamp ts;
-
- // current data
- ts = new Timestamp(System.currentTimeMillis());
- stmt.setTimestamp(2, ts);
-
- stmt.setInt(1, 1);
- stmt.executeUpdate();
-
- stmt.setInt(1, 4);
- stmt.executeUpdate();
-
- stmt.setInt(1, 5);
- stmt.executeUpdate();
-
- // expired data
- ts = new Timestamp(System.currentTimeMillis() - expMs);
- stmt.setTimestamp(2, ts);
-
- stmt.setInt(1, 2);
- stmt.executeUpdate();
-
- stmt.setInt(1, 3);
- stmt.executeUpdate();
- }
- }
-
- /**
- * Attaches {@link #conn} to the DB, if it isn't already attached.
- *
- * @throws SQLException sql exception
- * @throws IOException if the property file cannot be read
- */
- private void attachDb() throws SQLException, IOException {
- if (conn == null) {
- Properties props = loadDbProps();
-
- conn =
- DriverManager.getConnection(
- props.getProperty(DroolsPersistenceProperties.DB_URL),
- props.getProperty(DroolsPersistenceProperties.DB_USER),
- props.getProperty(DroolsPersistenceProperties.DB_PWD));
- conn.setAutoCommit(true);
- }
- }
-
- /**
- * Loads the DB properties from the file, <i>feature-session-persistence.properties</i>.
- *
- * @return the properties that were loaded
- * @throws IOException if the property file cannot be read
- * @throws FileNotFoundException if the property file does not exist
- */
- private Properties loadDbProps() throws IOException, FileNotFoundException {
-
- Properties props = new Properties();
-
- try (FileReader rdr =
- new FileReader("src/test/resources/feature-session-persistence.properties")) {
- props.load(rdr);
- }
-
- return props;
- }
-
- /**
- * Create a mock DB connection and statement.
- *
- * @param retval value to be returned when the statement is executed, or negative to throw an
- * exception
- * @return the statement that will be returned by the connection
- * @throws SQLException sql exception
- */
- private PreparedStatement mockDbConn(int retval) throws SQLException {
- Connection connection = mock(Connection.class);
- PreparedStatement statement = mock(PreparedStatement.class);
-
- when(bds.getConnection()).thenReturn(connection);
- when(connection.prepareStatement(anyString())).thenReturn(statement);
-
- if (retval < 0) {
- // should throw an exception
- when(statement.executeUpdate()).thenThrow(new SQLException(EXPECTED));
-
- } else {
- // should return the value
- when(statement.executeUpdate()).thenReturn(retval);
- }
-
- feat = new PersistenceFeatureMockDb();
- feat.globalInit(null, SRC_TEST_RESOURCES);
-
- return statement;
- }
-
- /**
- * Feature with a mock DB.
- */
- private class PersistenceFeatureMockDb extends PersistenceFeatureKie {
-
- @Override
- protected BasicDataSource makeDataSource(Properties dsProps) {
- return bds;
- }
- }
-
- /**
- * Feature supporting newKieSession.
- */
- private class PersistenceFeatureKie extends PersistenceFeatureImpl {
-
- @Override
- protected EntityManagerFactory makeEntMgrFact(Map<String, Object> props) {
- ++emfCount;
- return emf;
- }
-
- @Override
- protected DroolsSessionConnector makeJpaConnector(EntityManagerFactory emf) {
- ++jpaCount;
- return jpa;
- }
- }
-
- /**
- * Feature with overrides.
- */
- private class PersistenceFeatureImpl extends PartialFeature {
-
- @Override
- protected Properties loadProperties(String filenm) throws IOException {
- propName = filenm;
- return props;
- }
-
- @Override
- protected BasicDataSource makeDataSource(Properties dsProps) {
- return null;
- }
-
- @Override
- protected DroolsSessionConnector makeJpaConnector(EntityManagerFactory emf) {
- ++jpaCount;
- return null;
- }
- }
-
- /**
- * Feature with <i>some</i> overrides.
- */
- private class PartialFeature extends PersistenceFeature {
-
- @Override
- protected TransactionManager getTransMgr() {
- return transmgr;
- }
-
- @Override
- protected UserTransaction getUserTrans() {
- return usertrans;
- }
-
- @Override
- protected TransactionSynchronizationRegistry getTransSyncReg() {
- return transreg;
- }
-
- @Override
- protected KieServices getKieServices() {
- return kiesvc;
- }
-
- @Override
- protected EntityManagerFactory makeEntMgrFact(Map<String, Object> props) {
- ++emfCount;
- return emf;
- }
-
- @Override
- protected PolicyController getPolicyController(PolicyContainer container) {
- return polctlr;
- }
- }
-}
diff --git a/feature-session-persistence/src/test/resources/META-INF/persistence.xml b/feature-session-persistence/src/test/resources/META-INF/persistence.xml
deleted file mode 100644
index 0fc695d3..00000000
--- a/feature-session-persistence/src/test/resources/META-INF/persistence.xml
+++ /dev/null
@@ -1,38 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- ============LICENSE_START=======================================================
- feature-session-persistence
- ================================================================================
- Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
- ================================================================================
- Licensed 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.
- ============LICENSE_END=========================================================
- -->
-
-<persistence version="2.1"
- xmlns="http://xmlns.jcp.org/xml/ns/persistence"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
-
- <persistence-unit name="junitDroolsSessionEntityPU"
- transaction-type="JTA">
- <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
- <class>org.onap.policy.drools.persistence.DroolsSessionEntity</class>
- <properties>
- <property
- name="javax.persistence.schema-generation.database.action"
- value="create" />
- </properties>
- </persistence-unit>
-
-</persistence>
diff --git a/feature-session-persistence/src/test/resources/feature-session-persistence.properties b/feature-session-persistence/src/test/resources/feature-session-persistence.properties
deleted file mode 100644
index 1c662f95..00000000
--- a/feature-session-persistence/src/test/resources/feature-session-persistence.properties
+++ /dev/null
@@ -1,28 +0,0 @@
-###
-# ============LICENSE_START=======================================================
-# feature-session-persistence
-# ================================================================================
-# Copyright (C) 2017, 2021 AT&T Intellectual Property. All rights reserved.
-# ================================================================================
-# Licensed 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.
-# ============LICENSE_END=========================================================
-###
-
-eclipselink.target-database=Auto
-javax.persistence.jdbc.driver=org.h2.Driver
-javax.persistence.jdbc.url=jdbc:h2:mem:TestPersistenceFeature
-javax.persistence.jdbc.user=testuser
-javax.persistence.jdbc.password=testpass
-
-persistence.sessioninfo.timeout=10
-persistence.objectstore.dir=target/jta
diff --git a/feature-session-persistence/src/test/resources/logback-test.xml b/feature-session-persistence/src/test/resources/logback-test.xml
deleted file mode 100644
index 7f151173..00000000
--- a/feature-session-persistence/src/test/resources/logback-test.xml
+++ /dev/null
@@ -1,49 +0,0 @@
-<!--
- ============LICENSE_START=======================================================
- feature-session-persistence
- ================================================================================
- Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
- ================================================================================
- Licensed 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.
- ============LICENSE_END=========================================================
- -->
-
-<!-- Controls the output of logs for JUnit tests -->
-
-<configuration>
-
- <appender name="STDOUT"
- class="ch.qos.logback.core.ConsoleAppender">
- <encoder
- class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
- <Pattern>
- %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M\(%line\) - %msg%n
- </Pattern>
- </encoder>
- </appender>
- <appender name="FILE"
- class="ch.qos.logback.core.FileAppender">
- <file>logs/debug.log</file>
- <encoder>
- <Pattern>
- %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M\(%line\) - %msg%n
- </Pattern>
- </encoder>
- </appender>
-
- <root level="debug">
- <appender-ref ref="STDOUT" />
- <appender-ref ref="FILE" />
- </root>
-
-</configuration>