summaryrefslogtreecommitdiffstats
path: root/ECOMP-PAP-REST/src/test
diff options
context:
space:
mode:
authorPamela Dragosh <pdragosh@research.att.com>2017-02-14 19:41:00 -0500
committerPamela Dragosh <pdragosh@research.att.com>2017-02-14 19:41:32 -0500
commit91d04c64771832a0b8815ffbe1f0f9920320d94d (patch)
treefb02d5e1c84a3d91def9a7ee95bc87f9c046cc96 /ECOMP-PAP-REST/src/test
parentb9d4caa40ef8e3566ac475968bce17b9b64b6939 (diff)
Initial OpenECOMP policy/engine commit
Change-Id: I7dbff37733b661643dd4d1caefa3d7dccc361b6e Signed-off-by: Pamela Dragosh <pdragosh@research.att.com>
Diffstat (limited to 'ECOMP-PAP-REST/src/test')
-rw-r--r--ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/ia/DbAuditCompareEntriesTest.java519
-rw-r--r--ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/xacml/rest/XACMLPapServletTest.java368
-rw-r--r--ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/xacml/rest/components/PolicyDBDaoTest.java823
-rw-r--r--ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/xacml/rest/jpa/PolicyEntityTest.java802
4 files changed, 2512 insertions, 0 deletions
diff --git a/ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/ia/DbAuditCompareEntriesTest.java b/ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/ia/DbAuditCompareEntriesTest.java
new file mode 100644
index 000000000..c5fa37925
--- /dev/null
+++ b/ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/ia/DbAuditCompareEntriesTest.java
@@ -0,0 +1,519 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PAP-REST
+ * ================================================================================
+ * 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=========================================================
+ */
+
+package org.openecomp.policy.pap.ia;
+
+import static org.junit.Assert.*;
+
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Properties;
+
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.EntityTransaction;
+import javax.persistence.Persistence;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.openecomp.policy.jpa.BackUpMonitorEntity;
+import org.openecomp.policy.rest.jpa.ActionBodyEntity;
+import org.openecomp.policy.rest.jpa.ActionList;
+import org.openecomp.policy.rest.jpa.ActionPolicyDict;
+import org.openecomp.policy.rest.jpa.AddressGroup;
+import org.openecomp.policy.rest.jpa.Attribute;
+import org.openecomp.policy.rest.jpa.AttributeAssignment;
+import org.openecomp.policy.rest.jpa.BRMSParamTemplate;
+import org.openecomp.policy.rest.jpa.Category;
+import org.openecomp.policy.rest.jpa.ClosedLoopD2Services;
+import org.openecomp.policy.rest.jpa.ClosedLoopSite;
+import org.openecomp.policy.rest.jpa.ConfigurationDataEntity;
+import org.openecomp.policy.rest.jpa.ConstraintType;
+import org.openecomp.policy.rest.jpa.ConstraintValue;
+import org.openecomp.policy.rest.jpa.DCAEUsers;
+import org.openecomp.policy.rest.jpa.DCAEuuid;
+import org.openecomp.policy.rest.jpa.DatabaseLockEntity;
+import org.openecomp.policy.rest.jpa.Datatype;
+import org.openecomp.policy.rest.jpa.DecisionSettings;
+import org.openecomp.policy.rest.jpa.DescriptiveScope;
+import org.openecomp.policy.rest.jpa.EcompName;
+import org.openecomp.policy.rest.jpa.EnforcingType;
+import org.openecomp.policy.rest.jpa.FunctionArgument;
+import org.openecomp.policy.rest.jpa.FunctionDefinition;
+import org.openecomp.policy.rest.jpa.GlobalRoleSettings;
+import org.openecomp.policy.rest.jpa.GroupEntity;
+import org.openecomp.policy.rest.jpa.GroupPolicyScopeList;
+import org.openecomp.policy.rest.jpa.GroupServiceList;
+import org.openecomp.policy.rest.jpa.MicroServiceConfigName;
+import org.openecomp.policy.rest.jpa.MicroServiceLocation;
+import org.openecomp.policy.rest.jpa.MicroServiceModels;
+import org.openecomp.policy.rest.jpa.Obadvice;
+import org.openecomp.policy.rest.jpa.ObadviceExpression;
+import org.openecomp.policy.rest.jpa.PEPOptions;
+import org.openecomp.policy.rest.jpa.PIPConfigParam;
+import org.openecomp.policy.rest.jpa.PIPConfiguration;
+import org.openecomp.policy.rest.jpa.PIPResolver;
+import org.openecomp.policy.rest.jpa.PIPResolverParam;
+import org.openecomp.policy.rest.jpa.PIPType;
+import org.openecomp.policy.rest.jpa.PREFIXLIST;
+import org.openecomp.policy.rest.jpa.PdpEntity;
+import org.openecomp.policy.rest.jpa.PolicyAlgorithms;
+import org.openecomp.policy.rest.jpa.PolicyDBDaoEntity;
+import org.openecomp.policy.rest.jpa.PolicyEntity;
+import org.openecomp.policy.rest.jpa.PolicyManagement;
+import org.openecomp.policy.rest.jpa.PolicyRoles;
+import org.openecomp.policy.rest.jpa.PolicyScopeClosedLoop;
+import org.openecomp.policy.rest.jpa.PolicyScopeResource;
+import org.openecomp.policy.rest.jpa.PolicyScopeService;
+import org.openecomp.policy.rest.jpa.PolicyScopeType;
+import org.openecomp.policy.rest.jpa.PolicyScore;
+import org.openecomp.policy.rest.jpa.PolicyVersion;
+import org.openecomp.policy.rest.jpa.PortList;
+import org.openecomp.policy.rest.jpa.ProtocolList;
+import org.openecomp.policy.rest.jpa.RemoteCatalogValues;
+import org.openecomp.policy.rest.jpa.RuleAlgorithms;
+import org.openecomp.policy.rest.jpa.SecurityZone;
+import org.openecomp.policy.rest.jpa.ServiceList;
+import org.openecomp.policy.rest.jpa.SystemLogDB;
+import org.openecomp.policy.rest.jpa.TermList;
+import org.openecomp.policy.rest.jpa.UserInfo;
+import org.openecomp.policy.rest.jpa.VMType;
+import org.openecomp.policy.rest.jpa.VNFType;
+import org.openecomp.policy.rest.jpa.VSCLAction;
+import org.openecomp.policy.rest.jpa.VarbindDictionary;
+import org.openecomp.policy.rest.jpa.Zone;
+
+import org.openecomp.policy.common.ia.DbAudit;
+import org.openecomp.policy.common.ia.DbDAO;
+import org.openecomp.policy.common.ia.IntegrityAuditProperties;
+import org.openecomp.policy.common.ia.jpa.IntegrityAuditEntity;
+import org.openecomp.policy.common.im.jpa.ForwardProgressEntity;
+import org.openecomp.policy.common.im.jpa.ResourceRegistrationEntity;
+import org.openecomp.policy.common.im.jpa.StateManagementEntity;
+
+import org.apache.commons.lang3.SerializationUtils;
+
+@Ignore
+public class DbAuditCompareEntriesTest {
+
+ private static Log logger = LogFactory.getLog(DbAuditCompareEntriesTest.class);
+ private DbDAO dbDAO;
+ private String persistenceUnit;
+ private Properties properties;
+ private String resourceName;
+ private String dbDriver;
+ private String dbUrl;
+ private String dbUser;
+ private String dbPwd;
+ private String siteName;
+ private String nodeType;
+
+ @Before
+ public void setUp() throws Exception {
+ logger.info("setUp: Entering");
+
+ properties = new Properties();
+ properties.put(IntegrityAuditProperties.DB_DRIVER, IntegrityAuditProperties.DEFAULT_DB_DRIVER);
+ properties.put(IntegrityAuditProperties.DB_URL, "jdbc:h2:file:./sql/xacmlTest");
+ properties.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER);
+ properties.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.DEFAULT_DB_PWD);
+ properties.put(IntegrityAuditProperties.SITE_NAME, "SiteA");
+ properties.put(IntegrityAuditProperties.NODE_TYPE, "pap");
+
+ dbDriver = IntegrityAuditProperties.DEFAULT_DB_DRIVER;
+ dbUrl = "jdbc:h2:file:./sql/xacmlTest";
+ dbUser = IntegrityAuditProperties.DEFAULT_DB_USER;
+ dbPwd = IntegrityAuditProperties.DEFAULT_DB_PWD;
+ siteName = "SiteA";
+ nodeType = "pap";
+ persistenceUnit = "testPapPU";
+ resourceName = "siteA.pap1";
+
+ //Clean the iaTest DB table for IntegrityAuditEntity entries
+ cleanDb(persistenceUnit, properties);
+
+ logger.info("setUp: Exiting");
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ logger.info("tearDown: Entering");
+ //nothing to do
+ logger.info("tearDown: Exiting");
+ }
+
+ public void cleanDb(String persistenceUnit, Properties properties){
+ logger.debug("cleanDb: enter");
+
+ EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, properties);
+
+ EntityManager em = emf.createEntityManager();
+ // Start a transaction
+ EntityTransaction et = em.getTransaction();
+
+ et.begin();
+
+ // Clean up the DB
+ em.createQuery("Delete from IntegrityAuditEntity").executeUpdate();
+
+ // commit transaction
+ et.commit();
+ em.close();
+ logger.debug("cleanDb: exit");
+ }
+
+
+ /*
+ * Tests that a comparison between hashsets is successful if
+ * the entries match
+ */
+ //@Ignore
+ @Test
+ public void runAllTests() throws Exception {
+ logger.info("runAllTests: Entering");
+
+
+ testIntegrityAuditEntity();
+ testBackupMonitorEntity();
+ testStateManagementEntity();
+ testForwardProgressEntity();
+ testResourceRegistrationEntity();
+
+ //clean up the IntegrityAuditEntity table
+ cleanDb(persistenceUnit, properties);
+
+ logger.info("runAllTests: Exit");
+ }
+
+
+ public void testIntegrityAuditEntity() throws Exception {
+ logger.info("testIntegrityAuditEntity: Entering");
+
+ dbDAO = new DbDAO(resourceName, persistenceUnit, properties);
+ DbAudit dbAudit = new DbAudit(dbDAO);
+
+ String className = null;
+ //There is only one entry IntegrityAuditEntity, but we will check anyway
+ HashSet<String> classNameSet = dbDAO.getPersistenceClassNames();
+ for(String c : classNameSet){
+ if (c.equals("org.openecomp.policy.common.ia.IntegrityAuditEntity")){
+ className = c;
+ }
+ }
+ String resourceName1 = resourceName;
+ String resourceName2 = resourceName;
+
+ IntegrityAuditEntity entry1 = new IntegrityAuditEntity();
+ IntegrityAuditEntity entry2 = new IntegrityAuditEntity();
+ Date date = new Date();
+
+ /*
+ * Two entries with the same field values
+ */
+ entry1.setDesignated(false);
+ entry1.setJdbcDriver(dbDriver);
+ entry1.setJdbcPassword(dbPwd);
+ entry1.setJdbcUrl(dbUrl);
+ entry1.setJdbcUser(dbUser);
+ entry1.setLastUpdated(date);
+ entry1.setNodeType(nodeType);
+ entry1.setPersistenceUnit(persistenceUnit);
+ entry1.setResourceName(resourceName1);
+ entry1.setSite(siteName);
+
+ entry2 = SerializationUtils.clone(entry1);
+
+ dbAudit.writeAuditDebugLog(className, resourceName1, resourceName2, entry1, entry2);
+
+ HashMap<Object, Object> myEntries = new HashMap<Object, Object>();
+ HashMap<Object, Object> theirEntries = new HashMap<Object, Object>();
+
+ myEntries.put("pdp1", entry1);
+ theirEntries.put("pdp1", entry2);
+
+ HashSet<Object> result = dbAudit.compareEntries(myEntries, theirEntries);
+
+ /*
+ * Assert that there are no mismatches returned
+ */
+ assertTrue(result.isEmpty());
+
+ /*
+ * ************************************
+ * Now test with a mis-matched entry
+ * ************************************
+ */
+
+ /*
+ * Change the entry2 to different designated value
+ */
+ entry2.setDesignated(true);
+
+ myEntries = new HashMap<Object, Object>();
+ theirEntries = new HashMap<Object, Object>();
+
+ myEntries.put("pdp1", entry1);
+ theirEntries.put("pdp1", entry2);
+
+ result = dbAudit.compareEntries(myEntries, theirEntries);
+
+ /*
+ * Assert that there was one mismatch
+ */
+ assertEquals(1, result.size());
+ logger.info("testIntegrityAuditEntity: Exit");
+ }
+
+ void testBackupMonitorEntity() throws Exception {
+ logger.info("testBackupMonitorEntity: Entering");
+
+ dbDAO = new DbDAO(resourceName, persistenceUnit, properties);
+ DbAudit dbAudit = new DbAudit(dbDAO);
+
+ BackUpMonitorEntity entry1 = new BackUpMonitorEntity();
+ BackUpMonitorEntity entry2 = new BackUpMonitorEntity();
+
+ // Two entries with the same field values
+
+
+ entry1.setFlag("flag1");
+ entry1.setResoruceNodeName("node1");
+ entry1.setResourceName("resourceName");
+ entry1.setTimeStamp(new Date());
+
+ // Clone the first entry
+ entry2 = SerializationUtils.clone(entry1);
+
+ HashMap<Object, Object> myEntries = new HashMap<Object, Object>();
+ HashMap<Object, Object> theirEntries = new HashMap<Object, Object>();
+
+ myEntries.put("pdp1", entry1);
+ theirEntries.put("pdp1", entry2);
+
+ HashSet<Object> result = dbAudit.compareEntries(myEntries, theirEntries);
+
+
+ // Assert that there are no mismatches returned
+
+ assertTrue(result.isEmpty());
+
+
+ /* ************************************
+ * Now test with a mis-matched entry
+ * ************************************/
+
+
+
+ // Change a field on entry2
+
+ entry2.setFlag("flag2");
+
+ myEntries = new HashMap<Object, Object>();
+ theirEntries = new HashMap<Object, Object>();
+
+ myEntries.put("pdp1", entry1);
+ theirEntries.put("pdp1", entry2);
+
+ result = dbAudit.compareEntries(myEntries, theirEntries);
+
+
+ //Assert that there was one mismatch
+
+ assertEquals(1, result.size());
+ logger.info("testBackupMonitorEntity: Exit");
+ }
+
+ void testStateManagementEntity() throws Exception {
+ logger.info("testStateManagementEntity: Entering");
+
+ dbDAO = new DbDAO(resourceName, persistenceUnit, properties);
+ DbAudit dbAudit = new DbAudit(dbDAO);
+
+ StateManagementEntity entry1 = new StateManagementEntity();
+ StateManagementEntity entry2 = new StateManagementEntity();
+
+ // Two entries with the same field values
+
+ entry1.setAdminState("locked");
+ entry1.setAvailStatus("null");
+ entry1.setModifiedDate(new Date());
+ entry1.setOpState("enabled");
+ entry1.setResourceName("myResource");
+ entry1.setStandbyStatus("coldstandby");
+
+ // Clone the first entry
+ entry2 = SerializationUtils.clone(entry1);
+
+ HashMap<Object, Object> myEntries = new HashMap<Object, Object>();
+ HashMap<Object, Object> theirEntries = new HashMap<Object, Object>();
+
+ myEntries.put("pdp1", entry1);
+ theirEntries.put("pdp1", entry2);
+
+ HashSet<Object> result = dbAudit.compareEntries(myEntries, theirEntries);
+
+
+ // Assert that there are no mismatches returned
+
+ assertTrue(result.isEmpty());
+
+
+ /* ************************************
+ * Now test with a mis-matched entry
+ * ************************************/
+
+
+
+ // Change a field on entry2
+
+ entry2.setAdminState("unlocked");
+
+ myEntries = new HashMap<Object, Object>();
+ theirEntries = new HashMap<Object, Object>();
+
+ myEntries.put("pdp1", entry1);
+ theirEntries.put("pdp1", entry2);
+
+ result = dbAudit.compareEntries(myEntries, theirEntries);
+
+
+ //Assert that there was one mismatch
+
+ assertEquals(1, result.size());
+ logger.info("testStateManagementEntity: Exit");
+ }
+
+ void testForwardProgressEntity() throws Exception {
+ logger.info("testForwardProgressEntity: Entering");
+
+ dbDAO = new DbDAO(resourceName, persistenceUnit, properties);
+ DbAudit dbAudit = new DbAudit(dbDAO);
+
+ ForwardProgressEntity entry1 = new ForwardProgressEntity();
+ ForwardProgressEntity entry2 = new ForwardProgressEntity();
+
+ // Two entries with the same field values
+
+ entry1.setFpcCount(123L);
+ entry1.setLastUpdated(new Date());
+ entry1.setResourceName("myResource");
+
+ // Clone the first entry
+ entry2 = SerializationUtils.clone(entry1);
+
+ HashMap<Object, Object> myEntries = new HashMap<Object, Object>();
+ HashMap<Object, Object> theirEntries = new HashMap<Object, Object>();
+
+ myEntries.put("pdp1", entry1);
+ theirEntries.put("pdp1", entry2);
+
+ HashSet<Object> result = dbAudit.compareEntries(myEntries, theirEntries);
+
+
+ // Assert that there are no mismatches returned
+
+ assertTrue(result.isEmpty());
+
+
+ /* ************************************
+ * Now test with a mis-matched entry
+ * ************************************/
+
+ // Change a field on entry2
+
+ entry2.setFpcCount(321L);
+
+ myEntries = new HashMap<Object, Object>();
+ theirEntries = new HashMap<Object, Object>();
+
+ myEntries.put("pdp1", entry1);
+ theirEntries.put("pdp1", entry2);
+
+ result = dbAudit.compareEntries(myEntries, theirEntries);
+
+
+ //Assert that there was one mismatch
+
+ assertEquals(1, result.size());
+ logger.info("testForwardProgressEntity: Exit");
+ }
+
+ void testResourceRegistrationEntity() throws Exception {
+ logger.info("testResourceRegistrationEntity: Entering");
+
+ dbDAO = new DbDAO(resourceName, persistenceUnit, properties);
+ DbAudit dbAudit = new DbAudit(dbDAO);
+
+ ResourceRegistrationEntity entry1 = new ResourceRegistrationEntity();
+ ResourceRegistrationEntity entry2 = new ResourceRegistrationEntity();
+
+ // Two entries with the same field values
+
+ entry1.setNodeType("pap");
+ entry1.setLastUpdated(new Date());
+ entry1.setResourceName("myResource");
+ entry1.setResourceUrl("http://nowhere.com");
+ entry1.setSite("site_1");
+
+ // Clone the first entry
+ entry2 = SerializationUtils.clone(entry1);
+
+ HashMap<Object, Object> myEntries = new HashMap<Object, Object>();
+ HashMap<Object, Object> theirEntries = new HashMap<Object, Object>();
+
+ myEntries.put("pdp1", entry1);
+ theirEntries.put("pdp1", entry2);
+
+ HashSet<Object> result = dbAudit.compareEntries(myEntries, theirEntries);
+
+
+ // Assert that there are no mismatches returned
+
+ assertTrue(result.isEmpty());
+
+
+ /* ************************************
+ * Now test with a mis-matched entry
+ * ************************************/
+
+ // Change a field on entry2
+
+ entry2.setSite("site_1a");
+
+ myEntries = new HashMap<Object, Object>();
+ theirEntries = new HashMap<Object, Object>();
+
+ myEntries.put("pdp1", entry1);
+ theirEntries.put("pdp1", entry2);
+
+ result = dbAudit.compareEntries(myEntries, theirEntries);
+
+
+ //Assert that there was one mismatch
+
+ assertEquals(1, result.size());
+ logger.info("testResourceRegistrationEntity: Exit");
+ }
+}
diff --git a/ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/xacml/rest/XACMLPapServletTest.java b/ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/xacml/rest/XACMLPapServletTest.java
new file mode 100644
index 000000000..da11d72ce
--- /dev/null
+++ b/ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/xacml/rest/XACMLPapServletTest.java
@@ -0,0 +1,368 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PAP-REST
+ * ================================================================================
+ * 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=========================================================
+ */
+
+package org.openecomp.policy.pap.xacml.rest;
+
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Properties;
+
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.EntityTransaction;
+import javax.persistence.Persistence;
+import javax.servlet.ServletConfig;
+import javax.servlet.ServletOutputStream;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import junit.framework.TestCase;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.openecomp.policy.pap.xacml.rest.XACMLPapServlet;
+import org.openecomp.policy.rest.XACMLRestProperties;
+import org.springframework.mock.web.MockHttpServletResponse;
+import org.springframework.mock.web.MockServletConfig;
+
+import org.openecomp.policy.common.ia.IntegrityAudit;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+
+public class XACMLPapServletTest extends TestCase{
+ private static Logger logger = FlexLogger.getLogger(XACMLPapServletTest.class);
+
+ private List<String> headers = new ArrayList<String>();
+
+ private HttpServletRequest httpServletRequest;
+ private HttpServletResponse httpServletResponse;
+ private ServletOutputStream mockOutput;
+ private ServletConfig servletConfig;
+ private XACMLPapServlet papServlet;
+
+
+ @Before
+
+ public void setUp() throws IOException {
+ httpServletRequest = Mockito.mock(HttpServletRequest.class);
+ Mockito.when(httpServletRequest.getMethod()).thenReturn("POST");
+ Mockito.when(httpServletRequest.getParameter("groupId")).thenReturn(null);
+ Mockito.when(httpServletRequest.getHeaderNames()).thenReturn(Collections.enumeration(headers));
+ Mockito.when(httpServletRequest.getAttributeNames()).thenReturn(Collections.enumeration(headers));
+
+
+ mockOutput = Mockito.mock(ServletOutputStream.class);
+
+ //when(httpServletRequest.getPathInfo()).thenReturn("/lineup/world.xml");
+ //HttpServletResponse httpResponse = new HttpServletResponse();
+ httpServletResponse = Mockito.mock(MockHttpServletResponse.class);
+
+ Mockito.when(httpServletResponse.getOutputStream()).thenReturn(mockOutput);
+
+
+ //when(httpServletResponse.getOutputStream()).thenReturn(servletOutputStream);
+ servletConfig = Mockito.mock(MockServletConfig.class);
+ //Mockito.when(servletConfig.getInitParameterNames()).thenReturn(Collections.enumeration(headers));
+ //servletConfig
+ Mockito.when(servletConfig.getInitParameterNames()).thenReturn(Collections.enumeration(headers));
+ papServlet = new XACMLPapServlet();
+
+ Mockito.when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME")).thenReturn("xacml.pap.test.properties");
+
+ System.setProperty("xacml.PAP.papEngineFactory", "org.openecomp.policy.xacml.std.pap.StdEngineFactory");
+ System.setProperty("xacml.pap.pdps", "pdps");
+ System.setProperty("xacml.rest.pap.url", "http://localhost:8070/pap/");
+ System.setProperty("xacml.rest.pap.initiate.pdp", "false");
+ System.setProperty("xacml.rest.pdp.idfile", "testpdp.properties");
+ System.setProperty("xacml.rest.pep.idfile", "client.properties");
+ System.setProperty("javax.persistence.jdbc.driver", "org.h2.Driver");
+ System.setProperty("javax.persistence.jdbc.url", "jdbc:h2:file:./sql/xacmlTest");
+ System.setProperty("javax.persistence.jdbc.user", "sa");
+ System.setProperty("javax.persistence.jdbc.password", "");
+ System.setProperty("xacml.rest.pap.jmx.url", "service:jmx:rmi:///jndi/rmi://localhost:9990/jmxrmi");
+ System.setProperty("xacml.rest.pap.resource.name", "site_1.pap_1");
+ System.setProperty("fp_monitor_interval", "30");
+ System.setProperty("failed_counter_threshold", "3");
+ System.setProperty("test_trans_interval", "10");
+ System.setProperty("write_fpc_interval", "5");
+ System.setProperty("com.sun.management.jmxremote.port", "9999");
+ System.setProperty("dependency_groups", "site_1.logparser_1;site_1.adminconsole_1;site_1.elk_1");
+ System.setProperty("site_name", "site_1");
+ System.setProperty("node_type", "pap");
+ }
+
+ /*
+ * This method initializes and cleans the DB so the XACMLPapServlet will be able to instantiate an
+ * IntegrityAudit object which will use the DB.
+ */
+ public void initializeDb(){
+ logger.debug("initializeDb: enter");
+ Properties cleanProperties = new Properties();
+ cleanProperties.put(XACMLRestProperties.PROP_PAP_DB_DRIVER,"org.h2.Driver");
+ cleanProperties.put(XACMLRestProperties.PROP_PAP_DB_URL, "jdbc:h2:file:./sql/xacmlTest");
+ cleanProperties.put(XACMLRestProperties.PROP_PAP_DB_USER, "sa");
+ cleanProperties.put(XACMLRestProperties.PROP_PAP_DB_PASSWORD, "");
+ EntityManagerFactory emf = Persistence.createEntityManagerFactory("testPapPU", cleanProperties);
+
+ EntityManager em = emf.createEntityManager();
+ // Start a transaction
+ EntityTransaction et = em.getTransaction();
+
+ et.begin();
+
+ // Clean up the DB
+ em.createQuery("Delete from IntegrityAuditEntity").executeUpdate();
+
+ // commit transaction
+ et.commit();
+ em.close();
+ logger.debug("initializeDb: exit");
+ }
+
+ @Test
+ public void testInit() throws Exception{
+ System.setProperty("integrity_audit_period_seconds", "0");
+ initializeDb();
+ try {
+ papServlet.init(servletConfig);
+ IntegrityAudit ia = papServlet.getIa();
+ if(ia.isThreadInitialized()){
+ assertTrue(true);
+ }else{
+ fail();
+ }
+ ia.stopAuditThread();
+ // Allow time for the thread to stop
+ Thread.sleep(1000);
+ if(!ia.isThreadInitialized()){
+ assertTrue(true);
+ }else{
+ fail();
+ }
+ } catch (Exception e) {
+ // TODO Auto-generated catch block
+ fail();
+ }
+ }
+
+/* public void testDoGetPapTest(){
+ try{
+ Mockito.when(httpServletRequest.getRequestURI()).thenReturn("/pap/test");
+ papServlet.init(servletConfig);
+ IntegrityAudit ia = papServlet.getIa();
+ ia.stopAuditThread();
+ papServlet.doGet(httpServletRequest, httpServletResponse);
+ logger.info(httpServletResponse.getStatus());
+
+ //Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
+ }catch (Exception e){
+ logger.info("testDoGetPapTest failed with message: " + e.getMessage());
+ fail();
+ }
+ assertTrue(true);
+ }*/
+
+/*
+ * Need to figure a way to get it to match any message string
+ * public void testDoGetPapTestFpcFailure(){
+ try{
+ Mockito.when(httpServletRequest.getRequestURI()).thenReturn("/pap/test");
+ Mockito.when(httpServletRequest.getHeader("THIS-IS-A-TEST")).thenReturn("FPC");
+ papServlet.init(servletConfig);
+ IntegrityAudit ia = papServlet.getIa();
+ ia.stopAuditThread();
+ papServlet.doGet(httpServletRequest, httpServletResponse);
+ Mockito.verify(httpServletResponse).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Mockito.anyString());
+ }catch (Exception e){
+ logger.info("testDoGetPapTestFpcFailure failed with message: " + e.getMessage());
+ fail();
+ }
+ assertTrue(true);
+ }*/
+
+ public void testDoGetLocal(){
+ try{
+ Mockito.when(httpServletRequest.getRemoteHost()).thenReturn("localhost");
+ papServlet.init(servletConfig);
+ IntegrityAudit ia = papServlet.getIa();
+ ia.stopAuditThread();
+ papServlet.doGet(httpServletRequest, httpServletResponse);
+
+ logger.info(httpServletResponse.getStatus());
+ Mockito.verify(httpServletResponse).setHeader("content-type", "application/json");
+ Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
+ }catch (Exception e){
+ fail();
+ }
+
+ assertTrue(true);
+ }
+
+ public void testDoGetNonLocal(){
+ //return non-local host remote address, which is invalid
+ Mockito.when(httpServletRequest.getRemoteHost()).thenReturn("0.0.0.0");
+ try{
+ papServlet.init(servletConfig);
+ IntegrityAudit ia = papServlet.getIa();
+ ia.stopAuditThread();
+ papServlet.doGet(httpServletRequest, httpServletResponse);
+ logger.info(httpServletResponse.getStatus());
+ String message = "Unknown PDP: from 0.0.0.0 us: null";
+
+ Mockito.verify(httpServletResponse).sendError(401, message);
+
+ }catch (Exception e){
+ fail();
+ }
+ }
+
+ public void testDoGetWithGroup() throws Exception{
+ Mockito.when(httpServletRequest.getParameter("groupId")).thenReturn("default");
+ //Mockito.when(httpServletRequest.getHeader("X-XACML-PDP-ID")).thenReturn("default");
+ papServlet.init(servletConfig);
+ IntegrityAudit ia = papServlet.getIa();
+ ia.stopAuditThread();
+ papServlet.doGet(httpServletRequest, httpServletResponse);
+ Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
+ }
+
+ public void testDoPostWithGroup(){
+ Mockito.when(httpServletRequest.getParameter("groupId")).thenReturn("default");
+ Mockito.when(httpServletRequest.getParameter("policyId")).thenReturn("default");
+ try{
+ papServlet.init(servletConfig);
+ IntegrityAudit ia = papServlet.getIa();
+ ia.stopAuditThread();
+ papServlet.doPost(httpServletRequest, httpServletResponse);
+ //Mockito.verify(httpServletResponse).sendError(500, "Policy 'default' not copied to group 'default': java.lang.NullPointerException");
+ //Mockito.verify(httpServletResponse).sendError(500, "Policy 'default' not copied to group 'default': javax.persistence.PersistenceException: Group policy is being added to does not exist with id default");
+
+ }catch (Exception e){
+ fail();
+ }
+ }
+ //why is this test trying to send no pdp id and expecting a 200 response?
+ /*
+ public void testDoPost(){
+ final ByteArrayOutputStream os = new ByteArrayOutputStream ();
+ ByteArrayOutputStream multiPartResponse = new ByteArrayOutputStream();
+ Mockito.when(httpServletRequest.getHeader("X-XACML-PDP-JMX-PORT")).thenReturn("0");
+
+ try{
+ multiPartResponse.writeTo(os);
+ final ByteArrayInputStream is = new ByteArrayInputStream (os.toByteArray ());
+ Mockito.when(httpServletRequest.getInputStream()).thenReturn(new ServletInputStream() {
+ @Override
+ public int read() throws IOException {
+ return is.read();
+ }
+ });
+
+ papServlet.init(servletConfig);
+ IntegrityAudit ia = papServlet.getIa();
+ ia.stopAuditThread();
+ papServlet.doPost(httpServletRequest, httpServletResponse);
+ Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK);
+ }catch (Exception e){
+ fail();
+ }
+ }
+ */
+
+ public void testDoPostPDPId(){
+ String groupId = "newPDP";
+ Mockito.when(httpServletRequest.getParameter("groupId")).thenReturn(groupId);
+ Mockito.when(httpServletRequest.getHeader("X-XACML-PDP-ID")).thenReturn(groupId);
+ try{
+ papServlet.init(servletConfig);
+ IntegrityAudit ia = papServlet.getIa();
+ ia.stopAuditThread();
+ papServlet.doPut(httpServletRequest, httpServletResponse);
+ Mockito.verify(httpServletResponse).sendError(HttpServletResponse.SC_NOT_FOUND, "Unknown groupId '" + groupId +"'");
+ }catch(Exception e){
+ fail();
+ }
+ }
+
+ public void testDoPutInvalidAdminConsoleURL(){
+ Mockito.when(httpServletRequest.getParameter("adminConsoleURL")).thenReturn("wwww.adminConsole.com");
+ //204
+ try{
+ papServlet.init(servletConfig);
+ IntegrityAudit ia = papServlet.getIa();
+ ia.stopAuditThread();
+ papServlet.doPut(httpServletRequest, httpServletResponse);
+ Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_NO_CONTENT);
+ }catch (Exception e){
+ fail();
+ }
+ }
+
+ public void testDoPutWithGroupIdAndUnimplimentedPipId(){
+ Mockito.when(httpServletRequest.getParameter("groupId")).thenReturn("default");
+ Mockito.when(httpServletRequest.getParameter("pipId")).thenReturn("default");
+ try{
+ papServlet.init(servletConfig);
+ IntegrityAudit ia = papServlet.getIa();
+ ia.stopAuditThread();
+ papServlet.doPut(httpServletRequest, httpServletResponse);
+ Mockito.verify(httpServletResponse).sendError(HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED");
+ }catch (Exception e){
+ fail();
+ }
+ }
+
+ public void testDoDeleteNoGroup(){
+ Mockito.when(httpServletRequest.getParameter("groupdId")).thenReturn(null);
+
+ try{
+ papServlet.init(servletConfig);
+ IntegrityAudit ia = papServlet.getIa();
+ ia.stopAuditThread();
+ papServlet.doDelete(httpServletRequest, httpServletResponse);
+ Mockito.verify(httpServletResponse).sendError(HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId");
+ }catch (Exception e){
+ fail();
+ }
+ }
+
+ public void testDoDeleteWithDefaultGroup(){
+ Mockito.when(httpServletRequest.getParameter("groupId")).thenReturn("default");
+
+ try{
+ papServlet.init(servletConfig);
+ IntegrityAudit ia = papServlet.getIa();
+ ia.stopAuditThread();
+ papServlet.doDelete(httpServletRequest, httpServletResponse);
+ Mockito.verify(httpServletResponse).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"You cannot delete the default group.");
+ }catch(Exception e){
+ fail();
+ }
+ }
+}
diff --git a/ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/xacml/rest/components/PolicyDBDaoTest.java b/ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/xacml/rest/components/PolicyDBDaoTest.java
new file mode 100644
index 000000000..81f33c99b
--- /dev/null
+++ b/ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/xacml/rest/components/PolicyDBDaoTest.java
@@ -0,0 +1,823 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PAP-REST
+ * ================================================================================
+ * 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=========================================================
+ */
+
+package org.openecomp.policy.pap.xacml.rest.components;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.file.Paths;
+import java.util.Date;
+import java.util.List;
+
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.Persistence;
+import javax.persistence.PersistenceException;
+import javax.persistence.Query;
+
+import org.junit.Test;
+import org.openecomp.policy.pap.xacml.rest.adapters.PolicyRestAdapter;
+import org.openecomp.policy.pap.xacml.rest.components.ConfigPolicy;
+import org.openecomp.policy.pap.xacml.rest.components.Policy;
+import org.openecomp.policy.pap.xacml.rest.components.PolicyDBDao;
+import org.openecomp.policy.pap.xacml.rest.components.PolicyDBDaoTransaction;
+import org.openecomp.policy.pap.xacml.rest.components.PolicyDBDao.PolicyDBDaoTestClass;
+import org.openecomp.policy.rest.XACMLRestProperties;
+import org.openecomp.policy.rest.jpa.ActionBodyEntity;
+import org.openecomp.policy.rest.jpa.GroupEntity;
+import org.openecomp.policy.rest.jpa.PdpEntity;
+import org.openecomp.policy.rest.jpa.PolicyEntity;
+import org.openecomp.policy.rest.util.Webapps;
+
+import com.att.research.xacml.api.pap.PAPException;
+
+import org.openecomp.policy.xacml.api.pap.EcompPDPGroup;
+import org.openecomp.policy.xacml.std.pap.StdPDPGroup;
+import org.openecomp.policy.xacml.util.XACMLPolicyWriter;
+import com.att.research.xacml.util.XACMLProperties;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.IOUtils;
+//import org.apache.commons.logging.Log;
+//import org.apache.commons.logging.LogFactory;
+import org.junit.Before;
+import org.junit.After;
+import org.junit.Ignore;
+
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
+
+import org.junit.Assert;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+
+@Ignore //only run locally as timing sometimes causes failures on Jenkins
+public class PolicyDBDaoTest {
+
+ private static Logger logger = FlexLogger.getLogger(PolicyDBDaoTest.class);
+
+ PolicyDBDaoTestClass d;
+ PolicyDBDao dbd;
+ PolicyDBDao dbd2;
+ EntityManagerFactory emf;
+ @Before
+ public void init(){
+ System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME,"xacml.pap.properties");
+ emf = Persistence.createEntityManagerFactory("testPapPU");
+ EntityManager em = emf.createEntityManager();
+ em.getTransaction().begin();
+ try{
+ em.createQuery("DELETE FROM PolicyDBDaoEntity").executeUpdate();
+ em.createQuery("DELETE FROM PolicyEntity").executeUpdate();
+ em.createQuery("DELETE FROM ConfigurationDataEntity").executeUpdate();
+ em.createQuery("DELETE FROM ActionBodyEntity").executeUpdate();
+ em.createQuery("DELETE FROM PdpEntity").executeUpdate();
+ em.createQuery("DELETE FROM GroupEntity").executeUpdate();
+
+ em.getTransaction().commit();
+ } catch(Exception e){
+ e.printStackTrace();
+ em.getTransaction().rollback();
+ }
+ em.close();
+ try {
+ dbd = PolicyDBDao.getPolicyDBDaoInstance(emf);
+ dbd2 = PolicyDBDao.getPolicyDBDaoInstance(emf);
+ } catch (Exception e) {
+ //e.printStackTrace();
+ Assert.fail();
+ }
+
+ d = PolicyDBDao.getPolicyDBDaoTestClass();
+ }
+
+ @After
+ public void cleanUp(){
+ EntityManager em = emf.createEntityManager();
+ em.getTransaction().begin();
+ try{
+ em.createQuery("DELETE FROM PolicyDBDaoEntity").executeUpdate();
+ em.createQuery("DELETE FROM PolicyEntity").executeUpdate();
+ em.createQuery("DELETE FROM ConfigurationDataEntity").executeUpdate();
+ em.createQuery("DELETE FROM ActionBodyEntity").executeUpdate();
+ em.createQuery("DELETE FROM PdpEntity").executeUpdate();
+ em.createQuery("DELETE FROM GroupEntity").executeUpdate();
+
+ em.getTransaction().commit();
+ } catch(Exception e){
+ em.getTransaction().rollback();
+ }
+ em.close();
+ try {
+ FileUtils.forceDelete(new File("src/test/resources/junitTestCreatedDirectory"));
+ } catch (IOException e) {
+ //could not delete
+ }
+
+ }
+
+ @Test
+ public void getScopeAndNameAndTypeTest(){
+
+ String s = d.getGitPath();
+ String pathIwantToUse;
+ if(s.contains("/")){
+ pathIwantToUse = "/root/users/" + s + "/org/openecomp/Config_mypolicy.xml";
+ } else {
+ pathIwantToUse = "C:\\root\\users\\" + s + "\\org\\openecomp\\Config_mypolicy.xml";
+ }
+ String[] snt = d.getScopeAndNameAndType(pathIwantToUse);
+ Assert.assertEquals("Scope was parsed wrong","org.openecomp", snt[0]);
+ Assert.assertEquals("Policy name was parsed wrong","Config_mypolicy.xml", snt[1]);
+ Assert.assertEquals("Policy type was parsed wrong","Config", snt[2]);
+ }
+ @Test
+ public void computeScopeTest(){
+ Assert.assertEquals("com",d.computeScope("C:\\Users\\testuser\\admin\\repo\\com\\", "C:\\Users\\testuser\\admin\\repo"));
+ Assert.assertEquals("org.openecomp.policy",d.computeScope("/Users/testuser/admin/repo/org/openecomp/policy", "/Users/testuser/admin/repo"));
+ }
+ @Test
+ public void getConfigFileTest(){
+ PolicyRestAdapter pra = new PolicyRestAdapter();
+ pra.setConfigType(ConfigPolicy.JSON_CONFIG);
+ String configFile = d.getConfigFile("Config_mypolicy.xml", "org.openecomp", pra);
+ Assert.assertEquals("org.openecomp.Config_mypolicy.json", configFile);
+ //yes, we can do action files too even though they don't have configs
+ configFile = d.getConfigFile("Action_mypolicy.xml", "org.openecomp", pra);
+ Assert.assertEquals("org.openecomp.Action_mypolicy.json", configFile);
+ }
+
+ @Test
+ public void transactionTests(){
+
+
+// try{
+// transac.commitTransaction();
+// Assert.fail();
+// } catch(IllegalStateException e){
+// //worked
+// } catch(Exception e2){
+// Assert.fail();
+// }
+ String filePath = null;
+ String xmlFile = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<Policy xmlns=\"urn:oasis:names:tc:xacml:3.0:core:schema:wd-17\" PolicyId=\"urn:com:xacml:policy:id:eaa4bb64-59cf-4517-bb44-b2eeabd50b11\" Version=\"1\" RuleCombiningAlgId=\"urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides\">\n <Description></Description>\n <Target>\n <AnyOf>\n <AllOf>\n <Match MatchId=\"org.openecomp.function.regex-match\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#integer\">99</AttributeValue>\n <AttributeDesignator Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\" AttributeId=\"cpu\" DataType=\"http://www.w3.org/2001/XMLSchema#integer\" MustBePresent=\"false\"/>\n </Match>\n </AllOf>\n </AnyOf>\n </Target>\n <Rule RuleId=\"urn:com:xacml:rule:id:3350bf37-43d0-4a94-a317-febec81150d8\" Effect=\"Permit\">\n <Target/>\n <ObligationExpressions>\n <ObligationExpression ObligationId=\"test\" FulfillOn=\"Permit\">\n <AttributeAssignmentExpression AttributeId=\"performer\" Category=\"urn:oasis:names:tc:xacml:1.0:subject-category:recipient-subject\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">PDPAction</AttributeValue>\n </AttributeAssignmentExpression>\n <AttributeAssignmentExpression AttributeId=\"type\" Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">REST</AttributeValue>\n </AttributeAssignmentExpression>\n <AttributeAssignmentExpression AttributeId=\"url\" Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#anyURI\">http://localhost:8056/pcd</AttributeValue>\n </AttributeAssignmentExpression>\n <AttributeAssignmentExpression AttributeId=\"method\" Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">GET</AttributeValue>\n </AttributeAssignmentExpression>\n <AttributeAssignmentExpression AttributeId=\"body\" Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#anyURI\">$URLaction/com.Action_patbaction7.json</AttributeValue>\n </AttributeAssignmentExpression>\n </ObligationExpression>\n </ObligationExpressions>\n </Rule>\n</Policy>\n";
+ String jsonFile = "{\"actionAttribute\":\"Memory\"}";
+
+ try{
+ //policy file
+ InputStream in = new ByteArrayInputStream(xmlFile.getBytes());
+ String workspaceDir = "src/test/resources/junitTestCreatedDirectory/"+XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WORKSPACE)+"/admin/"+XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_REPOSITORY);
+ FileUtils.forceMkdir(new File(workspaceDir+"/org/openecomp"));
+ File outFile = new File(workspaceDir+"/org/openecomp/Action_mypol.xml");
+ OutputStream out = new FileOutputStream(outFile);
+ IOUtils.copy(in, out);
+ filePath = outFile.getAbsolutePath();
+ out.close();
+
+ //action body file
+ InputStream actionIn = new ByteArrayInputStream(jsonFile.getBytes());
+ String webappDir = "src/test/resources/junitTestCreatedDirectory/"+XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WORKSPACE);
+ XACMLProperties.setProperty(XACMLRestProperties.PROP_PAP_WEBAPPS, webappDir);
+ String actionDir = Webapps.getActionHome();
+ FileUtils.forceMkdir(new File(actionDir));
+ File actionOutFile = new File(actionDir+"/org.openecomp.Action_mypol.json");
+ OutputStream actionOut = new FileOutputStream(actionOutFile);
+ IOUtils.copy(actionIn, actionOut);
+ actionOut.close();
+
+ }catch(Exception e){
+ //could not run test
+ }
+ PolicyDBDaoTransaction transac = dbd.getNewTransaction();
+ if(filePath != null){
+ try{
+ transac.createPolicy(filePath, "tester");
+ transac.commitTransaction();
+ } catch(Exception e){
+ Assert.fail();
+ }
+ EntityManager getData = emf.createEntityManager();
+ Query getDataQuery = getData.createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:name");
+ getDataQuery.setParameter("scope", "org.openecomp");
+ getDataQuery.setParameter("name","Action_mypol.xml");
+ PolicyEntity result = null;
+ try{
+ result = (PolicyEntity)getDataQuery.getSingleResult();
+ } catch(Exception e){
+ e.printStackTrace();
+ Assert.fail();
+ }
+ Assert.assertEquals(xmlFile, result.getPolicyData());
+ getData.close();
+ result = null;
+ xmlFile = null;
+ try{
+ transac = dbd.getNewTransaction();
+ transac.deletePolicy(filePath);
+ } catch(Exception e){
+ e.printStackTrace();
+ Assert.fail();
+ }
+ Assert.assertTrue(transac.isTransactionOpen());
+ try{
+ transac.deletePolicy(filePath);
+ Assert.fail();
+ } catch(IllegalStateException e){
+ //pass
+ } catch(Exception e){
+ Assert.fail();
+ }
+ transac.commitTransaction();
+ //Assert.assertFalse(transac.isTransactionOpen());
+ try{
+ transac = dbd.getNewTransaction();
+ transac.deletePolicy(filePath);
+ } catch(Exception e){
+ e.printStackTrace();
+ Assert.fail();
+ }
+ transac.commitTransaction();
+ //Assert.assertFalse(transac.isTransactionOpen());
+ String workspaceDir = "src/test/resources/junitTestCreatedDirectory/"+XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WORKSPACE)+"/admin/"+XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_REPOSITORY);
+ PolicyDBDaoTransaction willFail = dbd.getNewTransaction();
+ File fakeFile = new File("directorythatdoesnotexist/"+workspaceDir);
+ try{
+ willFail.createPolicy(fakeFile.getAbsolutePath(), "user1");
+ Assert.fail();
+ } catch(IllegalArgumentException e){
+ if(!e.getMessage().equals("The file path could not be parsed")){
+ Assert.fail();
+ }
+ }
+ willFail.close();
+
+ fakeFile = new File("directorythatdoesnotexist/"+workspaceDir+"/Action_mypol2.xml");
+ willFail = dbd.getNewTransaction();
+ try{
+ willFail.createPolicy(fakeFile.getAbsolutePath(), "user1");
+ Assert.fail();
+ } catch(IllegalArgumentException e){
+ if(!e.getMessage().equals("The file path could not be parsed")){
+ Assert.fail();
+ }
+ }
+ willFail.close();
+
+ fakeFile = new File("directorythatdoesnotexist/"+workspaceDir+"org/openecomp/Action_mypol2.xml");
+ willFail = dbd.getNewTransaction();
+ try{
+ willFail.createPolicy(fakeFile.getAbsolutePath(), "user1");
+ Assert.fail();
+ } catch(IllegalArgumentException e){
+ if(!e.getMessage().equals("The file path does not exist")){
+ Assert.fail();
+ }
+ }
+ willFail.close();
+
+ emf = Persistence.createEntityManagerFactory("testPU");
+ EntityManager aem = emf.createEntityManager();
+ Query actionQuery = aem.createQuery("SELECT a FROM ActionBodyEntity a WHERE a.actionBodyName=:actionBodyName");
+ actionQuery.setParameter("actionBodyName", "org.openecomp.Action_mypol.json");
+ List<?> actionQueryList = actionQuery.getResultList();
+ if(actionQueryList.size() < 1){
+ Assert.fail("ActionBodyEntity not found with actionBodyName=: org.openecomp.Action_mypol.json" );
+ } else if(actionQueryList.size() > 1){
+ //something went wrong
+ Assert.fail("Somehow, more than one ActionBodyEntity with the actionBodyName = org.openecomp.Action_mypol.json");
+ } else {
+ ActionBodyEntity abe = (ActionBodyEntity)actionQueryList.get(0);
+ logger.debug("\n\nPolicyDBDaoTest.transactionTests() Assert.assertEquals"
+ + "\n abe.getActionBody() = " + abe.getActionBody()
+ + "\n jsonFile = " + jsonFile
+ + "\n\n");
+ Assert.assertEquals(abe.getActionBody(),jsonFile);
+ }
+ }
+ }
+
+ @Test
+ public void createFromPolicyObject(){
+ String workspaceDir = "src/test/resources/junitTestCreatedDirectory/"+XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WORKSPACE)+"/admin/"+XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_REPOSITORY);
+ File parentPath = new File(workspaceDir+"/org/openecomp");
+ File scope = new File(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WORKSPACE)+"/admin/"+XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_REPOSITORY));
+ Policy policyObject = new ConfigPolicy();
+ policyObject.policyAdapter = new PolicyRestAdapter();
+ policyObject.policyAdapter.setConfigName("testpolicy1");
+ policyObject.policyAdapter.setParentPath(parentPath.getAbsolutePath());
+ policyObject.policyAdapter.setUserGitPath(scope.getPath());
+ policyObject.policyAdapter.setPolicyDescription("my description");
+ policyObject.policyAdapter.setConfigBodyData("this is my test config file");
+ policyObject.policyAdapter.setPolicyName("testpolicy1");
+ policyObject.policyAdapter.setConfigType(ConfigPolicy.OTHER_CONFIG);
+ policyObject.policyAdapter.setPolicyType("Config");
+ PolicyType policyTypeObject = new PolicyType();
+ policyObject.policyAdapter.setPolicyData(policyTypeObject);
+ PolicyDBDaoTransaction transaction = dbd.getNewTransaction();
+ try{
+ transaction.createPolicy(policyObject, "testuser1");
+ transaction.commitTransaction();
+ } catch(Exception e){
+ transaction.rollbackTransaction();
+ Assert.fail();
+ }
+
+ EntityManager getData = emf.createEntityManager();
+ Query getDataQuery = getData.createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:name");
+ getDataQuery.setParameter("scope", "org.openecomp");
+ getDataQuery.setParameter("name","Config_testpolicy1.xml");
+ PolicyEntity result = null;
+ try{
+ result = (PolicyEntity)getDataQuery.getSingleResult();
+ } catch(Exception e){
+ e.printStackTrace();
+ Assert.fail();
+ }
+ String expectedData;
+ try {
+ expectedData = IOUtils.toString(XACMLPolicyWriter.getXmlAsInputStream(policyTypeObject));
+ } catch (IOException e1) {
+ expectedData = "";
+ }
+ Assert.assertEquals(expectedData, result.getPolicyData());
+ getData.close();
+ result = null;
+ File policyFile = new File(workspaceDir+"/org/openecomp/Config_testpolicy1.xml");
+ try{
+ transaction = dbd.getNewTransaction();
+ transaction.deletePolicy(policyFile.getAbsolutePath());
+ } catch(Exception e){
+ e.printStackTrace();
+ Assert.fail();
+ }
+ Assert.assertTrue(transaction.isTransactionOpen());
+ try{
+ transaction.deletePolicy(policyFile.getAbsolutePath());
+ Assert.fail();
+ } catch(IllegalStateException e){
+ //pass
+ } catch(Exception e){
+ Assert.fail();
+ }
+ transaction.commitTransaction();
+ Assert.assertFalse(transaction.isTransactionOpen());
+ try{
+ transaction = dbd.getNewTransaction();
+ transaction.deletePolicy(policyFile.getAbsolutePath());
+ } catch(Exception e){
+ e.printStackTrace();
+ Assert.fail();
+ }
+ //Assert.assertFalse(transaction.isTransactionOpen());
+ transaction.commitTransaction();
+ }
+
+ @Test
+ public void groupTransactions(){
+ PolicyDBDaoTransaction group = dbd.getNewTransaction();
+ String groupName = "test group 1";
+ try{
+ group.createGroup(PolicyDBDao.createNewPDPGroupId(groupName), groupName, "this is a test group","testuser");
+ group.commitTransaction();
+ } catch(Exception e){
+ group.rollbackTransaction();
+ e.printStackTrace();
+ Assert.fail();
+ }
+ EntityManager em = emf.createEntityManager();
+ Query getGroup = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted");
+ getGroup.setParameter("groupId", PolicyDBDao.createNewPDPGroupId(groupName));
+ getGroup.setParameter("deleted", false);
+ List<?> groups = getGroup.getResultList();
+ if(groups.size() != 1){
+ Assert.fail();
+ }
+ GroupEntity groupEntity = (GroupEntity)groups.get(0);
+ em.close();
+ Assert.assertEquals(groupName, groupEntity.getgroupName());
+ Assert.assertEquals("this is a test group", groupEntity.getDescription());
+ group = dbd.getNewTransaction();
+ try{
+ EcompPDPGroup groupToDelete = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId(groupName),Paths.get("/"));
+ group.deleteGroup(groupToDelete, null,"testuser");
+ group.commitTransaction();
+ } catch(Exception e){
+ group.rollbackTransaction();
+ e.printStackTrace();
+ Assert.fail();
+ }
+ em = emf.createEntityManager();
+ getGroup = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted");
+ getGroup.setParameter("groupId", PolicyDBDao.createNewPDPGroupId(groupName));
+ getGroup.setParameter("deleted", false);
+ groups = getGroup.getResultList();
+ if(groups.size() != 0){
+ System.out.println("Group size: "+groups.size());
+ Assert.fail();
+ }
+ em.close();
+ //add a pdp to a group
+ group = dbd.getNewTransaction();
+ try{
+ group.createGroup(PolicyDBDao.createNewPDPGroupId(groupName), groupName, "test group", "testuser");
+ group.commitTransaction();
+ } catch(Exception e){
+ group.rollbackTransaction();
+ e.printStackTrace();
+ Assert.fail();
+ }
+ group = dbd.getNewTransaction();
+ try{
+ group.addPdpToGroup("http://localhost:4344/pdp/", PolicyDBDao.createNewPDPGroupId(groupName), "primary", "the main pdp", 3232, "testuser");
+ group.commitTransaction();
+ } catch(Exception e){
+ group.rollbackTransaction();
+ e.printStackTrace();
+ Assert.fail();
+ }
+ em = emf.createEntityManager();
+ Query getPdp = em.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted");
+ getPdp.setParameter("pdpId", "http://localhost:4344/pdp/");
+ getPdp.setParameter("deleted", false);
+ List<?> pdps = getPdp.getResultList();
+ if(pdps.size() != 1){
+ System.out.println("Group size: "+pdps.size());
+ Assert.fail();
+ }
+ PdpEntity pdp = (PdpEntity)pdps.get(0);
+ Assert.assertEquals(groupName, pdp.getGroup().getgroupName());
+ Assert.assertEquals(pdp.getPdpName(), "primary");
+ em.close();
+ group = dbd.getNewTransaction();
+ try{
+ group.removePdpFromGroup("http://localhost:4344/pdp/","testuser");
+ group.commitTransaction();
+ } catch(Exception e){
+ group.rollbackTransaction();
+ e.printStackTrace();
+ Assert.fail();
+ }
+ em = emf.createEntityManager();
+ getPdp = em.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted");
+ getPdp.setParameter("pdpId", "http://localhost:4344/pdp/");
+ getPdp.setParameter("deleted", false);
+ pdps = getPdp.getResultList();
+ if(pdps.size() != 0){
+ System.out.println("Group size: "+pdps.size());
+ Assert.fail();
+ }
+ em.close();
+
+ //add some pdps to groups
+ group = dbd.getNewTransaction();
+ try{
+ group.createGroup(PolicyDBDao.createNewPDPGroupId("testgroup1"), "testgroup1", "test group", "testuser");
+ group.commitTransaction();
+ } catch(Exception e){
+ group.rollbackTransaction();
+ e.printStackTrace();
+ Assert.fail();
+ }
+ group = dbd.getNewTransaction();
+ try{
+ group.createGroup(PolicyDBDao.createNewPDPGroupId("testgroup2"), "testgroup2", "test group", "testuser");
+ group.commitTransaction();
+ } catch(Exception e){
+ group.rollbackTransaction();
+ e.printStackTrace();
+ Assert.fail();
+ }
+
+ group = dbd.getNewTransaction();
+ try{
+ group.addPdpToGroup("http://localhost:4344/pdp/", PolicyDBDao.createNewPDPGroupId("testgroup1"), "primary", "the main pdp", 3232, "testuser");
+ group.commitTransaction();
+ } catch(Exception e){
+ group.rollbackTransaction();
+ e.printStackTrace();
+ Assert.fail();
+ }
+ group = dbd.getNewTransaction();
+ try{
+ group.addPdpToGroup("http://localhost:4345/pdp/", PolicyDBDao.createNewPDPGroupId("testgroup1"), "secondary", "the second pdp", 3233, "testuser");
+ group.commitTransaction();
+ } catch(Exception e){
+ group.rollbackTransaction();
+ e.printStackTrace();
+ Assert.fail();
+ }
+ em = emf.createEntityManager();
+ getPdp = em.createQuery("SELECT p FROM PdpEntity p WHERE p.deleted=:deleted");
+ getPdp.setParameter("deleted", false);
+ pdps = getPdp.getResultList();
+ for(Object o : pdps){
+ Assert.assertEquals("testgroup1",((PdpEntity)o).getGroup().getgroupName());
+ }
+ em.close();
+
+ group = dbd.getNewTransaction();
+ try{
+ EcompPDPGroup groupToDelete = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId("testgroup1"),Paths.get("/"));
+ EcompPDPGroup groupToMoveTo = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId("testgroup2"),Paths.get("/"));
+ group.deleteGroup(groupToDelete, groupToMoveTo,"testuser");
+ group.commitTransaction();
+ } catch(Exception e){
+ group.rollbackTransaction();
+ e.printStackTrace();
+ Assert.fail();
+ }
+ em = emf.createEntityManager();
+ getGroup = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted");
+ getGroup.setParameter("groupId", "testgroup1");
+ getGroup.setParameter("deleted", false);
+ groups = getGroup.getResultList();
+ if(groups.size() != 0){
+ System.out.println("Group size: "+groups.size());
+ Assert.fail();
+ }
+ em.close();
+
+ em = emf.createEntityManager();
+ getPdp = em.createQuery("SELECT p FROM PdpEntity p WHERE p.deleted=:deleted");
+ getPdp.setParameter("deleted", false);
+ pdps = getPdp.getResultList();
+ for(Object o : pdps){
+ Assert.assertEquals("testgroup2",((PdpEntity)o).getGroup().getgroupName());
+ }
+ em.close();
+
+ group = dbd.getNewTransaction();
+ try{
+ EcompPDPGroup groupToDelete = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId("testgroup2"),Paths.get("/"));
+ EcompPDPGroup groupToMoveTo = null;
+ group.deleteGroup(groupToDelete, groupToMoveTo,"testuser");
+ group.commitTransaction();
+ Assert.fail();
+ } catch(PAPException pe){
+ //good, can't delete group with pdps
+ group.rollbackTransaction();
+ } catch(Exception e){
+ group.rollbackTransaction();
+ e.printStackTrace();
+ Assert.fail();
+ }
+
+
+ //add policy to group
+
+ //update group
+ EcompPDPGroup pdpGroup = new StdPDPGroup("testgroup2", false, "newtestgroup2", "this is my new description", Paths.get("/"));
+ group = dbd.getNewTransaction();
+ try{
+ group.updateGroup(pdpGroup, "testuser");
+ group.commitTransaction();
+ }catch (Exception e){
+ e.printStackTrace();
+ group.rollbackTransaction();
+ Assert.fail();
+ }
+ em = emf.createEntityManager();
+ getGroup = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted");
+ getGroup.setParameter("groupId", "newtestgroup2");
+ getGroup.setParameter("deleted", false);
+ groups = getGroup.getResultList();
+ if(groups.size() != 1){
+ System.out.println("Group size: "+groups.size());
+ Assert.fail();
+ }
+ em.close();
+ em = emf.createEntityManager();
+ getGroup = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted");
+ getGroup.setParameter("groupId", "testgroup2");
+ getGroup.setParameter("deleted", false);
+ groups = getGroup.getResultList();
+ if(groups.size() != 0){
+ System.out.println("Group size: "+groups.size());
+ Assert.fail();
+ }
+ em.close();
+ //update pdp
+
+ //set group as default
+
+ //move pdp to new group
+
+
+ }
+
+ @Test
+ public void encryptionTest(){
+ try {
+ String encr = d.encryptPassword("testpassword");
+ System.out.println("original password: "+"testpassword");
+ System.out.println("Encrypted password: "+encr);
+ String decr = d.decryptPassword(encr);
+ System.out.println("Decrypted password: "+decr);
+ Assert.assertEquals("testpassword", decr);
+ } catch (Exception e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ Assert.fail();
+ }
+
+ }
+ @Test
+ public void getDescriptionFromXacmlTest(){
+ String myTestDesc = "hello this is a test";
+ String desc = d.getDescriptionFromXacml("<Description>"+myTestDesc+"</Description>");
+ Assert.assertEquals(myTestDesc, desc);
+ }
+
+ @Test
+ public void threadingStabilityTest(){
+ if(logger.isDebugEnabled()){
+ logger.debug("\n\n****************************"
+ + "threadingStabilityTest() entry"
+ + "******************************\n\n");
+ }
+
+ PolicyDBDaoTransaction t = dbd.getNewTransaction();
+ Assert.assertTrue(t.isTransactionOpen());
+ try {
+ //Add 1000 ms to the timeout just to be sure it actually times out
+ int sleepTime = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)) + 1000;
+ if(logger.isDebugEnabled()){
+ Date date= new java.util.Date();
+ logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
+ + "\n sleepTime = " + sleepTime
+ + "\n TimeStamp = " + date.getTime()
+ + "\n\n");
+ }
+ Thread.sleep(sleepTime);
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ if(logger.isDebugEnabled()){
+ Date date= new java.util.Date();
+ logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
+ + "\n Assert.assertFalse(t.isTransactionOpen() = " + t.isTransactionOpen() + ")"
+ + "\n TimeStamp = " + date.getTime()
+ + "\n\n");
+ }
+ Assert.assertFalse(t.isTransactionOpen());
+
+
+ if(logger.isDebugEnabled()){
+ Date date= new java.util.Date();
+ logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
+ + "\n a = dbd.getNewTransaction() "
+ + "\n TimeStamp = " + date.getTime()
+ + "\n\n");
+ }
+ PolicyDBDaoTransaction a = dbd.getNewTransaction();
+ if(logger.isDebugEnabled()){
+ Date date= new java.util.Date();
+ logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
+ + "\n Assert.assertTrue(a.isTransactionOpen() = " + a.isTransactionOpen() + ")"
+ + "\n TimeStamp = " + date.getTime()
+ + "\n\n");
+ }
+ Assert.assertTrue(a.isTransactionOpen());
+
+ try {
+ //Add 1000 ms to the timeout just to be sure it actually times out
+ int sleepTime = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)) + 1000;
+ if(logger.isDebugEnabled()){
+ Date date= new java.util.Date();
+ logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
+ + "\n sleepTime = " + sleepTime
+ + "\n TimeStamp = " + date.getTime()
+ + "\n\n");
+ }
+ Thread.sleep(sleepTime);
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ if(logger.isDebugEnabled()){
+ Date date= new java.util.Date();
+ logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
+ + "\n b = dbd.getNewTransaction() "
+ + "\n TimeStamp = " + date.getTime()
+ + "\n\n");
+ }
+ PolicyDBDaoTransaction b = dbd.getNewTransaction();
+ if(logger.isDebugEnabled()){
+ Date date= new java.util.Date();
+ logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
+ + "\n Assert.assertFalse(a.isTransactionOpen() = " + a.isTransactionOpen() + ")"
+ + "\n TimeStamp = " + date.getTime()
+ + "\n\n");
+ }
+ Assert.assertFalse(a.isTransactionOpen());
+ if(logger.isDebugEnabled()){
+ Date date= new java.util.Date();
+ logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
+ + "\n Assert.assertTrue(b.isTransactionOpen() = " + b.isTransactionOpen() + ")"
+ + "\n TimeStamp = " + date.getTime()
+ + "\n\n");
+ }
+ Assert.assertTrue(b.isTransactionOpen());
+ b.close();
+
+
+
+ //Now let's test the transaction wait time timeout. Shorten the wait time to 1000 ms
+ System.setProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT,"1000");
+ //And let's lengthen the transaction timeout to 5000 ms
+ System.setProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT,"5000");
+ //get a transacton
+ PolicyDBDaoTransaction t1 = dbd.getNewTransaction();
+ if(logger.isDebugEnabled()){
+ Date date= new java.util.Date();
+ logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
+ + "\n Assert.assertTrue(t1.isTransactionOpen() = " + t1.isTransactionOpen() + ")"
+ + "\n TimeStamp = " + date.getTime()
+ + "\n\n");
+ }
+ Assert.assertTrue(t1.isTransactionOpen());
+ //while it is open, get another from a different DB Dao so it will not collide on the synchronized code segment
+ //but will collide at the DB. Remember that the wait time is only 1000 ms
+ try {
+ //Now the 2nd transaction has a wait timeout in 1000 ms
+ PolicyDBDaoTransaction t2 = dbd2.getNewTransaction();
+ /*
+ * Give it plenty of time to time out the second transaction
+ * It will actually hang right here until it either gets the lock from the DB or the
+ * request for the DB lock times out. The timers are very sloppy so, I have given
+ * this plenty of leeway.
+ */
+
+ if(logger.isDebugEnabled()){
+ Date date= new java.util.Date();
+ logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
+ + "\n Thread.sleep(3000)"
+ + "\n TimeStamp = " + date.getTime()
+ + "\n\n");
+ }
+ Thread.sleep(3000);
+ if(logger.isDebugEnabled()){
+ Date date= new java.util.Date();
+ logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
+ + "\n Assert.assertTrue(t1.isTransactionOpen() = " + t1.isTransactionOpen() + ")"
+ + "\n Assert.assertFalse(t2.isTransactionOpen() = " + t2.isTransactionOpen() + ")"
+ + "\n TimeStamp = " + date.getTime()
+ + "\n\n");
+ }
+ //Assert.assertTrue(t1.isTransactionOpen());
+ //Assert.assertFalse(t2.isTransactionOpen());
+
+ Assert.fail("\n\nTransaction timeout of 1000 ms exceeded without a PersistenceException\n\n");
+ } catch (PersistenceException e) {
+ //success
+ if(logger.isDebugEnabled()){
+ Date date= new java.util.Date();
+ logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() "
+ + "\n SUCCESS! Transaction Wait Timeout worked!"
+ + "\n Caught PersistenceException = " + e
+ + "\n TimeStamp = " + date.getTime()
+ + "\n\n");
+ }
+ } catch (Exception e) {
+ // failure due to some other reason
+ if(logger.isDebugEnabled()){
+ Date date= new java.util.Date();
+ logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() FAILURE"
+ + "\n Caught Exception = " + e
+ + "\n TimeStamp = " + date.getTime()
+ + "\n\n");
+ }
+ e.printStackTrace();
+ Assert.fail();
+ }
+
+ if(logger.isDebugEnabled()){
+ Date date= new java.util.Date();
+ logger.debug("\n\nthreadingStabilityTest() exit"
+ + "\n TimeStamp = " + date.getTime()
+ + "\n\n");
+ }
+ }
+
+}
diff --git a/ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/xacml/rest/jpa/PolicyEntityTest.java b/ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/xacml/rest/jpa/PolicyEntityTest.java
new file mode 100644
index 000000000..f71026c39
--- /dev/null
+++ b/ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/xacml/rest/jpa/PolicyEntityTest.java
@@ -0,0 +1,802 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP-PAP-REST
+ * ================================================================================
+ * 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=========================================================
+ */
+
+package org.openecomp.policy.pap.xacml.rest.jpa;
+
+import static org.junit.Assert.*;
+
+//import org.apache.commons.logging.Log;
+//import org.apache.commons.logging.LogFactory;
+import org.junit.*;
+import org.openecomp.policy.rest.XACMLRestProperties;
+import org.openecomp.policy.rest.jpa.ActionBodyEntity;
+import org.openecomp.policy.rest.jpa.ConfigurationDataEntity;
+import org.openecomp.policy.rest.jpa.PolicyDBDaoEntity;
+import org.openecomp.policy.rest.jpa.PolicyEntity;
+
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.EntityTransaction;
+import javax.persistence.Persistence;
+import javax.persistence.Query;
+
+import java.util.Date;
+import java.util.List;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+
+import java.util.Properties;
+
+public class PolicyEntityTest {
+
+ private static Logger logger = FlexLogger.getLogger(PolicyEntityTest.class);
+
+// @Ignore
+ @Test
+ public void testAllOps(){
+ Properties properties = new Properties();
+ properties.put(XACMLRestProperties.PROP_PAP_DB_DRIVER,"org.h2.Driver");
+ properties.put(XACMLRestProperties.PROP_PAP_DB_URL, "jdbc:h2:file:./sql/xacmlTest");
+ properties.put(XACMLRestProperties.PROP_PAP_DB_USER, "sa");
+ properties.put(XACMLRestProperties.PROP_PAP_DB_PASSWORD, "");
+ EntityManagerFactory emf = Persistence.createEntityManagerFactory("testPapPU", properties);
+ EntityManager em = emf.createEntityManager();
+ // Start a transaction
+ EntityTransaction et = em.getTransaction();
+
+ et.begin();
+ //Make sure the DB is clean
+ em.createQuery("DELETE FROM PolicyDBDaoEntity").executeUpdate();
+ em.createQuery("DELETE FROM PolicyEntity").executeUpdate();
+ em.createQuery("DELETE FROM ConfigurationDataEntity").executeUpdate();
+ em.createQuery("DELETE FROM ActionBodyEntity").executeUpdate();
+
+ //Create a policy object
+ PolicyEntity p1 = new PolicyEntity();
+
+ //persist the policy
+ em.persist(p1);
+
+ long policyId1 = p1.getPolicyId();
+
+ String policyName1 = p1.getPolicyName();
+
+ int version1 = p1.getVersion();
+
+ String policyData1 = p1.getPolicyData();
+
+ ConfigurationDataEntity configData1 = p1.getConfigurationData();
+ String configDataStr1 = (configData1!=null ? "configurationDataId = " + configData1.getConfigurationDataId() : "configurationData is null");
+
+ ActionBodyEntity actionBody1 = p1.getActionBodyEntity();
+ String actionBodyStr1 = (actionBody1!=null ? "actionBodyId = " + actionBody1.getActionBodyId() : "actionBody is null");
+
+ String createdBy1 = p1.getCreatedBy();
+
+ Date createdDate1 = p1.getCreatedDate();
+ String createdDateStr1 = (createdDate1 != null ? createdDate1.toString() : "createdDate is null");
+
+ String description = p1.getDescription();
+
+ String modifiedBy1 = p1.getModifiedBy();
+
+ Date modifiedDate1 = p1.getModifiedDate();
+ String modifiedDateStr1 = (modifiedDate1 != null ? modifiedDate1.toString() : "modifiedDate is null");
+
+
+ logger.debug("\n\n********PolicyEntityTest: Local PolicyEntity and Configuration objects before persist*********"
+ + "\npolicyId1 = " + policyId1
+ + "\npolicyName1 = " + policyName1
+ + "\nversion1 = " + version1
+ + "\npolicyData1 = " + policyData1
+ + "\nconfigDataStr1 = " + configDataStr1
+ + "\nactionBodyStr1 = " + actionBodyStr1
+ + "\nscope = " + p1.getScope()
+ + "\ncreatedBy1 = " + createdBy1
+ + "\ncreatedDateStr1 = " + createdDateStr1
+ + "\ndescription = " + description
+ + "\nmodifiedBy1 = " + modifiedBy1
+ + "\nmodifiedDateStr1 = " + modifiedDateStr1
+ + "\ndeleted = " + p1.isDeleted());
+
+ //Set policyID
+ p1.setPolicyName("testPID2");
+
+ //Set policyData
+ p1.setPolicyData("<policy>PolicyData</policy>");
+
+ //We will NOT set the ConfigurationDataEntity or ActionBodyEntity object just to test that it is optional
+
+ //set createdBy
+ p1.setCreatedBy("super-admin");
+
+ //createdDate will be set when it is persisted
+
+ //set scope
+ p1.setScope("com.test");
+
+ //set description
+ p1.setDescription("PolicyEntity Description");
+
+ //set modifiedBy
+ p1.setModifiedBy("super-admin");
+
+ //modifiedDate will be set when it is persisted
+
+ //Flush to the DB
+ em.flush();
+
+ //Now lets get some attribute values
+
+ policyId1 = p1.getPolicyId();
+
+ policyName1 = p1.getPolicyName();
+
+ version1 = p1.getVersion();
+
+ policyData1 = p1.getPolicyData();
+
+ configData1 = p1.getConfigurationData();
+ configDataStr1 = (configData1!=null ? "configurationDataId = " + configData1.getConfigurationDataId() : "configurationData is null");
+
+ actionBody1 = p1.getActionBodyEntity();
+ actionBodyStr1 = (actionBody1!=null ? "actionBodyId = " + actionBody1.getActionBodyId() : "actionBody is null");
+
+ createdBy1 = p1.getCreatedBy();
+
+ createdDate1 = p1.getCreatedDate();
+ createdDateStr1 = (createdDate1 != null ? createdDate1.toString() : "createdDate is null");
+
+ description = p1.getDescription();
+
+ modifiedBy1 = p1.getModifiedBy();
+
+ modifiedDate1 = p1.getModifiedDate();
+ modifiedDateStr1 = (modifiedDate1 != null ? modifiedDate1.toString() : "modifiedDate is null");
+
+ logger.debug("\n\n********PolicyEntityTest: Local PolicyEntity and Configuration objects after persist*********"
+ + "\npolicyId1 = " + policyId1
+ + "\npolicyName1 = " + policyName1
+ + "\nversion1 = " + version1
+ + "\npolicyData1 = " + policyData1
+ + "\nconfigDataStr1 = " + configDataStr1
+ + "\nactionBodyStr1 = " + actionBodyStr1
+ + "\nscopeId = " + p1.getScope()
+ + "\ncreatedBy1 = " + createdBy1
+ + "\ncreatedDateStr1 = " + createdDateStr1
+ + "\ndescription = " + description
+ + "\nmodifiedBy1 = " + modifiedBy1
+ + "\nmodifiedDateStr1 = " + modifiedDateStr1
+ + "\ndeleted = " + p1.isDeleted());
+
+ //Now lets fully configure the configurationData and actionBody
+
+ //Create a ConfigurationDataEntity object and set ID
+ ConfigurationDataEntity c1 = new ConfigurationDataEntity();
+
+ ActionBodyEntity a1 = new ActionBodyEntity();
+
+ //persist the configuration Data
+ em.persist(c1);
+
+ c1.setConfigType("OTHER");
+
+ c1.setConfigBody("ABC");
+
+ c1.setDescription("ConfigurationDataEntity Description");
+
+ c1.setCreatedBy("super-admin");
+
+ c1.setDeleted(true);
+
+ //persist the action Body
+
+ em.persist(a1);
+
+ a1.setActionBody("myActionBody");
+
+ a1.setActionBodyName("myActionBodyName");
+
+ a1.setCreatedBy("super-admin");
+
+ a1.setModifiedBy("super-admin");
+
+ a1.setDeleted(false);
+
+
+ long configurationDataId = c1.getConfigurationDataId();
+
+ int cdVersion = c1.getVersion();
+
+ String cdConfigType = c1.getConfigType();
+
+ String cdConfigBody = c1.getConfigBody();
+
+ String cdCreatedBy = c1.getCreatedBy();
+
+ Date cdCreatedDate = c1.getCreatedDate();
+
+ String cdDescription = c1.getDescription();
+
+ String cdModifiedBy = c1.getModifiedBy();
+
+ Date cdModifiedDate = c1.getModifiedDate();
+
+ logger.debug("\n\n********PolicyEntityTest: Local Configuration object after setting values *********"
+ + "\nconfigurationDataId = " + configurationDataId
+ + "\ncdVersion = " + cdVersion
+ + "\ncdConfigType = " + cdConfigType
+ + "\ncdConfigBody = " + cdConfigBody
+ + "\ncdCreatedBy = " + cdCreatedBy
+ + "\ncdCreatedDate = " + cdCreatedDate
+ + "\ncdDescription = " + cdDescription
+ + "\ncdModifiedBy = " + cdModifiedBy
+ + "\ncdModifiedDate = " + cdModifiedDate
+ + "\ndeleted = " + c1.isDeleted());
+
+
+
+ logger.debug("\n\n********PolicyEntityTest: Local Action Body object after setting values *********"
+ + "\nactionBodyId = " + a1.getActionBodyId()
+ + "\nactionBodyVersion = " + a1.getVersion()
+ + "\nactionBody = " + a1.getActionBody()
+ + "\nactionBodyCeatedBy = " + a1.getCreatedBy()
+ + "\nactionBodyCreatedDate = " + a1.getCreatedDate()
+ + "\nactionBodyModifiedBy = " + a1.getModifiedBy()
+ + "\nactionBodyModifiedDate = " + a1.getModifiedDate()
+ + "\nactionBodyDeleted = " + a1.isDeleted());
+
+ p1.setScope("mckiou.kevin.kim");
+
+ //flush to the db
+ em.flush();
+
+ //Perform policy selects
+
+ Query query = em.createQuery("Select p from PolicyEntity p where p.policyId=:pid");
+ Query queryscope = em.createQuery("Select p from PolicyEntity p where p.scope=:s");
+
+ query.setParameter("pid", p1.getPolicyId());
+ queryscope.setParameter("s", "com.user");
+
+ //Just test that we are retrieving the right object
+ @SuppressWarnings("rawtypes")
+ List psList = queryscope.getResultList();
+ PolicyEntity px = null;
+ if(!psList.isEmpty()){
+ //ignores multiple results
+ px = (PolicyEntity) psList.get(0);
+ }else{
+ fail("\nPolicyEntityTest: No PolicyEntity using scope DB entry found");
+ }
+
+ //The scope object on the retrieved policy object should be same as the one we used to find it
+ assertSame(p1,px);
+
+
+ //Because getSingleResult() throws an unchecked exception which is an indication of a
+ //programming error, we are not going to use it.
+ @SuppressWarnings("rawtypes")
+ List resultList = query.getResultList();
+ PolicyEntity p2 = null;
+ if(!resultList.isEmpty()){
+ // ignores multiple results
+ p2 = (PolicyEntity) resultList.get(0);
+ }else{
+ fail("\nPolicyEntityTest: No PolicyEntity DB entry found");
+ }
+
+ logger.debug("\n\n********PolicyEntityTest: PolicyEntity object after retrieving from DB BEFORE assigning configurationData*********"
+ + "\npolicyId2 = " + p2.getPolicyId()
+ + "\npolicyName2 = " + p2.getPolicyName()
+ + "\nversion2 = " + p2.getVersion()
+ + "\npolicyData2 = " + p2.getPolicyData()
+ + "\nconfigurationData2 = " + (p2.getConfigurationData()!=null ? "configurationDataId = " + p2.getConfigurationData().getConfigurationDataId() : "configurationData is null")
+ + "\nactionBody2 = " + (p2.getActionBodyEntity()!=null ? "actionBodyId = " + p2.getActionBodyEntity().getActionBodyId() : "actionBody is null")
+ + "\nscope2 = " + p2.getScope()
+ + "\ncreatedBy2 = " + p2.getCreatedBy()
+ + "\ncreatedDate2 = " + p2.getCreatedDate()
+ + "\ndescription2 = " + p2.getDescription()
+ + "\nmodifiedBy2 = " + p2.getModifiedBy()
+ + "\nmodifiedDate2 = " + p2.getModifiedDate()
+ + "\ndeleted2 = " + p2.isDeleted());
+
+ //Confirm that the retrieved policy object is the same as the persisted object
+ assertSame(p1,p2);
+
+ //Perform configurationData selects
+ Query query2 = em.createQuery("Select c from ConfigurationDataEntity c where c.configurationDataId=:cid");
+
+ query2.setParameter("cid", c1.getConfigurationDataId());
+
+ //Get the database version of the Configuration Data
+ resultList = query2.getResultList();
+ ConfigurationDataEntity c2 = null;
+ if(!resultList.isEmpty()){
+ // ignores multiple results
+ c2 = (ConfigurationDataEntity) resultList.get(0);
+ }else{
+ fail("\nPolicyEntityTest: No ConfigurationDataEntity DB entry found");
+ }
+
+ logger.debug("\n\n********PolicyEntityTest: Configuration object after retrieving from DB BEFORE assigning to policy*********"
+ + "\nconfigurationDataId2 = " + c2.getConfigurationDataId()
+ + "\nversion2 = " + c2.getVersion()
+ + "\nconfigType2 = " + c2.getConfigType()
+ + "\nconfigBody2 = " + c2.getConfigBody()
+ + "\ncreatedBy2 = " + c2.getCreatedBy()
+ + "\ncreatedDate2 = " + c2.getCreatedDate()
+ + "\ndescription2 = " + c2.getDescription()
+ + "\nmodifiedBy2 = " + c2.getModifiedBy()
+ + "\nmodifiedDate2 = " + c2.getModifiedDate()
+ + "\ndeleted2 = " + c2.isDeleted());
+
+ //Confirm the retrieved ConfigurationDataEntity object is the same as the persisted
+ assertSame(c1,c2);
+
+ //Now assign the configurationData to the policy
+ p1.setConfigurationData(c1);
+
+ //Perform actionBody selects
+ Query querya2 = em.createQuery("Select a from ActionBodyEntity a where a.actionBodyId=:aid");
+
+ querya2.setParameter("aid", a1.getActionBodyId());
+
+ //Get the database version of the Action Body
+ resultList = querya2.getResultList();
+ ActionBodyEntity a2 = null;
+ if(!resultList.isEmpty()){
+ // ignores multiple results
+ a2 = (ActionBodyEntity) resultList.get(0);
+ }else{
+ fail("\nPolicyEntityTest: No ActionBodyEntity DB entry found");
+ }
+
+
+ logger.debug("\n\n********PolicyEntityTest: Local Action Body object after retrieving from DB BEFORE assigning to policy *********"
+ + "\nactionBodyId2 = " + a2.getActionBodyId()
+ + "\nactionBodyVersion2 = " + a2.getVersion()
+ + "\nactionBody2 = " + a2.getActionBody()
+ + "\nactionBodyCeatedBy2 = " + a2.getCreatedBy()
+ + "\nactionBodyCreatedDate2 = " + a2.getCreatedDate()
+ + "\nactionBodyModifiedBy2 = " + a2.getModifiedBy()
+ + "\nactionBodyModifiedDate2 = " + a2.getModifiedDate()
+ + "\nactionBodyDeleted2 = " + a2.isDeleted());
+
+
+ //Confirm the retrieved ActionBodyEntity object is the same as the persisted
+ assertSame(a1,a2);
+
+ //Now assign the ActionBodyEntity to the policy
+ p1.setActionBodyEntity(a1);
+
+ em.flush();
+
+ //Let's retrieve the policy, configurationData and actionBody from the DB and look at them
+ //Here is the policy object
+ resultList = query.getResultList();
+ p2 = null;
+ if(!resultList.isEmpty()){
+ // ignores multiple results
+ p2 = (PolicyEntity) resultList.get(0);
+ }else{
+ fail("PolicyEntityTest: No PolicyEntity DB entry found");
+ }
+
+ logger.debug("\n\n********PolicyEntityTest: PolicyEntity object after retrieving from DB AFTER assigning configurationData*********"
+ + "\npolicyId2 = " + p2.getPolicyId()
+ + "\npolicyName2 = " + p2.getPolicyName()
+ + "\nversion2 = " + p2.getVersion()
+ + "\npolicyData2 = " + p2.getPolicyData()
+ + "\nconfigurationData2 = " + (p2.getConfigurationData()!=null ? "configurationDataId = " + p2.getConfigurationData().getConfigurationDataId() : "configurationData is null")
+ + "\nactionBody2 = " + (p2.getActionBodyEntity()!=null ? "actionBodyId = " + p2.getActionBodyEntity().getActionBodyId() : "actionBody is null")
+ + "\nscope2 = " + p2.getScope()
+ + "\ncreatedBy2 = " + p2.getCreatedBy()
+ + "\ncreatedDate2 = " + p2.getCreatedDate()
+ + "\ndescription2 = " + p2.getDescription()
+ + "\nmodifiedBy2 = " + p2.getModifiedBy()
+ + "\nmodifiedDate2 = " + p2.getModifiedDate()
+ + "\ndeleted2 = " + p2.isDeleted());
+
+ //And now the ConfigurationDataEntity object
+ resultList = query2.getResultList();
+ c2 = null;
+ if(!resultList.isEmpty()){
+ // ignores multiple results
+ c2 = (ConfigurationDataEntity) resultList.get(0);
+ }else{
+ fail("\nPolicyEntityTest: No ConfigurationDataEntity DB entry found");
+ }
+
+ logger.debug("\n\n********PolicyEntityTest: Configuration object after retrieving from DB AFTER assigning to policy*********"
+ + "\nconfigurationDataId2 = " + c2.getConfigurationDataId()
+ + "\nversion2 = " + c2.getVersion()
+ + "\nconfigType2 = " + c2.getConfigType()
+ + "\nconfigBody2 = " + c2.getConfigBody()
+ + "\ncreatedBy2 = " + c2.getCreatedBy()
+ + "\ncreatedDate2 = " + c2.getCreatedDate()
+ + "\ndescription2 = " + c2.getDescription()
+ + "\nmodifiedBy = " + c2.getModifiedBy()
+ + "\nmodifiedDate = " + c2.getModifiedDate()
+ + "\ndeleted2 = " + c2.isDeleted());
+
+
+ //Get the database version of the Action Body
+ resultList = querya2.getResultList();
+ a2 = null;
+ if(!resultList.isEmpty()){
+ // ignores multiple results
+ a2 = (ActionBodyEntity) resultList.get(0);
+ }else{
+ fail("\nPolicyEntityTest: No ActionBodyEntity DB entry found");
+ }
+
+
+ logger.debug("\n\n********PolicyEntityTest: Local Action Body object after retrieving from DB AFTER assigning to policy *********"
+ + "\nactionBodyId2 = " + a2.getActionBodyId()
+ + "\nactionBodyVersion2 = " + a2.getVersion()
+ + "\nactionBody2 = " + a2.getActionBody()
+ + "\nactionBodyCeatedBy2 = " + a2.getCreatedBy()
+ + "\nactionBodyCreatedDate2 = " + a2.getCreatedDate()
+ + "\nactionBodyModifiedBy2 = " + a2.getModifiedBy()
+ + "\nactionBodyModifiedDate2 = " + a2.getModifiedDate()
+ + "\nactionBodyDeleted2 = " + a2.isDeleted());
+
+
+ //****Now lets see if the orphanRemoval=true does anything useful***
+ //Remove the configurationData from the policy relationship
+
+ p1.setConfigurationData(null);
+
+ p1.setActionBodyEntity(null);
+
+ //flush the update to the DB
+ em.flush();
+
+ //Attempt to retrieve the configuration data object from the db. It should not be there
+ //Reusing the previous query
+ resultList = query2.getResultList();
+ c2 = null;
+ if(resultList.isEmpty()){
+ logger.debug("\n\n********PolicyEntityTest: orphanRemoval=true******"
+ + "\n Success!! No ConfigurationDataEntity DB entry found");
+
+ }else{
+ c2 = (ConfigurationDataEntity) resultList.get(0);
+ fail("\nPolicyEntityTest: ConfigurationDataEntity DB entry found - and none should exist"
+ + "\nconfigurationDataId = " + c2.getConfigurationDataId());
+ }
+
+ //Attempt to retrieve the actionBody data object from the db. It should not be there
+ //Reusing the previous query
+ resultList = querya2.getResultList();
+ a2 = null;
+ if(resultList.isEmpty()){
+ logger.debug("\n\n********PolicyEntityTest: orphanRemoval=true******"
+ + "\n Success!! No ActionBodyEntity DB entry found");
+
+ }else{
+ a2 = (ActionBodyEntity) resultList.get(0);
+ fail("\nPolicyEntityTest: ActionBodyEntity DB entry found - and none should exist"
+ + "\nactionBodyId = " + a2.getActionBodyId());
+ }
+
+ //Now lets put the configurationData and actionBody back into the policy object and see what appears
+ //in the DB after a flush
+
+ //put c1 back into the persistence context since the orphanRemoval removed it.
+ em.persist(c1);
+ p1.setConfigurationData(c1);
+
+ em.persist(a1);
+ p1.setActionBodyEntity(a1);
+
+ em.flush();
+
+ //retrieve the policy object
+ resultList = query.getResultList();
+ p2 = null;
+ if(!resultList.isEmpty()){
+ // ignores multiple results
+ p2 = (PolicyEntity) resultList.get(0);
+ }else{
+ fail("\nPolicyEntityTest: No PolicyEntity DB entry found");
+ }
+
+ //output what we policy object found
+ logger.debug("\n\n********PolicyEntityTest: PolicyEntity object after again adding ConfigurationDataEntity and retrieving from DB*********"
+ + "\npolicyId2 = " + p2.getPolicyId()
+ + "\npolicyName2 = " + p2.getPolicyName()
+ + "\nversion2 = " + p2.getVersion()
+ + "\npolicyData2 = " + p2.getPolicyData()
+ + "\nconfigurationData2 = " + (p2.getConfigurationData()!=null ? "configurationDataId = " + p2.getConfigurationData().getConfigurationDataId() : "configurationData is null")
+ + "\nactionBody2 = " + (p2.getActionBodyEntity()!=null ? "actionBodyId = " + p2.getActionBodyEntity().getActionBodyId() : "actionBody is null")
+ + "\nscope2 = " + p2.getScope()
+ + "\ncreatedBy2 = " + p2.getCreatedBy()
+ + "\ncreatedDate2 = " + p2.getCreatedDate()
+ + "\ndescription2 = " + p2.getDescription()
+ + "\nmodifiedBy2 = " + p2.getModifiedBy()
+ + "\nmodifiedDate2 = " + p2.getModifiedDate()
+ + "\ndeleted2 = " + p2.isDeleted());
+
+
+ //now lets see if it put the configurationData c1 back into the table
+ resultList = query2.getResultList();
+ c2 = null;
+ if(!resultList.isEmpty()){
+ // ignores multiple results
+ c2 = (ConfigurationDataEntity) resultList.get(0);
+ }else{
+ fail("\nPolicyEntityTest - Check re-entry of configurationData into DB"
+ + "No ConfigurationDataEntity DB entry found");
+ }
+
+ //output what configurationData object we found
+ logger.debug("\n\n********PolicyEntityTest: Configuration object after re-enter into policy object and retrieving from DB *********"
+ + "\nconfigurationDataId2 = " + c2.getConfigurationDataId()
+ + "\nversion2 = " + c2.getVersion()
+ + "\nconfigType2 = " + c2.getConfigType()
+ + "\nconfigBody2 = " + c2.getConfigBody()
+ + "\ncreatedBy2 = " + c2.getCreatedBy()
+ + "\ncreatedDate2 = " + c2.getCreatedDate()
+ + "\ndescription2 = " + c2.getDescription()
+ + "\nmodifiedBy = " + c2.getModifiedBy()
+ + "\nmodifiedDate = " + c2.getModifiedDate()
+ + "\ndeleted2 = " + c2.isDeleted());
+
+ //now lets see if it put the actionBody a1 back into the table
+ //Get the database version of the Action Body
+ resultList = querya2.getResultList();
+ a2 = null;
+ if(!resultList.isEmpty()){
+ // ignores multiple results
+ a2 = (ActionBodyEntity) resultList.get(0);
+ }else{
+ fail("\nPolicyEntityTest - Check re-entry of actionBody into DB"
+ + "No ActionBodyEntity DB entry found");
+ }
+
+ logger.debug("\n\n********PolicyEntityTest: Local Action Body object after re-enter into policy object and retrieving from DB *********"
+ + "\nactionBodyId2 = " + a2.getActionBodyId()
+ + "\nactionBodyVersion2 = " + a2.getVersion()
+ + "\nactionBody2 = " + a2.getActionBody()
+ + "\nactionBodyCeatedBy2 = " + a2.getCreatedBy()
+ + "\nactionBodyCreatedDate2 = " + a2.getCreatedDate()
+ + "\nactionBodyModifiedBy2 = " + a2.getModifiedBy()
+ + "\nactionBodyModifiedDate2 = " + a2.getModifiedDate()
+ + "\nactionBodyDeleted2 = " + a2.isDeleted());
+
+ //I want to save all the above in the DB
+ try{
+ et.commit();
+ logger.debug("\n\n***********PolicyEntityTest: et.commit Succeeded********");
+ }catch(Exception e){
+ logger.debug("\n\n***********PolicyEntityTest: et.commit Failed********"
+ + "\nTRANSACTION ROLLBACK "
+ + "\n with exception: " + e);
+ }
+
+ // Start a new transaction
+ EntityTransaction et2 = em.getTransaction();
+
+ et2.begin();
+
+ //Let's test if the PolicyEntity uniqueConstraint for policyName and scopeId hold
+ PolicyEntity p3 = new PolicyEntity();
+ em.persist(p3);
+
+
+ //first let's assure that you can save with the same name but a different scope
+ p3.setPolicyName(p1.getPolicyName());
+ p3.setScope("mckiou.kevin.kory");
+ em.flush();
+ logger.debug("\n\n***********PolicyEntityTest: PolicyEntity Unique test for policyName and scope********"
+ + "\nSuccess! PolicyEntity uniqueness constraint allowed "
+ + "\n policyId1 " + p1.getPolicyId()
+ + "\n policyName1 " + p1.getPolicyName()
+ + "\n scope1 = " + p1.getScope()
+ + "\n policyId3 " + p3.getPolicyId()
+ + "\n policyName3 " + p3.getPolicyName()
+ + "\n scope3 = " + p3.getScope());
+
+ //Assert that the policyIds are NOT the same to show that the automatic sequencing is working
+ assert(p1.getPolicyId() != p3.getPolicyId());
+
+ try{
+ //Now set the scope the same to verify the uniqueness constraint will be enforced
+ p3.setScope(p1.getScope());
+
+ em.flush();
+ fail("\n\n***********PolicyEntityTest: PolicyEntity Unique test for policyName and scope********"
+ + "\nFailed! PolicyEntity Uniqueness constraint FAILED and DID allow "
+ + "\n policyId1 " + p1.getPolicyId()
+ + "\n policyName1 " + p1.getPolicyName()
+ + "\n scope1 = " + p1.getScope()
+ + "\n policyId3 " + p3.getPolicyId()
+ + "\n policyName3 " + p3.getPolicyName()
+ + "\n scope3 = " + p3.getScope());;
+ }
+ catch(Exception e){
+ //Success
+ logger.debug("\n\n***********PolicyEntityTest: PolicyEntity Unique test for policyName and scope********"
+ + "\nSuccess! PolicyEntity Uniqueness constraint SUCCEEDED and did NOT allow "
+ + "\n policyId1 " + p1.getPolicyId()
+ + "\n policyName1 " + p1.getPolicyName()
+ + "\n scope1 = " + p1.getScope()
+ + "\n policyId3 " + p3.getPolicyId()
+ + "\n policyName3 " + p3.getPolicyName()
+ + "\n scope3 = " + p3.getScope()
+ + "\n with excpetion: " + e);
+ }
+
+
+ try{
+ et2.commit();
+ logger.debug("\n\n***********PolicyEntityTest: et2.commit Succeeded********");
+ }catch(Exception e){
+ logger.debug("\n\n***********PolicyEntityTest: et2.commit Failed********"
+ + "\nTRANSACTION ROLLBACK "
+ + "\n with exception: " + e);
+ }
+
+ //****************Test the PolicyDBDaoEntity************************
+
+ //Create a transaction
+ EntityTransaction et3 = em.getTransaction();
+
+ et3.begin();
+
+ //create one
+ PolicyDBDaoEntity pe1 = new PolicyDBDaoEntity();
+ em.persist(pe1);
+
+ pe1.setDescription("This is pe1");
+
+ pe1.setPolicyDBDaoUrl("http://10.11.12.13:2345");
+
+ //push it to the DB
+ em.flush();
+
+ //create another
+ PolicyDBDaoEntity pe2 = new PolicyDBDaoEntity();
+ em.persist(pe2);
+
+ pe2.setDescription("This is pe2");
+
+ pe2.setPolicyDBDaoUrl("http://10.11.12.13:2345");
+
+ //Print them to the log before flushing
+ logger.debug("\n\n***********PolicyEntityTest: PolicyDBDaoEntity objects before flush********"
+ + "\n policyDBDaoUrl-1 = " + pe1.getPolicyDBDaoUrl()
+ + "\n description-1 = " + pe1.getDescription()
+ + "\n createdDate-1 = " + pe1.getCreatedDate()
+ + "\n modifiedDate-1 " + pe1.getModifiedDate()
+ + "\n*****************************************"
+ + "\n policyDBDaoUrl-2 = " + pe2.getPolicyDBDaoUrl()
+ + "\n description-2 = " + pe2.getDescription()
+ + "\n createdDate-2 = " + pe2.getCreatedDate()
+ + "\n modifiedDate-2 " + pe2.getModifiedDate()
+ );
+
+ //push it to the DB
+ em.flush();
+
+ //Now let's retrieve them from the DB using the named query
+
+ resultList = em.createNamedQuery("PolicyDBDaoEntity.findAll").getResultList();
+
+ PolicyDBDaoEntity pex = null;
+ PolicyDBDaoEntity pey = null;
+
+ if(!resultList.isEmpty()){
+ if (resultList.size() != 2){
+ fail("\nPolicyEntityTest: Number of PolicyDBDaoEntity entries = " + resultList.size() + " instead of 2");
+ }
+ for(Object policyDBDaoEntity: resultList){
+ PolicyDBDaoEntity pdbdao = (PolicyDBDaoEntity)policyDBDaoEntity;
+ if(pdbdao.getPolicyDBDaoUrl().equals("http://10.11.12.13:2345")){
+ pex = pdbdao;
+ }else if(pdbdao.getPolicyDBDaoUrl().equals("http://10.11.12.13:2345")){
+ pey = pdbdao;
+ }
+ }
+
+ //Print them to the log before flushing
+ logger.debug("\n\n***********PolicyEntityTest: PolicyDBDaoEntity objects retrieved from DB********"
+ + "\n policyDBDaoUrl-x = " + pex.getPolicyDBDaoUrl()
+ + "\n description-x = " + pex.getDescription()
+ + "\n createdDate-x = " + pex.getCreatedDate()
+ + "\n modifiedDate-x " + pex.getModifiedDate()
+ + "\n*****************************************"
+ + "\n policyDBDaoUrl-y = " + pey.getPolicyDBDaoUrl()
+ + "\n description-y = " + pey.getDescription()
+ + "\n createdDate-y = " + pey.getCreatedDate()
+ + "\n modifiedDate-y " + pey.getModifiedDate()
+ );
+ //Verify the retrieved objects are the same as the ones we stored in the DB
+ if(pex.getPolicyDBDaoUrl().equals("http://10.11.12.13:2345")){
+ assertSame(pe1,pex);
+ assertSame(pe2,pey);
+ }else{
+ assertSame(pe2,pex);
+ assertSame(pe1,pey);
+ }
+
+ }else{
+ fail("\nPolicyEntityTest: No PolicyDBDaoEntity DB entry found");
+ }
+
+ //Now let's see if we can do an update on the PolicyDBDaoEntity which we retrieved.
+ //em.persist(pex);
+ pex.setDescription("This is pex");
+ em.flush();
+
+ //retrieve it
+ Query createPolicyQuery = em.createQuery("SELECT p FROM PolicyDBDaoEntity p WHERE p.description=:desc");
+ resultList = createPolicyQuery.setParameter("desc", "This is pex").getResultList();
+
+ PolicyDBDaoEntity pez = null;
+
+ if(!resultList.isEmpty()){
+ if (resultList.size() != 1){
+ fail("\nPolicyEntityTest: Update Test - Number of PolicyDBDaoEntity entries = " + resultList.size() + " instead of 1");
+ }
+ pez = (PolicyDBDaoEntity) resultList.get(0);
+
+ //Print them to the log before flushing
+ logger.debug("\n\n***********PolicyEntityTest: Update Test - PolicyDBDaoEntity objects retrieved from DB********"
+ + "\n policyDBDaoUrl-x = " + pex.getPolicyDBDaoUrl()
+ + "\n description-x = " + pex.getDescription()
+ + "\n createdDate-x = " + pex.getCreatedDate()
+ + "\n modifiedDate-x " + pex.getModifiedDate()
+ + "\n*****************************************"
+ + "\n policyDBDaoUrl-z = " + pez.getPolicyDBDaoUrl()
+ + "\n description-z = " + pez.getDescription()
+ + "\n createdDate-z = " + pez.getCreatedDate()
+ + "\n modifiedDate-z " + pez.getModifiedDate()
+ );
+ //Verify the retrieved objects are the same as the ones we stored in the DB
+ assertSame(pex,pez);
+ }else{
+ fail("\nPolicyEntityTest: Update Test - No PolicyDBDaoEntity DB updated entry found");
+ }
+
+ //Clean up the DB
+ em.createQuery("DELETE FROM PolicyDBDaoEntity").executeUpdate();
+ em.createQuery("DELETE FROM PolicyEntity").executeUpdate();
+ em.createQuery("DELETE FROM ConfigurationDataEntity").executeUpdate();
+ em.createQuery("DELETE FROM ActionBodyEntity").executeUpdate();
+
+ //Wrap up the transaction
+ try{
+ et3.commit();
+ logger.debug("\n\n***********PolicyEntityTest: et3.commit Succeeded********");
+ }catch(Exception e){
+ logger.debug("\n\n***********PolicyEntityTest: et3.commit Failed********"
+ + "\nTRANSACTION ROLLBACK "
+ + "\n with exception: " + e);
+ }
+
+
+ //Tidy up
+ em.close();
+ }
+
+}