diff options
Diffstat (limited to 'controlloop/common')
39 files changed, 2014 insertions, 1543 deletions
diff --git a/controlloop/common/database/pom.xml b/controlloop/common/database/pom.xml index 4ae467c56..8c31cb63a 100644 --- a/controlloop/common/database/pom.xml +++ b/controlloop/common/database/pom.xml @@ -61,6 +61,12 @@ <artifactId>assertj-core</artifactId> <scope>test</scope> </dependency> + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-core</artifactId> + <version>2.13.0</version> + <scope>test</scope> + </dependency> </dependencies> <build> <plugins> diff --git a/controlloop/common/database/src/main/java/org/onap/policy/database/operationshistory/CountRecentOperationsPip.java b/controlloop/common/database/src/main/java/org/onap/policy/database/operationshistory/CountRecentOperationsPip.java index 1f73ed3ce..7b6f13611 100644 --- a/controlloop/common/database/src/main/java/org/onap/policy/database/operationshistory/CountRecentOperationsPip.java +++ b/controlloop/common/database/src/main/java/org/onap/policy/database/operationshistory/CountRecentOperationsPip.java @@ -27,11 +27,12 @@ import com.att.research.xacml.api.pip.PIPRequest; import com.att.research.xacml.api.pip.PIPResponse; import com.att.research.xacml.std.pip.StdMutablePIPResponse; import com.att.research.xacml.std.pip.StdPIPResponse; -import com.google.common.base.Strings; import java.util.Arrays; import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; import java.util.Properties; -import javax.persistence.Persistence; +import java.util.Set; import org.onap.policy.database.ToscaDictionary; import org.onap.policy.database.std.StdOnapPip; import org.slf4j.Logger; @@ -42,6 +43,9 @@ public class CountRecentOperationsPip extends StdOnapPip { public static final String ISSUER_NAME = "count-recent-operations"; private static Logger logger = LoggerFactory.getLogger(CountRecentOperationsPip.class); + private static final Set<String> TIME_WINDOW_SCALES = Collections + .unmodifiableSet(new HashSet<>(Arrays.asList("minute", "hour", "day", "week", "month", "year"))); + public CountRecentOperationsPip() { super(); } @@ -53,25 +57,7 @@ public class CountRecentOperationsPip extends StdOnapPip { @Override public void configure(String id, Properties properties) throws PIPException { - super.configure(id, properties); - // - // Create our entity manager - // - em = null; - try { - // - // In case there are any overloaded properties for the JPA - // - Properties emProperties = new Properties(properties); - // - // Create the entity manager factory - // - em = Persistence.createEntityManagerFactory( - properties.getProperty(ISSUER_NAME + ".persistenceunit"), - emProperties).createEntityManager(); - } catch (Exception e) { - logger.error("Persistence failed {} operations history db {}", e.getLocalizedMessage(), e); - } + super.configure(id, properties, ISSUER_NAME); } /** @@ -85,23 +71,11 @@ public class CountRecentOperationsPip extends StdOnapPip { public PIPResponse getAttributes(PIPRequest pipRequest, PIPFinder pipFinder) throws PIPException { logger.debug("getAttributes requesting attribute {} of type {} for issuer {}", pipRequest.getAttributeId(), pipRequest.getDataTypeId(), pipRequest.getIssuer()); - // - // Determine if the issuer is correct - // - if (Strings.isNullOrEmpty(pipRequest.getIssuer())) { - logger.debug("issuer is null - returning empty response"); - // - // We only respond to ourself as the issuer - // - return StdPIPResponse.PIP_RESPONSE_EMPTY; - } - if (! pipRequest.getIssuer().startsWith(ToscaDictionary.GUARD_ISSUER_PREFIX)) { - logger.debug("Issuer does not start with guard"); - // - // We only respond to ourself as the issuer - // + + if (isRequestInvalid(pipRequest)) { return StdPIPResponse.PIP_RESPONSE_EMPTY; } + // // Parse out the issuer which denotes the time window // Eg: any-prefix:tw:10:minute @@ -156,12 +130,7 @@ public class CountRecentOperationsPip extends StdOnapPip { // // Compute the time window // - if (! "minute".equalsIgnoreCase(timeWindowScale) - && ! "hour".equalsIgnoreCase(timeWindowScale) - && ! "day".equalsIgnoreCase(timeWindowScale) - && ! "week".equalsIgnoreCase(timeWindowScale) - && ! "month".equalsIgnoreCase(timeWindowScale) - && ! "year".equalsIgnoreCase(timeWindowScale)) { + if (! TIME_WINDOW_SCALES.contains(timeWindowScale.toLowerCase())) { // // Unsupported // @@ -197,7 +166,7 @@ public class CountRecentOperationsPip extends StdOnapPip { .setParameter(4, timeWindowScale) .setParameter(5, timeWindowVal * -1) .getSingleResult(); - } catch (Exception e) { + } catch (RuntimeException e) { logger.error("Named query failed ", e); } // @@ -209,10 +178,10 @@ public class CountRecentOperationsPip extends StdOnapPip { // logger.info("operations query returned {}", result); // - // Should get back a long + // Should get back a number // - if (result instanceof Long) { - return ((Long) result).intValue(); + if (result instanceof Number) { + return ((Number) result).intValue(); } // // We shouldn't really get this result, but just diff --git a/controlloop/common/database/src/main/java/org/onap/policy/database/operationshistory/GetOperationOutcomePip.java b/controlloop/common/database/src/main/java/org/onap/policy/database/operationshistory/GetOperationOutcomePip.java index 20c8f028a..5a0db0501 100644 --- a/controlloop/common/database/src/main/java/org/onap/policy/database/operationshistory/GetOperationOutcomePip.java +++ b/controlloop/common/database/src/main/java/org/onap/policy/database/operationshistory/GetOperationOutcomePip.java @@ -25,12 +25,10 @@ import com.att.research.xacml.api.pip.PIPRequest; import com.att.research.xacml.api.pip.PIPResponse; import com.att.research.xacml.std.pip.StdMutablePIPResponse; import com.att.research.xacml.std.pip.StdPIPResponse; -import com.google.common.base.Strings; import java.util.Arrays; import java.util.Collection; import java.util.Properties; import javax.persistence.NoResultException; -import javax.persistence.Persistence; import org.onap.policy.database.ToscaDictionary; import org.onap.policy.database.std.StdOnapPip; import org.slf4j.Logger; @@ -52,25 +50,7 @@ public class GetOperationOutcomePip extends StdOnapPip { @Override public void configure(String id, Properties properties) throws PIPException { - super.configure(id, properties); - // - // Create our entity manager - // - em = null; - try { - // - // In case there are any overloaded properties for the JPA - // - Properties emProperties = new Properties(properties); - // - // Create the entity manager factory - // - em = Persistence.createEntityManagerFactory( - properties.getProperty(ISSUER_NAME + ".persistenceunit"), - emProperties).createEntityManager(); - } catch (Exception e) { - logger.error("Persistence failed {} operations history db {}", e.getLocalizedMessage(), e); - } + super.configure(id, properties, ISSUER_NAME); } /** @@ -84,31 +64,28 @@ public class GetOperationOutcomePip extends StdOnapPip { public PIPResponse getAttributes(PIPRequest pipRequest, PIPFinder pipFinder) throws PIPException { logger.debug("getAttributes requesting attribute {} of type {} for issuer {}", pipRequest.getAttributeId(), pipRequest.getDataTypeId(), pipRequest.getIssuer()); - // - // Determine if the issuer is correct - // - if (Strings.isNullOrEmpty(pipRequest.getIssuer())) { - logger.debug("issuer is null - returning empty response"); - // - // We only respond to ourself as the issuer - // - return StdPIPResponse.PIP_RESPONSE_EMPTY; - } - if (! pipRequest.getIssuer().startsWith(ToscaDictionary.GUARD_ISSUER_PREFIX)) { - logger.debug("Issuer does not start with guard"); - // - // We only respond to ourself as the issuer - // + + if (isRequestInvalid(pipRequest)) { return StdPIPResponse.PIP_RESPONSE_EMPTY; } + // // Parse out the issuer which denotes the time window // Eg: any-prefix:clname:some-controlloop-name // String[] s1 = pipRequest.getIssuer().split("clname:"); String clname = s1[1]; - String target = null; - target = getTarget(pipFinder); + String target = getTarget(pipFinder); + // + // Sanity check + // + if (target == null) { + // + // See if we have all the values + // + logger.error("missing attributes return empty"); + return StdPIPResponse.PIP_RESPONSE_EMPTY; + } logger.debug("Going to query DB about: clname={}, target={}", clname, target); String outcome = doDatabaseQuery(clname, target); diff --git a/controlloop/common/database/src/main/java/org/onap/policy/database/std/StdOnapPip.java b/controlloop/common/database/src/main/java/org/onap/policy/database/std/StdOnapPip.java index a94727371..1416b3ef9 100644 --- a/controlloop/common/database/src/main/java/org/onap/policy/database/std/StdOnapPip.java +++ b/controlloop/common/database/src/main/java/org/onap/policy/database/std/StdOnapPip.java @@ -39,6 +39,8 @@ import java.util.Collections; import java.util.Iterator; import java.util.Properties; import javax.persistence.EntityManager; +import javax.persistence.Persistence; +import org.apache.commons.lang3.StringUtils; import org.onap.policy.database.ToscaDictionary; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -74,11 +76,65 @@ public abstract class StdOnapPip extends StdConfigurableEngine { return Collections.emptyList(); } - @Override - public void configure(String id, Properties properties) throws PIPException { + /** + * Configures this object and initializes {@link #em}. + * + * @param id name of this engine + * @param properties configuration properties + * @param issuerName name of this issuer, used to identify the persistence unit + * @throws PIPException if an error occurs + */ + protected void configure(String id, Properties properties, String issuerName) throws PIPException { super.configure(id, properties); logger.debug("Configuring historyDb PIP {}", properties); this.properties = properties; + + // + // Create our entity manager + // + em = null; + try { + // + // In case there are any overloaded properties for the JPA + // + Properties emProperties = new Properties(properties); + // + // Create the entity manager factory + // + em = Persistence.createEntityManagerFactory( + properties.getProperty(issuerName + ".persistenceunit"), + emProperties).createEntityManager(); + } catch (Exception e) { + logger.error("Persistence failed {} operations history db {}", e.getLocalizedMessage(), e); + } + } + + /** + * Determines if a request is valid. + * + * @param pipRequest request to validate + * @return {@code true} if the request is <i>NOT</i> valid, {@code false} if it is + */ + protected boolean isRequestInvalid(PIPRequest pipRequest) { + // + // Determine if the issuer is correct + // + if (StringUtils.isBlank(pipRequest.getIssuer())) { + logger.debug("issuer is null - returning empty response"); + // + // We only respond to ourself as the issuer + // + return true; + } + if (! pipRequest.getIssuer().startsWith(ToscaDictionary.GUARD_ISSUER_PREFIX)) { + logger.debug("Issuer does not start with guard"); + // + // We only respond to ourself as the issuer + // + return true; + } + + return false; } protected String getActor(PIPFinder pipFinder) { @@ -150,14 +206,16 @@ public abstract class StdOnapPip extends StdConfigurableEngine { } protected String findFirstAttributeValue(PIPResponse pipResponse) { - for (Attribute attribute: pipResponse.getAttributes()) { - Iterator<AttributeValue<String>> iterAttributeValues = attribute.findValues(DataTypes.DT_STRING); - if (iterAttributeValues != null) { - while (iterAttributeValues.hasNext()) { - String value = iterAttributeValues.next().getValue(); - if (value != null) { - return value; - } + for (Attribute attribute : pipResponse.getAttributes()) { + Iterator<AttributeValue<String>> iterAttributeValues = attribute.findValues(DataTypes.DT_STRING); + if (iterAttributeValues == null) { + continue; + } + + while (iterAttributeValues.hasNext()) { + String value = iterAttributeValues.next().getValue(); + if (value != null) { + return value; } } } @@ -165,31 +223,25 @@ public abstract class StdOnapPip extends StdConfigurableEngine { } protected void addIntegerAttribute(StdMutablePIPResponse stdPipResponse, Identifier category, - Identifier attributeId, int value, PIPRequest pipRequest) { - AttributeValue<BigInteger> attributeValue = null; + Identifier attributeId, int value, PIPRequest pipRequest) { try { - attributeValue = DataTypes.DT_INTEGER.createAttributeValue(value); + AttributeValue<BigInteger> attributeValue = DataTypes.DT_INTEGER.createAttributeValue(value); + stdPipResponse.addAttribute(new StdMutableAttribute(category, attributeId, attributeValue, + pipRequest.getIssuer(), false)); } catch (Exception e) { logger.error("Failed to convert {} to integer {}", value, e); } - if (attributeValue != null) { - stdPipResponse.addAttribute(new StdMutableAttribute(category, attributeId, attributeValue, - pipRequest.getIssuer(), false)); - } } protected void addStringAttribute(StdMutablePIPResponse stdPipResponse, Identifier category, Identifier attributeId, - String value, PIPRequest pipRequest) { - AttributeValue<String> attributeValue = null; + String value, PIPRequest pipRequest) { try { - attributeValue = DataTypes.DT_STRING.createAttributeValue(value); + AttributeValue<String> attributeValue = DataTypes.DT_STRING.createAttributeValue(value); + stdPipResponse.addAttribute(new StdMutableAttribute(category, attributeId, attributeValue, + pipRequest.getIssuer(), false)); } catch (Exception ex) { logger.error("Failed to convert {} to an AttributeValue<String>", value, ex); } - if (attributeValue != null) { - stdPipResponse.addAttribute(new StdMutableAttribute(category, attributeId, attributeValue, - pipRequest.getIssuer(), false)); - } } } diff --git a/controlloop/common/database/src/test/java/org/onap/policy/database/operationshistory/CountRecentOperationsPipTest.java b/controlloop/common/database/src/test/java/org/onap/policy/database/operationshistory/CountRecentOperationsPipTest.java index e3cb17fd5..66b412028 100644 --- a/controlloop/common/database/src/test/java/org/onap/policy/database/operationshistory/CountRecentOperationsPipTest.java +++ b/controlloop/common/database/src/test/java/org/onap/policy/database/operationshistory/CountRecentOperationsPipTest.java @@ -19,31 +19,54 @@ package org.onap.policy.database.operationshistory; import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import com.att.research.xacml.api.Attribute; +import com.att.research.xacml.api.AttributeValue; +import com.att.research.xacml.api.XACML3; +import com.att.research.xacml.api.pip.PIPException; +import com.att.research.xacml.api.pip.PIPFinder; +import com.att.research.xacml.api.pip.PIPRequest; +import com.att.research.xacml.api.pip.PIPResponse; +import com.att.research.xacml.std.pip.StdPIPResponse; import java.io.FileInputStream; -import java.lang.reflect.Method; import java.sql.Date; import java.time.Instant; - +import java.util.Collection; import java.util.Properties; import java.util.UUID; - import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.Query; - import org.junit.AfterClass; +import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; +import org.onap.policy.database.ToscaDictionary; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CountRecentOperationsPipTest { + private static final String ID = "issuer"; private static final Logger LOGGER = LoggerFactory.getLogger(CountRecentOperationsPipTest.class); - private static CountRecentOperationsPip pipEngine; + private static final String ISSUER = ToscaDictionary.GUARD_ISSUER_PREFIX + "-my-issuer:tw:1:HOUR"; + private static final String ACTOR = "Controller"; + private static final String RECIPE = "operationA"; + private static final String TARGET = "vnf-1"; + private static final String EXPECTED_EXCEPTION = "expected exception"; + + private static MyPip pipEngine; + private static Properties properties; + private static EntityManagerFactory emf; private static EntityManager em; + private PIPRequest req; + /** * Create an instance of our engine and also the persistence * factory. @@ -51,23 +74,23 @@ public class CountRecentOperationsPipTest { * @throws Exception connectivity issues */ @BeforeClass - public static void setup() throws Exception { + public static void setUpBeforeClass() throws Exception { LOGGER.info("Setting up PIP Testing"); // // Create instance // - pipEngine = new CountRecentOperationsPip(); + pipEngine = new MyPip(); // // Load our test properties to use // - Properties properties = new Properties(); + properties = new Properties(); try (FileInputStream is = new FileInputStream("src/test/resources/test.properties")) { properties.load(is); } // // Configure it using properties // - pipEngine.configure("issuer", properties); + pipEngine.configure(ID, properties); LOGGER.info("PIP configured now creating our entity manager"); LOGGER.info("properties {}", properties); // @@ -75,12 +98,18 @@ public class CountRecentOperationsPipTest { // String persistenceUnit = CountRecentOperationsPip.ISSUER_NAME + ".persistenceunit"; LOGGER.info("persistenceunit {}", persistenceUnit); - em = Persistence.createEntityManagerFactory(properties.getProperty(persistenceUnit), properties) - .createEntityManager(); + emf = Persistence.createEntityManagerFactory(properties.getProperty(persistenceUnit), properties); + em = emf.createEntityManager(); // // // - LOGGER.info("Configured own entity manager", em.toString()); + LOGGER.info("Configured own entity manager"); + } + + @Before + public void setUp() { + req = mock(PIPRequest.class); + when(req.getIssuer()).thenReturn(ISSUER); } private Dbao createEntry(String cl, String target, String outcome) { @@ -91,8 +120,8 @@ public class CountRecentOperationsPipTest { newEntry.setClosedLoopName(cl); newEntry.setTarget(target); newEntry.setOutcome(outcome); - newEntry.setActor("Controller"); - newEntry.setOperation("operationA"); + newEntry.setActor(ACTOR); + newEntry.setOperation(RECIPE); newEntry.setStarttime(Date.from(Instant.now().minusMillis(20000))); newEntry.setEndtime(Date.from(Instant.now())); newEntry.setRequestId(UUID.randomUUID().toString()); @@ -100,35 +129,64 @@ public class CountRecentOperationsPipTest { } @Test - public void testGetCountFromDb() throws Exception { - // - // Use reflection to run getCountFromDB - // - Method method = CountRecentOperationsPip.class.getDeclaredMethod("doDatabaseQuery", - String.class, - String.class, - String.class, - int.class, - String.class); - method.setAccessible(true); - // - // create entry - // - Dbao newEntry = createEntry("cl-foobar-1", "vnf-1", "SUCCESS"); - // - // Test pipEngine - // - int count = (int) method.invoke(pipEngine, newEntry.getActor(), newEntry.getOperation(), newEntry.getTarget(), - 1, "HOUR"); + public void testAttributesRequired() { + assertEquals(3, pipEngine.attributesRequired().size()); + } + + @Test + public void testGetAttributes_InvalidRequestInfo() throws PIPException { + // invalid request - null issuer + when(req.getIssuer()).thenReturn(null); + assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(req, null)); + + /* + * Make a valid issuer in the request, for subsequent tests. + */ + when(req.getIssuer()).thenReturn(ISSUER); + + // null actor + MyPip pip = new MyPip() { + @Override + protected String getActor(PIPFinder pipFinder) { + return null; + } + }; + pip.configure(ID, properties); + assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pip.getAttributes(req, null)); + + // null recipe + pip = new MyPip() { + @Override + protected String getRecipe(PIPFinder pipFinder) { + return null; + } + }; + pip.configure(ID, properties); + assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pip.getAttributes(req, null)); + + // null target + pip = new MyPip() { + @Override + protected String getTarget(PIPFinder pipFinder) { + return null; + } + }; + pip.configure(ID, properties); + assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pip.getAttributes(req, null)); + } + + @Test + public void testDoDatabaseQuery() throws Exception { + // // No entries yet // - assertEquals(0, count); + assertEquals(0, getCount(pipEngine.getAttributes(req, null))); // // Add entry // em.getTransaction().begin(); - em.persist(newEntry); + em.persist(createEntry("cl-foobar-1", TARGET, "SUCCESS")); em.getTransaction().commit(); // // Directly check ground truth @@ -137,14 +195,67 @@ public class CountRecentOperationsPipTest { .setParameter(1, 1); LOGGER.info("{} entries", queryCount.getSingleResult()); // - // Test pipEngine - // - count = (int) method.invoke(pipEngine, newEntry.getActor(), newEntry.getOperation(), newEntry.getTarget(), - 1, "HOUR"); - // // Should count 1 entry now // - assertEquals(1, count); + assertEquals(1, getCount(pipEngine.getAttributes(req, null))); + } + + @Test + public void testDoDatabaseQuery_InvalidTimeWindow() throws Exception { + when(req.getIssuer()).thenReturn(ISSUER + "invalid time window"); + + assertEquals(-1, getCount(pipEngine.getAttributes(req, null))); + } + + @Test + public void testDoDatabaseQuery_NullEm() throws Exception { + assertEquals(-1, getCount(new MyPip().getAttributes(req, null))); + } + + @Test + public void testDoDatabaseQuery_EmException() throws Exception { + MyPip pip = new MyPip() { + @Override + public void configure(String id, Properties properties) throws PIPException { + em = mock(EntityManager.class); + when(em.createNativeQuery(any())).thenThrow(new RuntimeException(EXPECTED_EXCEPTION)); + } + }; + pip.configure(ID, properties); + + assertEquals(-1, getCount(pip.getAttributes(req, null))); + } + + @Test + public void testDoDatabaseQuery_NonNumeric() throws Exception { + MyPip pip = new MyPip() { + @Override + public void configure(String id, Properties properties) throws PIPException { + em = mock(EntityManager.class); + Query query = mock(Query.class); + when(em.createNativeQuery(any())).thenReturn(query); + when(query.setParameter(anyInt(), any())).thenReturn(query); + when(query.getSingleResult()).thenReturn("200"); + } + }; + pip.configure(ID, properties); + + assertEquals(200, getCount(pip.getAttributes(req, null))); + } + + private int getCount(PIPResponse resp) { + Collection<Attribute> attrs = resp.getAttributes(); + assertEquals(1, attrs.size()); + + Attribute attr = attrs.iterator().next(); + assertEquals(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, attr.getCategory()); + assertEquals(ToscaDictionary.ID_RESOURCE_GUARD_OPERATIONCOUNT, attr.getAttributeId()); + + Collection<AttributeValue<?>> values = attr.getValues(); + assertEquals(1, values.size()); + + AttributeValue<?> value = values.iterator().next(); + return ((Number) value.getValue()).intValue(); } /** @@ -152,9 +263,26 @@ public class CountRecentOperationsPipTest { */ @AfterClass public static void cleanup() { - if (em != null) { - em.close(); + if (emf != null) { + emf.close(); } } + private static class MyPip extends CountRecentOperationsPip { + + @Override + protected String getActor(PIPFinder pipFinder) { + return ACTOR; + } + + @Override + protected String getRecipe(PIPFinder pipFinder) { + return RECIPE; + } + + @Override + protected String getTarget(PIPFinder pipFinder) { + return TARGET; + } + } } diff --git a/controlloop/common/database/src/test/java/org/onap/policy/database/operationshistory/GetOperationOutcomePipTest.java b/controlloop/common/database/src/test/java/org/onap/policy/database/operationshistory/GetOperationOutcomePipTest.java index 7e7258c5f..5ab850722 100644 --- a/controlloop/common/database/src/test/java/org/onap/policy/database/operationshistory/GetOperationOutcomePipTest.java +++ b/controlloop/common/database/src/test/java/org/onap/policy/database/operationshistory/GetOperationOutcomePipTest.java @@ -19,27 +19,57 @@ package org.onap.policy.database.operationshistory; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import com.att.research.xacml.api.Attribute; +import com.att.research.xacml.api.AttributeValue; +import com.att.research.xacml.api.XACML3; +import com.att.research.xacml.api.pip.PIPException; +import com.att.research.xacml.api.pip.PIPFinder; +import com.att.research.xacml.api.pip.PIPRequest; +import com.att.research.xacml.api.pip.PIPResponse; +import com.att.research.xacml.std.pip.StdPIPResponse; import java.io.FileInputStream; -import java.lang.reflect.Method; import java.sql.Date; import java.time.Instant; +import java.util.Collection; import java.util.Properties; import java.util.UUID; import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.NoResultException; import javax.persistence.Persistence; import org.junit.AfterClass; +import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; +import org.onap.policy.database.ToscaDictionary; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class GetOperationOutcomePipTest { + private static final String ID = "issuer"; + private static final String TEST_CL1 = "testcl1"; + private static final String TEST_TARGET1 = "testtarget1"; + private static final String TEST_TARGET2 = "testtarget2"; + private static final String ACTOR = "Controller"; + private static final String RECIPE = "operationA"; + private static final String EXPECTED_EXCEPTION = "expected exception"; + private static final String ISSUER_PREFIX = ToscaDictionary.GUARD_ISSUER_PREFIX + "-my-issuer:clname:"; + private static final String ISSUER = ISSUER_PREFIX + TEST_CL1; private static final Logger LOGGER = LoggerFactory.getLogger(GetOperationOutcomePipTest.class); - private static GetOperationOutcomePip pipEngine; + private static MyPip pipEngine; + private static Properties properties; + + private static EntityManagerFactory emf; private static EntityManager em; + private PIPRequest req; + /** * Create an instance of our engine and also the persistence * factory. @@ -47,23 +77,23 @@ public class GetOperationOutcomePipTest { * @throws Exception connectivity issues */ @BeforeClass - public static void setup() throws Exception { + public static void setUpBeforeClass() throws Exception { LOGGER.info("Setting up PIP Testing"); // // Create instance // - pipEngine = new GetOperationOutcomePip(); + pipEngine = new MyPip(TEST_TARGET1); // // Load our test properties to use // - Properties properties = new Properties(); + properties = new Properties(); try (FileInputStream is = new FileInputStream("src/test/resources/test.properties")) { properties.load(is); } // // Configure it using properties // - pipEngine.configure("issuer", properties); + pipEngine.configure(ID, properties); LOGGER.info("PIP configured now creating our entity manager"); LOGGER.info("properties {}", properties); // @@ -71,14 +101,20 @@ public class GetOperationOutcomePipTest { // String persistenceUnit = GetOperationOutcomePip.ISSUER_NAME + ".persistenceunit"; LOGGER.info("persistenceunit {}", persistenceUnit); - em = Persistence.createEntityManagerFactory(properties.getProperty(persistenceUnit), properties) - .createEntityManager(); + emf = Persistence.createEntityManagerFactory(properties.getProperty(persistenceUnit), properties); + em = emf.createEntityManager(); // // // LOGGER.info("Configured own entity manager", em.toString()); } + @Before + public void setUp() { + req = mock(PIPRequest.class); + when(req.getIssuer()).thenReturn(ISSUER); + } + private void insertEntry(String cl, String target, String outcome) { // // Create entry @@ -87,8 +123,8 @@ public class GetOperationOutcomePipTest { newEntry.setClosedLoopName(cl); newEntry.setTarget(target); newEntry.setOutcome(outcome); - newEntry.setActor("Controller"); - newEntry.setOperation("operationA"); + newEntry.setActor(ACTOR); + newEntry.setOperation(RECIPE); newEntry.setStarttime(Date.from(Instant.now().minusMillis(20000))); newEntry.setEndtime(Date.from(Instant.now())); newEntry.setRequestId(UUID.randomUUID().toString()); @@ -102,43 +138,104 @@ public class GetOperationOutcomePipTest { @Test - public void testGetOutcomeFromDb() throws Exception { - // - // Use reflection to run getCountFromDB - // - Method method = GetOperationOutcomePip.class.getDeclaredMethod("doDatabaseQuery", - String.class, - String.class); - method.setAccessible(true); + public void testAttributesRequired() { + assertEquals(1, pipEngine.attributesRequired().size()); + } + + @Test + public void testGetAttributes_InvalidRequestInfo() throws PIPException { + // invalid request - null issuer + when(req.getIssuer()).thenReturn(null); + assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(req, null)); + + /* + * Make a valid issuer in the request, for subsequent tests. + */ + when(req.getIssuer()).thenReturn(ISSUER); + + // null target + MyPip pip = new MyPip(null); + pip.configure(ID, properties); + assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pip.getAttributes(req, null)); + } + + @Test + public void testDoDatabaseQuery() throws Exception { // // Insert entry // - insertEntry("testcl1", "testtarget1", "1"); - // - // Test pipEngine - // - String outcome = (String) method.invoke(pipEngine, "testcl1", "testtarget1"); + insertEntry(TEST_CL1, TEST_TARGET1, "1"); // // outcome should be "1" // - assertEquals("1", outcome); + assertEquals("1", getOutcome(pipEngine.getAttributes(req, null))); // // Insert more entries // - insertEntry("testcl1", "testtarget1", "2"); - insertEntry("testcl2", "testtarget2", "3"); - insertEntry("testcl1", "testtarget2", "4"); + insertEntry(TEST_CL1, TEST_TARGET1, "2"); + insertEntry("testcl2", TEST_TARGET2, "3"); + insertEntry(TEST_CL1, TEST_TARGET2, "4"); // // Test pipEngine // - outcome = (String) method.invoke(pipEngine, "testcl1", "testtarget1"); - assertEquals("2", outcome); + assertEquals("2", getOutcome(TEST_CL1, TEST_TARGET1)); - outcome = (String) method.invoke(pipEngine, "testcl2", "testtarget2"); - assertEquals("3", outcome); + assertEquals("3", getOutcome("testcl2", TEST_TARGET2)); - outcome = (String) method.invoke(pipEngine, "testcl1", "testtarget2"); - assertEquals("4", outcome); + assertEquals("4", getOutcome(TEST_CL1, TEST_TARGET2)); + } + + @Test + public void testDoDatabaseQuery_NoResult() throws Exception { + MyPip pip = new MyPip(TEST_TARGET1) { + @Override + public void configure(String id, Properties properties) throws PIPException { + em = mock(EntityManager.class); + when(em.createQuery(anyString())).thenThrow(new NoResultException()); + } + }; + pip.configure(ID, properties); + + assertNull(getOutcome(pip.getAttributes(req, null))); + } + + @Test + public void testDoDatabaseQuery_EmException() throws Exception { + MyPip pip = new MyPip(TEST_TARGET1) { + @Override + public void configure(String id, Properties properties) throws PIPException { + em = mock(EntityManager.class); + when(em.createQuery(anyString())).thenThrow(new RuntimeException(EXPECTED_EXCEPTION)); + } + }; + pip.configure(ID, properties); + + assertEquals(null, getOutcome(pip.getAttributes(req, null))); + } + + private String getOutcome(String clname, String target) throws PIPException { + req = mock(PIPRequest.class); + when(req.getIssuer()).thenReturn(ISSUER_PREFIX + clname); + + MyPip pip = new MyPip(target); + pip.configure(ID, properties); + + return getOutcome(pip.getAttributes(req, null)); + } + + private String getOutcome(PIPResponse resp) { + Collection<Attribute> attrs = resp.getAttributes(); + assertEquals(1, attrs.size()); + + Attribute attr = attrs.iterator().next(); + assertEquals(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, attr.getCategory()); + assertEquals(ToscaDictionary.ID_RESOURCE_GUARD_OPERATIONOUTCOME, attr.getAttributeId()); + + Collection<AttributeValue<?>> values = attr.getValues(); + assertEquals(1, values.size()); + + AttributeValue<?> value = values.iterator().next(); + return (String) value.getValue(); } /** @@ -146,9 +243,31 @@ public class GetOperationOutcomePipTest { */ @AfterClass public static void cleanup() { - if (em != null) { - em.close(); + if (emf != null) { + emf.close(); } } + private static class MyPip extends GetOperationOutcomePip { + private String target; + + public MyPip(String target) { + this.target = target; + } + + @Override + protected String getActor(PIPFinder pipFinder) { + return ACTOR; + } + + @Override + protected String getRecipe(PIPFinder pipFinder) { + return RECIPE; + } + + @Override + protected String getTarget(PIPFinder pipFinder) { + return target; + } + } } diff --git a/controlloop/common/database/src/test/java/org/onap/policy/database/std/DbaoTest.java b/controlloop/common/database/src/test/java/org/onap/policy/database/std/DbaoTest.java new file mode 100644 index 000000000..43c6157cf --- /dev/null +++ b/controlloop/common/database/src/test/java/org/onap/policy/database/std/DbaoTest.java @@ -0,0 +1,70 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.database.std; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.Date; +import org.junit.Test; +import org.onap.policy.database.operationshistory.Dbao; + +public class DbaoTest { + + @Test + public void test() { + Dbao dao = new Dbao(); + + dao.setActor("my-actor"); + dao.setClosedLoopName("cl-name"); + Date endDate = new Date(); + dao.setEndtime(endDate); + dao.setId(100L); + dao.setMessage("my-message"); + dao.setOperation("my-operation"); + dao.setOutcome("my-outcome"); + dao.setRequestId("my-request"); + Date startDate = new Date(endDate.getTime() - 1); + dao.setStarttime(startDate); + dao.setSubrequestId("my-sub"); + dao.setTarget("my-target"); + + assertEquals("my-actor", dao.getActor()); + assertEquals("cl-name", dao.getClosedLoopName()); + assertEquals(endDate, dao.getEndtime()); + assertEquals(100L, dao.getId().longValue()); + assertEquals("my-message", dao.getMessage()); + assertEquals("my-operation", dao.getOperation()); + assertEquals("my-outcome", dao.getOutcome()); + assertEquals("my-request", dao.getRequestId()); + assertEquals(startDate, dao.getStarttime()); + assertEquals("my-sub", dao.getSubrequestId()); + assertEquals("my-target", dao.getTarget()); + + assertTrue(dao.toString().startsWith("Dbao")); + + int hc = dao.hashCode(); + dao.setId(101L); + assertTrue(hc != dao.hashCode()); + + assertTrue(dao.equals(dao)); + assertFalse(dao.equals(new Dbao())); + } +} diff --git a/controlloop/common/database/src/test/java/org/onap/policy/database/std/StdOnapPipTest.java b/controlloop/common/database/src/test/java/org/onap/policy/database/std/StdOnapPipTest.java new file mode 100644 index 000000000..de186c41d --- /dev/null +++ b/controlloop/common/database/src/test/java/org/onap/policy/database/std/StdOnapPipTest.java @@ -0,0 +1,268 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.database.std; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.att.research.xacml.api.Attribute; +import com.att.research.xacml.api.AttributeValue; +import com.att.research.xacml.api.Identifier; +import com.att.research.xacml.api.Status; +import com.att.research.xacml.api.pip.PIPException; +import com.att.research.xacml.api.pip.PIPFinder; +import com.att.research.xacml.api.pip.PIPRequest; +import com.att.research.xacml.api.pip.PIPResponse; +import com.att.research.xacml.std.datatypes.DataTypes; +import com.att.research.xacml.std.pip.StdMutablePIPResponse; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.function.Function; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.database.ToscaDictionary; + +public class StdOnapPipTest { + private static final String EXPECTED_EXCEPTION = "expected exception"; + private static final String A_VALUE = "a-value"; + private static final String ISSUER = ToscaDictionary.GUARD_ISSUER_PREFIX + "-my-issuer"; + + private MyPip pip; + private PIPRequest req; + private PIPFinder finder; + private StdMutablePIPResponse resp; + + /** + * Initializes mocks and populates {@link #pip}. + */ + @Before + public void setUp() { + req = mock(PIPRequest.class); + finder = mock(PIPFinder.class); + resp = new StdMutablePIPResponse(); + + when(req.getIssuer()).thenReturn(ISSUER); + + pip = new MyPip(); + } + + @Test + public void testAttributesProvided() { + assertTrue(pip.attributesProvided().isEmpty()); + } + + @Test + public void testIsRequestInvalid() { + // valid issuer + when(req.getIssuer()).thenReturn(ISSUER); + assertFalse(pip.isRequestInvalid(req)); + + // invalid issuer + when(req.getIssuer()).thenReturn("bogus-issuer"); + assertTrue(pip.isRequestInvalid(req)); + + // null issuer + when(req.getIssuer()).thenReturn(null); + assertTrue(pip.isRequestInvalid(req)); + } + + @Test + public void testGetActor() { + testGetArbitraryAttribute(StdOnapPip.PIP_REQUEST_ACTOR, pip2 -> pip2.getActor(finder)); + } + + @Test + public void testGetRecipe() { + testGetArbitraryAttribute(StdOnapPip.PIP_REQUEST_RECIPE, pip2 -> pip2.getRecipe(finder)); + } + + @Test + public void testGetTarget() { + testGetArbitraryAttribute(StdOnapPip.PIP_REQUEST_TARGET, pip2 -> pip2.getTarget(finder)); + } + + private void testGetArbitraryAttribute(PIPRequest request, Function<StdOnapPip, String> getter) { + // target found + pip = new MyPip() { + @Override + protected PIPResponse getAttribute(PIPRequest pipRequest, PIPFinder pipFinder) { + return resp; + } + + @Override + protected String findFirstAttributeValue(PIPResponse pipResponse) { + return A_VALUE; + } + }; + + pip = spy(pip); + + assertEquals(A_VALUE, getter.apply(pip)); + verify(pip).getAttribute(request, finder); + verify(pip).findFirstAttributeValue(resp); + + + // not found + pip = new MyPip() { + @Override + protected PIPResponse getAttribute(PIPRequest pipRequest, PIPFinder pipFinder) { + return null; + } + + @Override + protected String findFirstAttributeValue(PIPResponse pipResponse) { + return A_VALUE; + } + }; + + pip = spy(pip); + + assertNull(getter.apply(pip)); + verify(pip).getAttribute(request, finder); + verify(pip, never()).findFirstAttributeValue(resp); + } + + @Test + public void testGetAttribute() throws PIPException { + when(finder.getMatchingAttributes(req, pip)).thenReturn(resp); + + Status status = mock(Status.class); + Identifier ident = mock(Identifier.class); + + when(ident.stringValue()).thenReturn("my-attr-id"); + when(req.getAttributeId()).thenReturn(ident); + + // status != OK + resp.setStatus(status); + when(status.isOk()).thenReturn(false); + assertNull(pip.getAttribute(req, finder)); + + // status OK, empty attributes + resp.setStatus(status); + when(status.isOk()).thenReturn(true); + assertNull(pip.getAttribute(req, finder)); + + // status OK, has attributes + resp.setStatus(status); + when(status.isOk()).thenReturn(true); + resp.setAttributes(Arrays.asList(mock(Attribute.class))); + assertSame(resp, pip.getAttribute(req, finder)); + + // null status, has attributes + resp.setStatus(null); + resp.setAttributes(Arrays.asList(mock(Attribute.class))); + assertSame(resp, pip.getAttribute(req, finder)); + + // with exception + when(finder.getMatchingAttributes(req, pip)).thenThrow(new PIPException()); + assertNull(pip.getAttribute(req, finder)); + } + + @Test + public void testFindFirstAttributeValue() { + + // no attributes + resp.setAttributes(Collections.emptyList()); + assertNull(pip.findFirstAttributeValue(resp)); + + // attribute that returns null + Attribute attr = mock(Attribute.class); + resp.setAttributes(Arrays.asList(attr, attr)); + assertNull(pip.findFirstAttributeValue(resp)); + + // attribute that returns a list of null values + Attribute attr2 = mock(Attribute.class); + resp.setAttributes(Arrays.asList(attr, attr2)); + List<AttributeValue<String>> lst = Arrays.asList(makeAttr(null), makeAttr(null)); + when(attr.findValues(DataTypes.DT_STRING)).thenReturn(lst.iterator()); + assertNull(pip.findFirstAttributeValue(resp)); + + // non-null value in the middle of the list + lst = Arrays.asList(makeAttr(null), makeAttr(A_VALUE), makeAttr(null)); + when(attr.findValues(DataTypes.DT_STRING)).thenReturn(lst.iterator()); + assertEquals(A_VALUE, pip.findFirstAttributeValue(resp)); + } + + private AttributeValue<String> makeAttr(String value) { + @SuppressWarnings("unchecked") + AttributeValue<String> attrval = mock(AttributeValue.class); + + when(attrval.getValue()).thenReturn(value); + + return attrval; + } + + @Test + public void testAddIntegerAttribute() { + resp = spy(resp); + + Identifier cat = mock(Identifier.class); + Identifier attrid = mock(Identifier.class); + + pip.addIntegerAttribute(resp, cat, attrid, 100, req); + + verify(resp).addAttribute(any()); + + // try with exception + doThrow(new RuntimeException(EXPECTED_EXCEPTION)).when(resp).addAttribute(any()); + pip.addIntegerAttribute(resp, cat, attrid, 100, req); + } + + @Test + public void testAddStringAttribute() { + resp = spy(resp); + + Identifier cat = mock(Identifier.class); + Identifier attrid = mock(Identifier.class); + + pip.addStringAttribute(resp, cat, attrid, A_VALUE, req); + + verify(resp).addAttribute(any()); + + // try with exception + doThrow(new RuntimeException(EXPECTED_EXCEPTION)).when(resp).addAttribute(any()); + pip.addStringAttribute(resp, cat, attrid, A_VALUE, req); + } + + private class MyPip extends StdOnapPip { + + @Override + public Collection<PIPRequest> attributesRequired() { + return Collections.emptyList(); + } + + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPFinder pipFinder) throws PIPException { + return null; + } + + } +} diff --git a/controlloop/common/database/src/test/resources/META-INF/persistence.xml b/controlloop/common/database/src/test/resources/META-INF/persistence.xml index 0c49d94e2..202850d96 100644 --- a/controlloop/common/database/src/test/resources/META-INF/persistence.xml +++ b/controlloop/common/database/src/test/resources/META-INF/persistence.xml @@ -19,7 +19,8 @@ ============LICENSE_END========================================================= --> -<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence persistence_1_0.xsd" version="1.0"> +<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://java.sun.com/xml/ns/persistence persistence_1_0.xsd" version="1.0"> <persistence-unit name="PipEngineTest" transaction-type="RESOURCE_LOCAL"> <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> @@ -29,13 +30,13 @@ <properties> <property name="eclipselink.ddl-generation" value="create-tables" /> <property name="eclipselink.logging.level" value="FINE" /> - <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/> + <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" /> <property name="javax.persistence.jdbc.driver" value="org.h2.Driver" /> <property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:testdb;DATABASE_TO_UPPER=FALSE" /> <property name="javax.persistence.jdbc.user" value="policy" /> <property name="javax.persistence.jdbc.password" value="P01icY" /> - <property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/> - <property name="javax.persistence.schema-generation.create-source" value="metadata"/> + <property name="javax.persistence.schema-generation.database.action" value="drop-and-create" /> + <property name="javax.persistence.schema-generation.create-source" value="metadata" /> </properties> </persistence-unit> diff --git a/controlloop/common/eventmanager/pom.xml b/controlloop/common/eventmanager/pom.xml index e1621e597..bb5d903c5 100644 --- a/controlloop/common/eventmanager/pom.xml +++ b/controlloop/common/eventmanager/pom.xml @@ -142,6 +142,11 @@ <scope>test</scope> </dependency> <dependency> + <groupId>org.assertj</groupId> + <artifactId>assertj-core</artifactId> + <scope>test</scope> + </dependency> + <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <scope>provided</scope> diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManager.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManager.java index b82a5f8e5..57df6b3f4 100644 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManager.java +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManager.java @@ -24,13 +24,19 @@ import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; +import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; +import java.util.Set; import java.util.UUID; +import java.util.stream.Collectors; +import org.apache.commons.lang3.StringUtils; import org.onap.policy.aai.AaiCqResponse; import org.onap.policy.aai.AaiGetVnfResponse; import org.onap.policy.aai.AaiGetVserverResponse; @@ -90,6 +96,16 @@ public class ControlLoopEventManager implements LockCallback, Serializable { private static final Logger logger = LoggerFactory.getLogger(ControlLoopEventManager.class); private static final long serialVersionUID = -1216568161322872641L; + + private static final Set<String> VALID_TARGETS; + + static { + VALID_TARGETS = Collections.unmodifiableSet(new HashSet<>( + Arrays.asList(VM_NAME, VNF_NAME, VSERVER_VSERVER_NAME, + GENERIC_VNF_VNF_ID, GENERIC_VNF_VNF_NAME) + .stream().map(String::toLowerCase).collect(Collectors.toList()))); + } + public final String closedLoopControlName; private final UUID requestId; @@ -308,18 +324,7 @@ public class ControlLoopEventManager implements LockCallback, Serializable { * @throws ControlLoopException if an error occurs */ public VirtualControlLoopNotification isControlLoopFinal() throws ControlLoopException { - // - // Check if they activated us - // - if (!this.isActivated) { - throw new ControlLoopException("ControlLoopEventManager MUST be activated first."); - } - // - // Make sure we are expecting this call. - // - if (this.onset == null) { - throw new ControlLoopException("No onset event for ControlLoopEventManager."); - } + validateFinalControlLoop(); // // Ok, start creating the notification // @@ -374,14 +379,7 @@ public class ControlLoopEventManager implements LockCallback, Serializable { return notification; } - /** - * Process the control loop. - * - * @return a ControlLoopOperationManager - * @throws ControlLoopException if an error occurs - * @throws AaiException if an error occurs retrieving information from A&AI - */ - public ControlLoopOperationManager processControlLoop() throws ControlLoopException, AaiException { + private void validateFinalControlLoop() throws ControlLoopException { // // Check if they activated us // @@ -394,6 +392,17 @@ public class ControlLoopEventManager implements LockCallback, Serializable { if (this.onset == null) { throw new ControlLoopException("No onset event for ControlLoopEventManager."); } + } + + /** + * Process the control loop. + * + * @return a ControlLoopOperationManager + * @throws ControlLoopException if an error occurs + * @throws AaiException if an error occurs retrieving information from A&AI + */ + public ControlLoopOperationManager processControlLoop() throws ControlLoopException, AaiException { + validateFinalControlLoop(); // // Is there a current operation? // @@ -692,12 +701,8 @@ public class ControlLoopEventManager implements LockCallback, Serializable { * @throws ControlLoopException if an error occurs */ public void checkEventSyntax(VirtualControlLoopEvent event) throws ControlLoopException { - if (event.getClosedLoopEventStatus() == null - || (event.getClosedLoopEventStatus() != ControlLoopEventStatus.ONSET - && event.getClosedLoopEventStatus() != ControlLoopEventStatus.ABATED)) { - throw new ControlLoopException("Invalid value in closedLoopEventStatus"); - } - if (event.getClosedLoopControlName() == null || event.getClosedLoopControlName().length() < 1) { + validateStatus(event); + if (StringUtils.isBlank(event.getClosedLoopControlName())) { throw new ControlLoopException("No control loop name"); } if (event.getRequestId() == null) { @@ -706,14 +711,23 @@ public class ControlLoopEventManager implements LockCallback, Serializable { if (event.getClosedLoopEventStatus() == ControlLoopEventStatus.ABATED) { return; } - if (event.getTarget() == null || event.getTarget().length() < 1) { + if (StringUtils.isBlank(event.getTarget())) { throw new ControlLoopException("No target field"); - } else if (!VM_NAME.equalsIgnoreCase(event.getTarget()) && !VNF_NAME.equalsIgnoreCase(event.getTarget()) - && !VSERVER_VSERVER_NAME.equalsIgnoreCase(event.getTarget()) - && !GENERIC_VNF_VNF_ID.equalsIgnoreCase(event.getTarget()) - && !GENERIC_VNF_VNF_NAME.equalsIgnoreCase(event.getTarget())) { + } else if (!VALID_TARGETS.contains(event.getTarget().toLowerCase())) { throw new ControlLoopException("target field invalid - expecting VM_NAME or VNF_NAME"); } + validateAaiData(event); + } + + private void validateStatus(VirtualControlLoopEvent event) throws ControlLoopException { + if (event.getClosedLoopEventStatus() == null + || (event.getClosedLoopEventStatus() != ControlLoopEventStatus.ONSET + && event.getClosedLoopEventStatus() != ControlLoopEventStatus.ABATED)) { + throw new ControlLoopException("Invalid value in closedLoopEventStatus"); + } + } + + private void validateAaiData(VirtualControlLoopEvent event) throws ControlLoopException { if (event.getAai() == null) { throw new ControlLoopException("AAI is null"); } diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManager.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManager.java index 3ff5c260e..006899efe 100644 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManager.java +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManager.java @@ -62,6 +62,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ControlLoopOperationManager implements Serializable { + private static final String SUCCESS_MSG = " Success"; + private static final String FAILED_MSG = " Failed"; + private static final String AAI_CUSTOM_QUERY = "aai.customQuery"; private static final long serialVersionUID = -3773199283624595410L; private static final Logger logger = LoggerFactory.getLogger(ControlLoopOperationManager.class); @@ -110,28 +113,7 @@ public class ControlLoopOperationManager implements Serializable { // switch (policy.getActor()) { case "APPC": - if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) { - /* - * The target vnf-id may not be the same as the source vnf-id specified in the yaml, the target - * vnf-id is retrieved by a named query to A&AI. - */ - if (Boolean.valueOf(PolicyEngine.manager.getEnvironmentProperty("aai.customQuery"))) { - GenericVnf genvnf = this.eventManager.getCqResponse((VirtualControlLoopEvent) onset) - .getGenericVnfByModelInvariantId(policy.getTarget().getResourceID()); - if (genvnf == null) { - logger.info("Target entity could not be found"); - throw new AaiException("Target vnf-id could not be found"); - } - this.targetEntity = genvnf.getVnfId(); - - } else { - this.targetEntity = - AppcLcmActorServiceProvider.vnfNamedQuery(policy.getTarget().getResourceID(), - this.targetEntity, PolicyEngine.manager.getEnvironmentProperty("aai.url"), - PolicyEngine.manager.getEnvironmentProperty("aai.username"), - PolicyEngine.manager.getEnvironmentProperty("aai.password")); - } - } + initAppc(onset, policy); break; case "SO": break; @@ -147,6 +129,32 @@ public class ControlLoopOperationManager implements Serializable { } + private void initAppc(ControlLoopEvent onset, Policy policy) throws AaiException { + if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) { + /* + * The target vnf-id may not be the same as the source vnf-id specified in the yaml, the target + * vnf-id is retrieved by a named query to A&AI. + */ + if (Boolean.valueOf(PolicyEngine.manager.getEnvironmentProperty(AAI_CUSTOM_QUERY))) { + GenericVnf genvnf = this.eventManager.getCqResponse((VirtualControlLoopEvent) onset) + .getGenericVnfByModelInvariantId(policy.getTarget().getResourceID()); + if (genvnf == null) { + logger.info("Target entity could not be found"); + throw new AaiException("Target vnf-id could not be found"); + } + this.targetEntity = genvnf.getVnfId(); + + } else { + this.targetEntity = + AppcLcmActorServiceProvider.vnfNamedQuery(policy.getTarget().getResourceID(), + this.targetEntity, PolicyEngine.manager.getEnvironmentProperty("aai.url"), + PolicyEngine.manager.getEnvironmentProperty("aai.username"), + PolicyEngine.manager.getEnvironmentProperty("aai.password")); + } + } + } + + public ControlLoopEventManager getEventManager() { return eventManager; } @@ -218,72 +226,48 @@ public class ControlLoopOperationManager implements Serializable { throw new ControlLoopException("PNF target is not supported"); case VM: case VNF: - VirtualControlLoopEvent virtualOnset = (VirtualControlLoopEvent) this.onset; - if (this.onset.getTarget().equalsIgnoreCase(VSERVER_VSERVER_NAME)) { - return virtualOnset.getAai().get(VSERVER_VSERVER_NAME); - } else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_ID)) { - return virtualOnset.getAai().get(GENERIC_VNF_VNF_ID); - } else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_NAME)) { - /* - * If the onset is enriched with the vnf-id, we don't need an A&AI response - */ - if (virtualOnset.getAai().containsKey(GENERIC_VNF_VNF_ID)) { - return virtualOnset.getAai().get(GENERIC_VNF_VNF_ID); - } - - /* - * If the vnf-name was retrieved from the onset then the vnf-id must be obtained from the event - * manager's A&AI GET query - */ - String vnfId; - if (Boolean.valueOf(PolicyEngine.manager.getEnvironmentProperty("aai.customQuery"))) { - vnfId = this.eventManager.getCqResponse((VirtualControlLoopEvent) onset).getDefaultGenericVnf() - .getVnfId(); - } else { - vnfId = this.eventManager.getVnfResponse().getVnfId(); - } - if (vnfId == null) { - throw new AaiException("No vnf-id found"); - } - return vnfId; - } - throw new ControlLoopException("Target does not match target type"); + return getVfModuleTarget(); case VFMODULE: - VirtualControlLoopEvent virtualOnsetEvent = (VirtualControlLoopEvent) this.onset; - if (this.onset.getTarget().equalsIgnoreCase(VSERVER_VSERVER_NAME)) { - return virtualOnsetEvent.getAai().get(VSERVER_VSERVER_NAME); - } else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_ID)) { - return virtualOnsetEvent.getAai().get(GENERIC_VNF_VNF_ID); - } else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_NAME)) { - /* - * If the onset is enriched with the vnf-id, we don't need an A&AI response - */ - if (virtualOnsetEvent.getAai().containsKey(GENERIC_VNF_VNF_ID)) { - return virtualOnsetEvent.getAai().get(GENERIC_VNF_VNF_ID); - } - - /* - * If the vnf-name was retrieved from the onset then the vnf-id must be obtained from the event - * manager's A&AI GET query - */ - String vnfId; - if (Boolean.valueOf(PolicyEngine.manager.getEnvironmentProperty("aai.customQuery"))) { - vnfId = this.eventManager.getCqResponse((VirtualControlLoopEvent) onset).getDefaultGenericVnf() - .getVnfId(); - } else { - vnfId = this.eventManager.getVnfResponse().getVnfId(); - } - if (vnfId == null) { - throw new AaiException("No vnf-id found"); - } - return vnfId; - } - throw new ControlLoopException("Target does not match target type"); + return getVfModuleTarget(); default: throw new ControlLoopException("The target type is not supported"); } } + + private String getVfModuleTarget() throws AaiException, ControlLoopException { + VirtualControlLoopEvent virtualOnsetEvent = (VirtualControlLoopEvent) this.onset; + if (this.onset.getTarget().equalsIgnoreCase(VSERVER_VSERVER_NAME)) { + return virtualOnsetEvent.getAai().get(VSERVER_VSERVER_NAME); + } else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_ID)) { + return virtualOnsetEvent.getAai().get(GENERIC_VNF_VNF_ID); + } else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_NAME)) { + /* + * If the onset is enriched with the vnf-id, we don't need an A&AI response + */ + if (virtualOnsetEvent.getAai().containsKey(GENERIC_VNF_VNF_ID)) { + return virtualOnsetEvent.getAai().get(GENERIC_VNF_VNF_ID); + } + + /* + * If the vnf-name was retrieved from the onset then the vnf-id must be obtained from the event + * manager's A&AI GET query + */ + String vnfId; + if (Boolean.valueOf(PolicyEngine.manager.getEnvironmentProperty(AAI_CUSTOM_QUERY))) { + vnfId = this.eventManager.getCqResponse((VirtualControlLoopEvent) onset).getDefaultGenericVnf() + .getVnfId(); + } else { + vnfId = this.eventManager.getVnfResponse().getVnfId(); + } + if (vnfId == null) { + throw new AaiException("No vnf-id found"); + } + return vnfId; + } + throw new ControlLoopException("Target does not match target type"); + } + /** * Start an operation. * @@ -311,88 +295,113 @@ public class ControlLoopOperationManager implements Serializable { // switch (policy.getActor()) { case "APPC": - /* - * If the recipe is ModifyConfig, a legacy APPC request is constructed. Otherwise an LCMRequest is - * constructed. - */ - this.currentOperation = operation; - if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) { - this.operationRequest = AppcActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, - operation.clOperation, this.policy, this.targetEntity); - } else { - this.operationRequest = AppcLcmActorServiceProvider.constructRequest( - (VirtualControlLoopEvent) onset, operation.clOperation, this.policy, this.targetEntity); - } - // - // Save the operation - // - - return operationRequest; + return startAppcOperation(onset, operation); case "SO": - SoActorServiceProvider soActorSp = new SoActorServiceProvider(); - if (Boolean.valueOf(PolicyEngine.manager.getEnvironmentProperty("aai.customQuery"))) { - this.operationRequest = - soActorSp.constructRequestCq((VirtualControlLoopEvent) onset, operation.clOperation, - this.policy, eventManager.getCqResponse((VirtualControlLoopEvent) onset)); - } else { - this.operationRequest = soActorSp.constructRequest((VirtualControlLoopEvent) onset, - operation.clOperation, this.policy, eventManager.getNqVserverFromAai()); - } - - // Save the operation - this.currentOperation = operation; - - if (this.operationRequest == null) { - this.policyResult = PolicyResult.FAILURE; - } - - return operationRequest; + return startSoOperation(onset, operation); case "VFC": - if (Boolean.valueOf(PolicyEngine.manager.getEnvironmentProperty("aai.customQuery"))) { - this.operationRequest = VfcActorServiceProvider.constructRequestCq((VirtualControlLoopEvent) onset, - operation.clOperation, this.policy, - eventManager.getCqResponse((VirtualControlLoopEvent) onset)); - } else { - this.operationRequest = VfcActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, - operation.clOperation, this.policy, this.eventManager.getVnfResponse(), - PolicyEngine.manager.getEnvironmentProperty("vfc.url"), - PolicyEngine.manager.getEnvironmentProperty("vfc.username"), - PolicyEngine.manager.getEnvironmentProperty("vfc.password")); - } - this.currentOperation = operation; - if (this.operationRequest == null) { - this.policyResult = PolicyResult.FAILURE; - } - return operationRequest; + return startVfcOperation(onset, operation); case "SDNR": - /* - * If the recipe is ModifyConfig or ModifyConfigANR, a SDNR request is constructed. - */ - this.currentOperation = operation; - this.operationRequest = SdnrActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, - operation.clOperation, this.policy); - // - // Save the operation - // - if (this.operationRequest == null) { - this.policyResult = PolicyResult.FAILURE; - } - - return operationRequest; + return startSdnrOperation(onset, operation); case "SDNC": - SdncActorServiceProvider provider = new SdncActorServiceProvider(); - this.operationRequest = - provider.constructRequest((VirtualControlLoopEvent) onset, operation.clOperation, this.policy); - this.currentOperation = operation; - if (this.operationRequest == null) { - this.policyResult = PolicyResult.FAILURE; - } - return operationRequest; + return startSdncOperation(onset, operation); default: throw new ControlLoopException("invalid actor " + policy.getActor() + " on policy"); } } + + private Object startAppcOperation(ControlLoopEvent onset, Operation operation) { + /* + * If the recipe is ModifyConfig, a legacy APPC request is constructed. Otherwise an LCMRequest is + * constructed. + */ + this.currentOperation = operation; + if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) { + this.operationRequest = AppcActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, + operation.clOperation, this.policy, this.targetEntity); + } else { + this.operationRequest = AppcLcmActorServiceProvider.constructRequest( + (VirtualControlLoopEvent) onset, operation.clOperation, this.policy, this.targetEntity); + } + // + // Save the operation + // + + return operationRequest; + } + + + private Object startSoOperation(ControlLoopEvent onset, Operation operation) throws AaiException { + SoActorServiceProvider soActorSp = new SoActorServiceProvider(); + if (Boolean.valueOf(PolicyEngine.manager.getEnvironmentProperty(AAI_CUSTOM_QUERY))) { + this.operationRequest = + soActorSp.constructRequestCq((VirtualControlLoopEvent) onset, operation.clOperation, + this.policy, eventManager.getCqResponse((VirtualControlLoopEvent) onset)); + } else { + this.operationRequest = soActorSp.constructRequest((VirtualControlLoopEvent) onset, + operation.clOperation, this.policy, eventManager.getNqVserverFromAai()); + } + + // Save the operation + this.currentOperation = operation; + + if (this.operationRequest == null) { + this.policyResult = PolicyResult.FAILURE; + } + + return operationRequest; + } + + + private Object startVfcOperation(ControlLoopEvent onset, Operation operation) throws AaiException { + if (Boolean.valueOf(PolicyEngine.manager.getEnvironmentProperty(AAI_CUSTOM_QUERY))) { + this.operationRequest = VfcActorServiceProvider.constructRequestCq((VirtualControlLoopEvent) onset, + operation.clOperation, this.policy, + eventManager.getCqResponse((VirtualControlLoopEvent) onset)); + } else { + this.operationRequest = VfcActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, + operation.clOperation, this.policy, this.eventManager.getVnfResponse(), + PolicyEngine.manager.getEnvironmentProperty("vfc.url"), + PolicyEngine.manager.getEnvironmentProperty("vfc.username"), + PolicyEngine.manager.getEnvironmentProperty("vfc.password")); + } + this.currentOperation = operation; + if (this.operationRequest == null) { + this.policyResult = PolicyResult.FAILURE; + } + return operationRequest; + } + + + private Object startSdnrOperation(ControlLoopEvent onset, Operation operation) { + /* + * If the recipe is ModifyConfig or ModifyConfigANR, a SDNR request is constructed. + */ + this.currentOperation = operation; + this.operationRequest = SdnrActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, + operation.clOperation, this.policy); + // + // Save the operation + // + if (this.operationRequest == null) { + this.policyResult = PolicyResult.FAILURE; + } + + return operationRequest; + } + + + private Object startSdncOperation(ControlLoopEvent onset, Operation operation) { + SdncActorServiceProvider provider = new SdncActorServiceProvider(); + this.operationRequest = + provider.constructRequest((VirtualControlLoopEvent) onset, operation.clOperation, this.policy); + this.currentOperation = operation; + if (this.operationRequest == null) { + this.policyResult = PolicyResult.FAILURE; + } + return operationRequest; + } + /** * Handle a response. * @@ -448,15 +457,10 @@ public class ControlLoopOperationManager implements Serializable { // // Determine which subrequestID (ie. attempt) // - Integer operationAttempt = null; - try { - operationAttempt = Integer.parseInt(appcResponse.getCommonHeader().getSubRequestId()); - } catch (NumberFormatException e) { - // - // We cannot tell what happened if this doesn't exist - // + Integer operationAttempt = getSubRequestId(appcResponse); + if (operationAttempt == null) { this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", - PolicyResult.FAILURE_EXCEPTION); + PolicyResult.FAILURE_EXCEPTION); return PolicyResult.FAILURE_EXCEPTION; } // @@ -483,6 +487,12 @@ public class ControlLoopOperationManager implements Serializable { PolicyResult.FAILURE_EXCEPTION); return PolicyResult.FAILURE_EXCEPTION; } + + return onResponse(appcResponse, operationAttempt, code); + } + + + private PolicyResult onResponse(Response appcResponse, Integer operationAttempt, ResponseCode code) { // // Ok, let's figure out what APP-C's response is // @@ -502,30 +512,21 @@ public class ControlLoopOperationManager implements Serializable { // this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(), PolicyResult.FAILURE_EXCEPTION); - if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { - return null; - } - return PolicyResult.FAILURE_EXCEPTION; + return getTimeoutResult(PolicyResult.FAILURE_EXCEPTION); case SUCCESS: // // // this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(), PolicyResult.SUCCESS); - if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { - return null; - } - return PolicyResult.SUCCESS; + return getTimeoutResult(PolicyResult.SUCCESS); case FAILURE: // // // this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(), PolicyResult.FAILURE); - if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { - return null; - } - return PolicyResult.FAILURE; + return getTimeoutResult(PolicyResult.FAILURE); default: return null; } @@ -546,6 +547,7 @@ public class ControlLoopOperationManager implements Serializable { if (operationAttempt == null) { this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", PolicyResult.FAILURE_EXCEPTION); + return PolicyResult.FAILURE_EXCEPTION; } /* @@ -579,6 +581,7 @@ public class ControlLoopOperationManager implements Serializable { if (operationAttempt == null) { this.completeOperation(operationAttempt, "Policy was unable to parse SDNR SubRequestID.", PolicyResult.FAILURE_EXCEPTION); + return PolicyResult.FAILURE_EXCEPTION; } /* @@ -610,22 +613,16 @@ public class ControlLoopOperationManager implements Serializable { // // Consider it as success // - this.completeOperation(this.attempts, msoResponse.getSoResponse().getHttpResponseCode() + " Success", + this.completeOperation(this.attempts, msoResponse.getSoResponse().getHttpResponseCode() + SUCCESS_MSG, PolicyResult.SUCCESS); - if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { - return null; - } - return PolicyResult.SUCCESS; + return getTimeoutResult(PolicyResult.SUCCESS); default: // // Consider it as failure // - this.completeOperation(this.attempts, msoResponse.getSoResponse().getHttpResponseCode() + " Failed", + this.completeOperation(this.attempts, msoResponse.getSoResponse().getHttpResponseCode() + FAILED_MSG, PolicyResult.FAILURE); - if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { - return null; - } - return PolicyResult.FAILURE; + return getTimeoutResult(PolicyResult.FAILURE); } } @@ -640,17 +637,14 @@ public class ControlLoopOperationManager implements Serializable { // // Consider it as success // - this.completeOperation(this.attempts, " Success", PolicyResult.SUCCESS); - if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { - return null; - } - return PolicyResult.SUCCESS; + this.completeOperation(this.attempts, SUCCESS_MSG, PolicyResult.SUCCESS); + return getTimeoutResult(PolicyResult.SUCCESS); } else { // // Consider it as failure // - this.completeOperation(this.attempts, " Failed", PolicyResult.FAILURE); - if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { + this.completeOperation(this.attempts, FAILED_MSG, PolicyResult.FAILURE); + if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) { return null; } // increment operation attempts for retries @@ -670,17 +664,14 @@ public class ControlLoopOperationManager implements Serializable { // // Consider it as success // - this.completeOperation(this.attempts, " Success", PolicyResult.SUCCESS); - if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { - return null; - } - return PolicyResult.SUCCESS; + this.completeOperation(this.attempts, SUCCESS_MSG, PolicyResult.SUCCESS); + return getTimeoutResult(PolicyResult.SUCCESS); } else { // // Consider it as failure // - this.completeOperation(this.attempts, " Failed", PolicyResult.FAILURE); - if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) { + this.completeOperation(this.attempts, FAILED_MSG, PolicyResult.FAILURE); + if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) { return null; } // increment operation attempts for retries @@ -689,6 +680,22 @@ public class ControlLoopOperationManager implements Serializable { } } + private PolicyResult getTimeoutResult(PolicyResult result) { + return (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult) ? null : result); + } + + + private Integer getSubRequestId(Response appcResponse) { + try { + return Integer.valueOf(appcResponse.getCommonHeader().getSubRequestId()); + } catch (NumberFormatException e) { + // + // We cannot tell what happened if this doesn't exist + // + return null; + } + } + /** * Get the operation timeout. * diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopExceptionTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopExceptionTest.java index f06ea34dc..e33b260f9 100644 --- a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopExceptionTest.java +++ b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopExceptionTest.java @@ -3,6 +3,7 @@ * eventmanager * ================================================================================ * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,12 +29,14 @@ import org.junit.Test; public class ControlLoopExceptionTest { + private static final String IN_OZ = "In Oz"; + @Test public void testControlLoopException() { assertNotNull(new ControlLoopException()); - assertNotNull(new ControlLoopException("In Oz")); + assertNotNull(new ControlLoopException(IN_OZ)); assertNotNull(new ControlLoopException(new IOException())); - assertNotNull(new ControlLoopException("In Oz", new IOException())); - assertNotNull(new ControlLoopException("In Oz", new IOException(), false, false)); + assertNotNull(new ControlLoopException(IN_OZ, new IOException())); + assertNotNull(new ControlLoopException(IN_OZ, new IOException(), false, false)); } } diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopLoggerTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopLoggerTest.java index 4e2719075..35e4d534f 100644 --- a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopLoggerTest.java +++ b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopLoggerTest.java @@ -8,9 +8,9 @@ * 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. @@ -21,9 +21,8 @@ package org.onap.policy.controlloop; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; import org.junit.Test; import org.onap.policy.controlloop.impl.ControlLoopLoggerStdOutImpl; @@ -38,11 +37,7 @@ public class ControlLoopLoggerTest { logger.metrics("a metric", "and another", " and another"); logger.metrics(Double.valueOf(3)); - try { - new ControlLoopLogger.Factory().buildLogger("java.lang.String"); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("Cannot load class java.lang.String as a control loop logger", e.getMessage()); - } + assertThatThrownBy(() -> new ControlLoopLogger.Factory().buildLogger("java.lang.String")) + .hasMessage("Cannot load class java.lang.String as a control loop logger"); } } diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopPublisherTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopPublisherTest.java index 77a3d643f..42b721ec1 100644 --- a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopPublisherTest.java +++ b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopPublisherTest.java @@ -8,9 +8,9 @@ * 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. @@ -21,9 +21,8 @@ package org.onap.policy.controlloop; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; import org.junit.Test; import org.onap.policy.controlloop.impl.ControlLoopPublisherJUnitImpl; @@ -35,19 +34,11 @@ public class ControlLoopPublisherTest { new ControlLoopPublisher.Factory().buildLogger(ControlLoopPublisherJUnitImpl.class.getName()); assertNotNull(publisher); - try { - publisher.publish(Double.valueOf(3)); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("publish() method is not implemented on " - + "org.onap.policy.controlloop.impl.ControlLoopPublisherJUnitImpl", e.getMessage()); - } + assertThatThrownBy(() -> publisher.publish(Double.valueOf(3))) + .hasMessage("publish() method is not implemented on " + + "org.onap.policy.controlloop.impl.ControlLoopPublisherJUnitImpl"); - try { - new ControlLoopPublisher.Factory().buildLogger("java.lang.String"); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("Cannot load class java.lang.String as a control loop publisher", e.getMessage()); - } + assertThatThrownBy(() -> new ControlLoopPublisher.Factory().buildLogger("java.lang.String")) + .hasMessage("Cannot load class java.lang.String as a control loop publisher"); } } diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/SupportUtil.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/SupportUtil.java index 39077e3b3..9534f938a 100644 --- a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/SupportUtil.java +++ b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/SupportUtil.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * util * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,14 +20,11 @@ package org.onap.policy.controlloop; -import static org.junit.Assert.fail; - import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; - import org.apache.commons.io.IOUtils; import org.onap.policy.controlloop.policy.ControlLoopPolicy; import org.yaml.snakeyaml.Yaml; @@ -45,13 +42,18 @@ public final class SupportUtil { } } + private SupportUtil() { + // do nothing + } + /** * Load yaml into a Pair object. - * + * * @param testFile the yaml file * @return a Pair + * @throws IOException if the file cannot be read */ - public static Pair<ControlLoopPolicy, String> loadYaml(String testFile) { + public static Pair<ControlLoopPolicy, String> loadYaml(String testFile) throws IOException { try (InputStream is = new FileInputStream(new File(testFile))) { String contents = IOUtils.toString(is, StandardCharsets.UTF_8); // @@ -59,11 +61,8 @@ public final class SupportUtil { // Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); Object obj = yaml.load(contents); - return new Pair<ControlLoopPolicy, String>((ControlLoopPolicy) obj, contents); - } catch (IOException e) { - fail(e.getLocalizedMessage()); + return new Pair<>((ControlLoopPolicy) obj, contents); } - return null; } } diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManagerTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManagerTest.java index beea88d82..3a4b27770 100644 --- a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManagerTest.java +++ b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManagerTest.java @@ -20,12 +20,12 @@ package org.onap.policy.controlloop.eventmanager; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import java.io.File; import java.io.FileInputStream; @@ -71,16 +71,37 @@ import org.onap.policy.guard.PolicyGuard; import org.onap.policy.guard.PolicyGuard.LockResult; import org.onap.policy.guard.TargetLock; import org.powermock.reflect.Whitebox; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; public class ControlLoopEventManagerTest { + private static final String PROCESS_VSERVER_RESPONSE = "processVServerResponse"; + private static final String ONSET_ONE = "onsetOne"; + private static final String VSERVER_NAME = "vserver.vserver-name"; + private static final String TEST_YAML = "src/test/resources/test.yaml"; + private static final String SERVICE_TYPE = "service-subscription.service-type"; + private static final String SERVICE_INSTANCE_NAME = "service-instance.service-instance-name"; + private static final String SERVICE_INSTANCE_ID = "service-instance.service-instance-id"; + private static final String SERVICE_INSTANCE = "service-instance"; + private static final String VNF_NAME_TEXT = "lll_vnf_010317"; + private static final String SERVICE_INSTANCE_NAME_TEXT = "lll_svc_010317"; + private static final String VNF_NAME = "generic-vnf.vnf-name"; + private static final String VNF_ID = "generic-vnf.vnf-id"; + private static final String SERVICE_INSTANCE_UUID = "e1e9c97c-02c0-4919-9b4c-eb5d5ef68970"; + private static final String MSO_CUSTOMER_ID = "customer.global-customer-id"; + private static final String AAI_USERNAME = "aai.username"; + private static final String AAI_URL = "aai.url"; + private static final String AAI_PASS = "aai.password"; + private static final String TWO_ONSET_TEST = "TwoOnsetTest"; + private static final String MSO_1610_ST = "MSO_1610_ST"; + private static final String MSO_DEV_SERVICE_TYPE = "MSO-dev-service-type"; + private static final String VNF_UUID = "83f674e8-7555-44d7-9a39-bdc3770b0491"; + private static final String AAI_SERVICE_SUBSCRIPTION_URI = + "/aai/v11/business/customers/customer/MSO_1610_ST/service-subscriptions/service-subscription"; + private static final String MSO_SERVICE_INSTANCE_URI = "/MSO-dev-service-type/service-instances/service-instance/"; + private static final String PROCESS_VNF_RESPONSE_METHOD_NAME = "processVnfResponse"; private static final String INVALID_URL = "http://localhost:9999"; - private static final Logger logger = LoggerFactory.getLogger(ControlLoopEventManagerTest.class); - @Rule public ExpectedException thrown = ExpectedException.none(); @@ -91,15 +112,12 @@ public class ControlLoopEventManagerTest { * Set up test class. */ @BeforeClass - public static void setUpSimulator() { - try { - org.onap.policy.simulators.Util.buildAaiSim(); - } catch (Exception e) { - fail(e.getMessage()); - } - PolicyEngine.manager.setEnvironmentProperty("aai.username", "AAI"); - PolicyEngine.manager.setEnvironmentProperty("aai.password", "AAI"); - PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:6666"); + public static void setUpSimulator() throws Exception { + org.onap.policy.simulators.Util.buildAaiSim(); + + PolicyEngine.manager.setEnvironmentProperty(AAI_USERNAME, "AAI"); + PolicyEngine.manager.setEnvironmentProperty(AAI_PASS, "AAI"); + PolicyEngine.manager.setEnvironmentProperty(AAI_URL, "http://localhost:6666"); } @AfterClass @@ -120,113 +138,70 @@ public class ControlLoopEventManagerTest { onset.setAai(new HashMap<String, String>()); onset.getAai().put("cloud-region.identity-url", "foo"); onset.getAai().put("vserver.selflink", "bar"); - onset.getAai().put("generic-vnf.vnf-id", "83f674e8-7555-44d7-9a39-bdc3770b0491"); + onset.getAai().put(VNF_ID, VNF_UUID); onset.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:6666"); + PolicyEngine.manager.setEnvironmentProperty(AAI_URL, "http://localhost:6666"); } @Test - public void testAaiVnfInfo() { - final SupportUtil.Pair<ControlLoopPolicy, String> pair = SupportUtil.loadYaml("src/test/resources/test.yaml"); + public void testAaiVnfInfo() throws IOException { + final SupportUtil.Pair<ControlLoopPolicy, String> pair = SupportUtil.loadYaml(TEST_YAML); onset.setClosedLoopControlName(pair.key.getControlLoop().getControlLoopName()); - try { - AaiGetVnfResponse response = getQueryByVnfId2( - PolicyEngine.manager.getEnvironmentProperty("aai.url") - + "/aai/v11/network/generic-vnfs/generic-vnf/", - PolicyEngine.manager.getEnvironmentProperty("aai.username"), - PolicyEngine.manager.getEnvironmentProperty("aai.password"), UUID.randomUUID(), - "5e49ca06-2972-4532-9ed4-6d071588d792"); - assertNotNull(response); - logger.info("testAAIVnfInfo test result is " + (response == null ? "null" : "not null")); - } catch (Exception e) { - logger.error("testAAIVnfInfo Exception: ", e); - fail(e.getMessage()); - } + AaiGetVnfResponse response = getQueryByVnfId2(); + assertNotNull(response); } @Test - public void testAaiVnfInfo2() { - final SupportUtil.Pair<ControlLoopPolicy, String> pair = SupportUtil.loadYaml("src/test/resources/test.yaml"); + public void testAaiVnfInfo2() throws IOException { + final SupportUtil.Pair<ControlLoopPolicy, String> pair = SupportUtil.loadYaml(TEST_YAML); onset.setClosedLoopControlName(pair.key.getControlLoop().getControlLoopName()); - try { - AaiGetVnfResponse response = getQueryByVnfName2( - PolicyEngine.manager.getEnvironmentProperty("aai.url") - + "/aai/v11/network/generic-vnfs/generic-vnf?vnf-name=", - PolicyEngine.manager.getEnvironmentProperty("aai.username"), - PolicyEngine.manager.getEnvironmentProperty("aai.password"), UUID.randomUUID(), "lll_vnf_010317"); - assertNotNull(response); - logger.info("testAAIVnfInfo2 test result is " + (response == null ? "null" : "not null")); - } catch (Exception e) { - logger.error("testAAIVnfInfo2 Exception: ", e); - fail(e.getMessage()); - } + AaiGetVnfResponse response = getQueryByVnfName2(); + assertNotNull(response); } @Test - public void testAaiVserver() { - final SupportUtil.Pair<ControlLoopPolicy, String> pair = SupportUtil.loadYaml("src/test/resources/test.yaml"); + public void testAaiVserver() throws IOException { + final SupportUtil.Pair<ControlLoopPolicy, String> pair = SupportUtil.loadYaml(TEST_YAML); onset.setClosedLoopControlName(pair.key.getControlLoop().getControlLoopName()); - try { - AaiGetVserverResponse response = getQueryByVserverName2( - PolicyEngine.manager.getEnvironmentProperty("aai.url") + "/aai/v11/nodes/vservers?vserver-name=", - PolicyEngine.manager.getEnvironmentProperty("aai.username"), - PolicyEngine.manager.getEnvironmentProperty("aai.password"), UUID.randomUUID(), - "USMSO1SX7NJ0103UJZZ01-vjunos0"); - assertNotNull(response); - logger.info("testAAIVserver test result is " + (response == null ? "null" : "not null")); - } catch (Exception e) { - logger.error("testAAIVserver Exception: ", e); - fail(e.getMessage()); - } + AaiGetVserverResponse response = getQueryByVserverName2(); + assertNotNull(response); } @Test - public void abatementCheckEventSyntaxTest() { + public void abatementCheckEventSyntaxTest() throws ControlLoopException { VirtualControlLoopEvent event = new VirtualControlLoopEvent(); event.setClosedLoopControlName("abatementAAI"); event.setRequestId(UUID.randomUUID()); - event.setTarget("generic-vnf.vnf-id"); + event.setTarget(VNF_ID); event.setClosedLoopAlarmStart(Instant.now()); event.setClosedLoopEventStatus(ControlLoopEventStatus.ABATED); ControlLoopEventManager manager = makeManager(event); assertNull(manager.getVnfResponse()); assertNull(manager.getVserverResponse()); - try { - manager.checkEventSyntax(event); - } catch (ControlLoopException e) { - logger.debug("ControlLoopException in abatemetCheckEventSyntaxTest: " + e.getMessage()); - e.printStackTrace(); - fail("Exception in check event syntax"); - } + manager.checkEventSyntax(event); assertNull(manager.getVnfResponse()); assertNull(manager.getVserverResponse()); event.setAai(new HashMap<>()); - event.getAai().put("generic-vnf.vnf-name", "abatementTest"); - try { - manager.checkEventSyntax(event); - } catch (ControlLoopException e) { - logger.debug("ControlLoopException in abatemetCheckEventSyntaxTest: " + e.getMessage()); - e.printStackTrace(); - fail("Exception in check event syntax"); - } + event.getAai().put(VNF_NAME, "abatementTest"); + manager.checkEventSyntax(event); assertNull(manager.getVnfResponse()); assertNull(manager.getVserverResponse()); } @Test - public void subsequentOnsetTest() throws IOException { + public void subsequentOnsetTest() throws Exception { UUID requestId = UUID.randomUUID(); VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName("TwoOnsetTest"); + event.setClosedLoopControlName(TWO_ONSET_TEST); event.setRequestId(requestId); - event.setTarget("generic-vnf.vnf-id"); + event.setTarget(VNF_ID); event.setClosedLoopAlarmStart(Instant.now()); event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); event.setAai(new HashMap<>()); - event.getAai().put("generic-vnf.vnf-name", "onsetOne"); + event.getAai().put(VNF_NAME, ONSET_ONE); ControlLoopEventManager manager = makeManager(event); VirtualControlLoopNotification notification = manager.activate(event); @@ -235,12 +210,7 @@ public class ControlLoopEventManagerTest { assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); ControlLoopEventManager.NewEventStatus status = null; - try { - status = manager.onNewEvent(event); - } catch (AaiException e) { - logger.warn(e.toString()); - fail("A&AI Query Failed"); - } + status = manager.onNewEvent(event); assertNotNull(status); assertEquals(ControlLoopEventManager.NewEventStatus.FIRST_ONSET, status); @@ -249,21 +219,16 @@ public class ControlLoopEventManagerTest { assertNull(manager.getVserverResponse()); VirtualControlLoopEvent event2 = new VirtualControlLoopEvent(); - event2.setClosedLoopControlName("TwoOnsetTest"); + event2.setClosedLoopControlName(TWO_ONSET_TEST); event2.setRequestId(requestId); - event2.setTarget("generic-vnf.vnf-id"); + event2.setTarget(VNF_ID); event2.setClosedLoopAlarmStart(Instant.now()); event2.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); event2.setAai(new HashMap<>()); - event2.getAai().put("generic-vnf.vnf-name", "onsetTwo"); + event2.getAai().put(VNF_NAME, "onsetTwo"); - try { - status = manager.onNewEvent(event2); - } catch (AaiException e) { - logger.warn(e.toString()); - fail("A&AI Query Failed"); - } + status = manager.onNewEvent(event2); assertEquals(ControlLoopEventManager.NewEventStatus.SUBSEQUENT_ONSET, status); AaiGetVnfResponse response2 = manager.getVnfResponse(); assertNotNull(response2); @@ -275,12 +240,11 @@ public class ControlLoopEventManagerTest { /** * Simulate a response. */ - public static AaiGetVnfResponse getQueryByVnfId2(String urlGet, String username, String password, UUID requestId, - String key) { + public static AaiGetVnfResponse getQueryByVnfId2() { AaiGetVnfResponse response = new AaiGetVnfResponse(); - response.setVnfId("83f674e8-7555-44d7-9a39-bdc3770b0491"); - response.setVnfName("lll_vnf_010317"); + response.setVnfId(VNF_UUID); + response.setVnfName(VNF_NAME_TEXT); response.setVnfType("Basa-122216-Service/VidVsamp12BaseVolume 1"); response.setServiceId("a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb"); response.setOrchestrationStatus("Created"); @@ -293,28 +257,28 @@ public class ControlLoopEventManagerTest { final Relationship relationship = new Relationship(); RelationshipData relationshipDataItem = new RelationshipData(); - relationshipDataItem.setRelationshipKey("customer.global-customer-id"); - relationshipDataItem.setRelationshipValue("MSO_1610_ST"); + relationshipDataItem.setRelationshipKey(MSO_CUSTOMER_ID); + relationshipDataItem.setRelationshipValue(MSO_1610_ST); relationship.getRelationshipData().add(relationshipDataItem); - relationshipDataItem.setRelationshipKey("service-subscription.service-type"); - relationshipDataItem.setRelationshipValue("MSO-dev-service-type"); + relationshipDataItem.setRelationshipKey(SERVICE_TYPE); + relationshipDataItem.setRelationshipValue(MSO_DEV_SERVICE_TYPE); relationship.getRelationshipData().add(relationshipDataItem); - relationshipDataItem.setRelationshipKey("service-instance.service-instance-id"); - relationshipDataItem.setRelationshipValue("e1e9c97c-02c0-4919-9b4c-eb5d5ef68970"); + relationshipDataItem.setRelationshipKey(SERVICE_INSTANCE_ID); + relationshipDataItem.setRelationshipValue(SERVICE_INSTANCE_UUID); relationship.getRelationshipData().add(relationshipDataItem); RelatedToProperty item = new RelatedToProperty(); - item.setPropertyKey("service-instance.service-instance-name"); - item.setPropertyValue("lll_svc_010317"); + item.setPropertyKey(SERVICE_INSTANCE_NAME); + item.setPropertyValue(SERVICE_INSTANCE_NAME_TEXT); relationship.getRelatedToProperty().add(item); - relationship.setRelatedTo("service-instance"); + relationship.setRelatedTo(SERVICE_INSTANCE); relationship.setRelatedLink( - "/aai/v11/business/customers/customer/MSO_1610_ST/service-subscriptions/service-subscription" - + "/MSO-dev-service-type/service-instances/service-instance/" - + "e1e9c97c-02c0-4919-9b4c-eb5d5ef68970"); + AAI_SERVICE_SUBSCRIPTION_URI + + MSO_SERVICE_INSTANCE_URI + + SERVICE_INSTANCE_UUID); relationshipList.getRelationships().add(relationship); response.setRelationshipList(relationshipList); @@ -325,12 +289,11 @@ public class ControlLoopEventManagerTest { /** * Simulate a response. */ - public static AaiGetVnfResponse getQueryByVnfName2(String urlGet, String username, String password, UUID requestId, - String key) { + public static AaiGetVnfResponse getQueryByVnfName2() { AaiGetVnfResponse response = new AaiGetVnfResponse(); - response.setVnfId("83f674e8-7555-44d7-9a39-bdc3770b0491"); - response.setVnfName("lll_vnf_010317"); + response.setVnfId(VNF_UUID); + response.setVnfName(VNF_NAME_TEXT); response.setVnfType("Basa-122216-Service/VidVsamp12BaseVolume 1"); response.setServiceId("a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb"); response.setOrchestrationStatus("Created"); @@ -343,28 +306,28 @@ public class ControlLoopEventManagerTest { final Relationship relationship = new Relationship(); RelationshipData relationshipDataItem = new RelationshipData(); - relationshipDataItem.setRelationshipKey("customer.global-customer-id"); - relationshipDataItem.setRelationshipValue("MSO_1610_ST"); + relationshipDataItem.setRelationshipKey(MSO_CUSTOMER_ID); + relationshipDataItem.setRelationshipValue(MSO_1610_ST); relationship.getRelationshipData().add(relationshipDataItem); - relationshipDataItem.setRelationshipKey("service-subscription.service-type"); - relationshipDataItem.setRelationshipValue("MSO-dev-service-type"); + relationshipDataItem.setRelationshipKey(SERVICE_TYPE); + relationshipDataItem.setRelationshipValue(MSO_DEV_SERVICE_TYPE); relationship.getRelationshipData().add(relationshipDataItem); - relationshipDataItem.setRelationshipKey("service-instance.service-instance-id"); - relationshipDataItem.setRelationshipValue("e1e9c97c-02c0-4919-9b4c-eb5d5ef68970"); + relationshipDataItem.setRelationshipKey(SERVICE_INSTANCE_ID); + relationshipDataItem.setRelationshipValue(SERVICE_INSTANCE_UUID); relationship.getRelationshipData().add(relationshipDataItem); RelatedToProperty item = new RelatedToProperty(); - item.setPropertyKey("service-instance.service-instance-name"); - item.setPropertyValue("lll_svc_010317"); + item.setPropertyKey(SERVICE_INSTANCE_NAME); + item.setPropertyValue(SERVICE_INSTANCE_NAME_TEXT); relationship.getRelatedToProperty().add(item); - relationship.setRelatedTo("service-instance"); + relationship.setRelatedTo(SERVICE_INSTANCE); relationship.setRelatedLink( - "/aai/v11/business/customers/customer/MSO_1610_ST/service-subscriptions/service-subscription" - + "/MSO-dev-service-type/service-instances/service-instance/" - + "e1e9c97c-02c0-4919-9b4c-eb5d5ef68970"); + AAI_SERVICE_SUBSCRIPTION_URI + + MSO_SERVICE_INSTANCE_URI + + SERVICE_INSTANCE_UUID); relationshipList.getRelationships().add(relationship); response.setRelationshipList(relationshipList); @@ -375,8 +338,7 @@ public class ControlLoopEventManagerTest { /** * Simulate a response. */ - public static AaiGetVserverResponse getQueryByVserverName2(String urlGet, String username, String password, - UUID requestId, String key) { + public static AaiGetVserverResponse getQueryByVserverName2() { final AaiGetVserverResponse response = new AaiGetVserverResponse(); AaiNqVServer svr = new AaiNqVServer(); @@ -394,28 +356,28 @@ public class ControlLoopEventManagerTest { final Relationship relationship = new Relationship(); RelationshipData relationshipDataItem = new RelationshipData(); - relationshipDataItem.setRelationshipKey("customer.global-customer-id"); - relationshipDataItem.setRelationshipValue("MSO_1610_ST"); + relationshipDataItem.setRelationshipKey(MSO_CUSTOMER_ID); + relationshipDataItem.setRelationshipValue(MSO_1610_ST); relationship.getRelationshipData().add(relationshipDataItem); - relationshipDataItem.setRelationshipKey("service-subscription.service-type"); - relationshipDataItem.setRelationshipValue("MSO-dev-service-type"); + relationshipDataItem.setRelationshipKey(SERVICE_TYPE); + relationshipDataItem.setRelationshipValue(MSO_DEV_SERVICE_TYPE); relationship.getRelationshipData().add(relationshipDataItem); - relationshipDataItem.setRelationshipKey("service-instance.service-instance-id"); - relationshipDataItem.setRelationshipValue("e1e9c97c-02c0-4919-9b4c-eb5d5ef68970"); + relationshipDataItem.setRelationshipKey(SERVICE_INSTANCE_ID); + relationshipDataItem.setRelationshipValue(SERVICE_INSTANCE_UUID); relationship.getRelationshipData().add(relationshipDataItem); RelatedToProperty item = new RelatedToProperty(); - item.setPropertyKey("service-instance.service-instance-name"); - item.setPropertyValue("lll_svc_010317"); + item.setPropertyKey(SERVICE_INSTANCE_NAME); + item.setPropertyValue(SERVICE_INSTANCE_NAME_TEXT); relationship.getRelatedToProperty().add(item); - relationship.setRelatedTo("service-instance"); + relationship.setRelatedTo(SERVICE_INSTANCE); relationship.setRelatedLink( - "/aai/v11/business/customers/customer/MSO_1610_ST/service-subscriptions/service-subscription" - + "/MSO-dev-service-type/service-instances/service-instance/" - + "e1e9c97c-02c0-4919-9b4c-eb5d5ef68970"); + AAI_SERVICE_SUBSCRIPTION_URI + + MSO_SERVICE_INSTANCE_URI + + SERVICE_INSTANCE_UUID); relationshipList.getRelationships().add(relationship); svr.setRelationshipList(relationshipList); @@ -463,13 +425,13 @@ public class ControlLoopEventManagerTest { public void testAlreadyActivated() { UUID requestId = UUID.randomUUID(); VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName("TwoOnsetTest"); + event.setClosedLoopControlName(TWO_ONSET_TEST); event.setRequestId(requestId); - event.setTarget("generic-vnf.vnf-id"); + event.setTarget(VNF_ID); event.setClosedLoopAlarmStart(Instant.now()); event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); event.setAai(new HashMap<>()); - event.getAai().put("generic-vnf.vnf-name", "onsetOne"); + event.getAai().put(VNF_NAME, ONSET_ONE); ControlLoopEventManager manager = makeManager(event); manager.setActivated(true); @@ -479,7 +441,7 @@ public class ControlLoopEventManagerTest { @Test public void testActivationYaml() throws IOException { - InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + InputStream is = new FileInputStream(new File(TEST_YAML)); final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); InputStream isBad = new FileInputStream(new File("src/test/resources/notutf8.yaml")); @@ -487,13 +449,13 @@ public class ControlLoopEventManagerTest { UUID requestId = UUID.randomUUID(); VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName("TwoOnsetTest"); + event.setClosedLoopControlName(TWO_ONSET_TEST); event.setRequestId(requestId); - event.setTarget("generic-vnf.vnf-id"); + event.setTarget(VNF_ID); event.setClosedLoopAlarmStart(Instant.now()); event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); event.setAai(new HashMap<>()); - event.getAai().put("generic-vnf.vnf-name", "onsetOne"); + event.getAai().put(VNF_NAME, ONSET_ONE); ControlLoopEventManager manager = makeManager(event); @@ -523,35 +485,28 @@ public class ControlLoopEventManagerTest { } @Test - public void testControlLoopFinal() throws ControlLoopException, IOException { - InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + public void testControlLoopFinal() throws Exception { + InputStream is = new FileInputStream(new File(TEST_YAML)); final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); UUID requestId = UUID.randomUUID(); VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName("TwoOnsetTest"); + event.setClosedLoopControlName(TWO_ONSET_TEST); event.setRequestId(requestId); - event.setTarget("generic-vnf.vnf-id"); + event.setTarget(VNF_ID); event.setClosedLoopAlarmStart(Instant.now()); event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); event.setAai(new HashMap<>()); - event.getAai().put("generic-vnf.vnf-name", "onsetOne"); + event.getAai().put(VNF_NAME, ONSET_ONE); ControlLoopEventManager manager = makeManager(event); - try { - manager.isControlLoopFinal(); - fail("test should throw an exception here"); - } catch (ControlLoopException e) { - assertEquals("ControlLoopEventManager MUST be activated first.", e.getMessage()); - } + ControlLoopEventManager manager2 = manager; + assertThatThrownBy(manager2::isControlLoopFinal).isInstanceOf(ControlLoopException.class) + .hasMessage("ControlLoopEventManager MUST be activated first."); manager.setActivated(true); - try { - manager.isControlLoopFinal(); - fail("test should throw an exception here"); - } catch (ControlLoopException e) { - assertEquals("No onset event for ControlLoopEventManager.", e.getMessage()); - } + assertThatThrownBy(manager2::isControlLoopFinal).isInstanceOf(ControlLoopException.class) + .hasMessage("No onset event for ControlLoopEventManager."); manager.setActivated(false); VirtualControlLoopNotification notification = manager.activate(yamlString, event); @@ -596,35 +551,28 @@ public class ControlLoopEventManagerTest { } @Test - public void testProcessControlLoop() throws ControlLoopException, IOException, AaiException { - InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + public void testProcessControlLoop() throws Exception { + InputStream is = new FileInputStream(new File(TEST_YAML)); final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); UUID requestId = UUID.randomUUID(); VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName("TwoOnsetTest"); + event.setClosedLoopControlName(TWO_ONSET_TEST); event.setRequestId(requestId); - event.setTarget("generic-vnf.vnf-id"); + event.setTarget(VNF_ID); event.setClosedLoopAlarmStart(Instant.now()); event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); event.setAai(new HashMap<>()); - event.getAai().put("generic-vnf.vnf-name", "onsetOne"); + event.getAai().put(VNF_NAME, ONSET_ONE); ControlLoopEventManager manager = makeManager(event); - try { - manager.processControlLoop(); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("ControlLoopEventManager MUST be activated first.", e.getMessage()); - } + ControlLoopEventManager manager2 = manager; + assertThatThrownBy(manager2::processControlLoop).isInstanceOf(ControlLoopException.class) + .hasMessage("ControlLoopEventManager MUST be activated first."); manager.setActivated(true); - try { - manager.processControlLoop(); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("No onset event for ControlLoopEventManager.", e.getMessage()); - } + assertThatThrownBy(manager2::processControlLoop).isInstanceOf(ControlLoopException.class) + .hasMessage("No onset event for ControlLoopEventManager."); manager.setActivated(false); VirtualControlLoopNotification notification = manager.activate(yamlString, event); @@ -639,12 +587,9 @@ public class ControlLoopEventManagerTest { manager = Serializer.roundTrip(manager); // Test operation in progress - try { - manager.processControlLoop(); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("Already working an Operation, do not call this method.", e.getMessage()); - } + ControlLoopEventManager manager3 = manager; + assertThatThrownBy(manager3::processControlLoop).isInstanceOf(ControlLoopException.class) + .hasMessage("Already working an Operation, do not call this method."); manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestId()); notification = manager.activate(yamlString, event); @@ -657,12 +602,9 @@ public class ControlLoopEventManagerTest { assertEquals(ControlLoopNotificationType.FINAL_FAILURE, clfNotification.getNotification()); // Test operation completed - try { - manager.processControlLoop(); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("Control Loop is in FINAL state, do not call this method.", e.getMessage()); - } + ControlLoopEventManager manager4 = manager; + assertThatThrownBy(manager4::processControlLoop).isInstanceOf(ControlLoopException.class) + .hasMessage("Control Loop is in FINAL state, do not call this method."); manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestId()); notification = manager.activate(yamlString, event); @@ -671,59 +613,45 @@ public class ControlLoopEventManagerTest { manager.getProcessor().nextPolicyForResult(PolicyResult.FAILURE); // Test operation with no next policy defined - try { - manager.processControlLoop(); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("The target type is null", e.getMessage()); - } + ControlLoopEventManager manager5 = manager; + assertThatThrownBy(manager5::processControlLoop).isInstanceOf(ControlLoopException.class) + .hasMessage("The target type is null"); } @Test - public void testFinishOperation() throws IOException, ControlLoopException, AaiException { + public void testFinishOperation() throws Exception { InputStream is = new FileInputStream(new File("src/test/resources/testSOactor.yaml")); final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - InputStream isStd = new FileInputStream(new File("src/test/resources/test.yaml")); + InputStream isStd = new FileInputStream(new File(TEST_YAML)); final String yamlStringStd = IOUtils.toString(isStd, StandardCharsets.UTF_8); UUID requestId = UUID.randomUUID(); VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName("TwoOnsetTest"); + event.setClosedLoopControlName(TWO_ONSET_TEST); event.setRequestId(requestId); - event.setTarget("generic-vnf.vnf-id"); + event.setTarget(VNF_ID); event.setClosedLoopAlarmStart(Instant.now()); event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); event.setAai(new HashMap<>()); - event.getAai().put("generic-vnf.vnf-id", "onsetOne"); + event.getAai().put(VNF_ID, ONSET_ONE); ControlLoopEventManager manager = makeManager(event); - try { - manager.finishOperation(null); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("No operation to finish.", e.getMessage()); - } + ControlLoopEventManager manager2 = manager; + assertThatThrownBy(() -> manager2.finishOperation(null)).isInstanceOf(ControlLoopException.class) + .hasMessage("No operation to finish."); manager.setActivated(true); - try { - manager.finishOperation(null); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("No operation to finish.", e.getMessage()); - } + assertThatThrownBy(() -> manager2.finishOperation(null)).isInstanceOf(ControlLoopException.class) + .hasMessage("No operation to finish."); manager.setActivated(false); VirtualControlLoopNotification notification = manager.activate(yamlString, event); assertNotNull(notification); assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - try { - manager.lockCurrentOperation(); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("Do not have a current operation.", e.getMessage()); - } + assertThatThrownBy(manager2::lockCurrentOperation).isInstanceOf(ControlLoopException.class) + .hasMessage("Do not have a current operation."); assertNull(manager.unlockCurrentOperation()); @@ -769,28 +697,28 @@ public class ControlLoopEventManagerTest { } @Test - public void testOnNewEvent() throws IOException, AaiException { - InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + public void testOnNewEvent() throws Exception { + InputStream is = new FileInputStream(new File(TEST_YAML)); final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); UUID requestId = UUID.randomUUID(); VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); - onsetEvent.setClosedLoopControlName("TwoOnsetTest"); + onsetEvent.setClosedLoopControlName(TWO_ONSET_TEST); onsetEvent.setRequestId(requestId); - onsetEvent.setTarget("generic-vnf.vnf-id"); + onsetEvent.setTarget(VNF_ID); onsetEvent.setClosedLoopAlarmStart(Instant.now()); onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); onsetEvent.setAai(new HashMap<>()); - onsetEvent.getAai().put("generic-vnf.vnf-name", "onsetOne"); + onsetEvent.getAai().put(VNF_NAME, ONSET_ONE); VirtualControlLoopEvent abatedEvent = new VirtualControlLoopEvent(); - abatedEvent.setClosedLoopControlName("TwoOnsetTest"); + abatedEvent.setClosedLoopControlName(TWO_ONSET_TEST); abatedEvent.setRequestId(requestId); - abatedEvent.setTarget("generic-vnf.vnf-id"); + abatedEvent.setTarget(VNF_ID); abatedEvent.setClosedLoopAlarmStart(Instant.now()); abatedEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ABATED); abatedEvent.setAai(new HashMap<>()); - abatedEvent.getAai().put("generic-vnf.vnf-name", "onsetOne"); + abatedEvent.getAai().put(VNF_NAME, ONSET_ONE); ControlLoopEventManager manager = makeManager(onsetEvent); VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); @@ -828,7 +756,7 @@ public class ControlLoopEventManagerTest { checkSyntaxEvent.setClosedLoopControlName(""); assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - checkSyntaxEvent.setClosedLoopControlName("TwoOnsetTest"); + checkSyntaxEvent.setClosedLoopControlName(TWO_ONSET_TEST); assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); checkSyntaxEvent.setRequestId(null); @@ -861,13 +789,13 @@ public class ControlLoopEventManagerTest { checkSyntaxEvent.setTarget("VNF_NAME"); assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - checkSyntaxEvent.setTarget("vserver.vserver-name"); + checkSyntaxEvent.setTarget(VSERVER_NAME); assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - checkSyntaxEvent.setTarget("generic-vnf.vnf-id"); + checkSyntaxEvent.setTarget(VNF_ID); assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - checkSyntaxEvent.setTarget("generic-vnf.vnf-name"); + checkSyntaxEvent.setTarget(VNF_NAME); assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); checkSyntaxEvent.setAai(null); @@ -876,30 +804,30 @@ public class ControlLoopEventManagerTest { checkSyntaxEvent.setAai(new HashMap<>()); assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - checkSyntaxEvent.getAai().put("generic-vnf.vnf-name", "onsetOne"); + checkSyntaxEvent.getAai().put(VNF_NAME, ONSET_ONE); assertEquals(NewEventStatus.SUBSEQUENT_ABATEMENT, manager.onNewEvent(abatedEvent)); - checkSyntaxEvent.getAai().put("vserver.vserver-name", "onsetOne"); + checkSyntaxEvent.getAai().put(VSERVER_NAME, ONSET_ONE); assertEquals(NewEventStatus.SUBSEQUENT_ABATEMENT, manager.onNewEvent(abatedEvent)); - checkSyntaxEvent.getAai().put("generic-vnf.vnf-id", "onsetOne"); + checkSyntaxEvent.getAai().put(VNF_ID, ONSET_ONE); assertEquals(NewEventStatus.SUBSEQUENT_ABATEMENT, manager.onNewEvent(abatedEvent)); } @Test public void testControlLoopTimeout() throws IOException { - InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + InputStream is = new FileInputStream(new File(TEST_YAML)); final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); UUID requestId = UUID.randomUUID(); VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); - onsetEvent.setClosedLoopControlName("TwoOnsetTest"); + onsetEvent.setClosedLoopControlName(TWO_ONSET_TEST); onsetEvent.setRequestId(requestId); - onsetEvent.setTarget("generic-vnf.vnf-id"); + onsetEvent.setTarget(VNF_ID); onsetEvent.setClosedLoopAlarmStart(Instant.now()); onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); onsetEvent.setAai(new HashMap<>()); - onsetEvent.getAai().put("generic-vnf.vnf-name", "onsetOne"); + onsetEvent.getAai().put(VNF_NAME, ONSET_ONE); ControlLoopEventManager manager = makeManager(onsetEvent); assertTrue(0 == manager.getControlLoopTimeout(null)); @@ -909,7 +837,7 @@ public class ControlLoopEventManagerTest { assertNotNull(notification); assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - assertTrue(60 == manager.getControlLoopTimeout(null)); + assertEquals(60, manager.getControlLoopTimeout(null)); } @Test @@ -919,13 +847,13 @@ public class ControlLoopEventManagerTest { UUID requestId = UUID.randomUUID(); VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); - onsetEvent.setClosedLoopControlName("TwoOnsetTest"); + onsetEvent.setClosedLoopControlName(TWO_ONSET_TEST); onsetEvent.setRequestId(requestId); - onsetEvent.setTarget("generic-vnf.vnf-id"); + onsetEvent.setTarget(VNF_ID); onsetEvent.setClosedLoopAlarmStart(Instant.now()); onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); onsetEvent.setAai(new HashMap<>()); - onsetEvent.getAai().put("generic-vnf.vnf-name", "onsetOne"); + onsetEvent.getAai().put(VNF_NAME, ONSET_ONE); ControlLoopEventManager manager = makeManager(onsetEvent); @@ -944,13 +872,13 @@ public class ControlLoopEventManagerTest { UUID requestId = UUID.randomUUID(); VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); - onsetEvent.setClosedLoopControlName("TwoOnsetTest"); + onsetEvent.setClosedLoopControlName(TWO_ONSET_TEST); onsetEvent.setRequestId(requestId); - onsetEvent.setTarget("generic-vnf.vnf-id"); + onsetEvent.setTarget(VNF_ID); onsetEvent.setClosedLoopAlarmStart(Instant.now()); onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); onsetEvent.setAai(new HashMap<>()); - onsetEvent.getAai().put("generic-vnf.vnf-name", "onsetOne"); + onsetEvent.getAai().put(VNF_NAME, ONSET_ONE); ControlLoopEventManager manager = makeManager(onsetEvent); @@ -964,43 +892,28 @@ public class ControlLoopEventManagerTest { @Test public void testQueryAai_AlreadyDisabled() throws AaiException { - ControlLoopEventManager mgr = null; - - try { - onset.getAai().put(ControlLoopEventManager.GENERIC_VNF_IS_CLOSED_LOOP_DISABLED, Boolean.TRUE.toString()); - onset.getAai().put(ControlLoopEventManager.GENERIC_VNF_PROV_STATUS, - ControlLoopEventManager.PROV_STATUS_ACTIVE); - - mgr = makeManager(onset); - mgr.queryAai(onset); + onset.getAai().put(ControlLoopEventManager.GENERIC_VNF_IS_CLOSED_LOOP_DISABLED, Boolean.TRUE.toString()); + onset.getAai().put(ControlLoopEventManager.GENERIC_VNF_PROV_STATUS, ControlLoopEventManager.PROV_STATUS_ACTIVE); - fail("missing exception"); + ControlLoopEventManager mgr = makeManager(onset); - } catch (AaiException expected) { - assertEquals("is-closed-loop-disabled is set to true on VServer or VNF", expected.getMessage()); - assertNull(mgr.getVnfResponse()); - assertNull(mgr.getVserverResponse()); - } + assertThatThrownBy(() -> mgr.queryAai(onset)).isInstanceOf(AaiException.class) + .hasMessage("is-closed-loop-disabled is set to true on VServer or VNF"); + assertNull(mgr.getVnfResponse()); + assertNull(mgr.getVserverResponse()); } @Test public void testQueryAai_AlreadyInactive() throws AaiException { - ControlLoopEventManager mgr = null; - - try { - onset.getAai().put(ControlLoopEventManager.GENERIC_VNF_IS_CLOSED_LOOP_DISABLED, Boolean.FALSE.toString()); - onset.getAai().put(ControlLoopEventManager.GENERIC_VNF_PROV_STATUS, "not-active2"); + onset.getAai().put(ControlLoopEventManager.GENERIC_VNF_IS_CLOSED_LOOP_DISABLED, Boolean.FALSE.toString()); + onset.getAai().put(ControlLoopEventManager.GENERIC_VNF_PROV_STATUS, "not-active2"); - mgr = makeManager(onset); - mgr.queryAai(onset); + ControlLoopEventManager mgr = makeManager(onset); - fail("missing exception"); - - } catch (AaiException expected) { - assertEquals("prov-status is not ACTIVE on VServer or VNF", expected.getMessage()); - assertNull(mgr.getVnfResponse()); - assertNull(mgr.getVserverResponse()); - } + assertThatThrownBy(() -> mgr.queryAai(onset)).isInstanceOf(AaiException.class) + .hasMessage("prov-status is not ACTIVE on VServer or VNF"); + assertNull(mgr.getVnfResponse()); + assertNull(mgr.getVserverResponse()); } @Test @@ -1046,33 +959,24 @@ public class ControlLoopEventManagerTest { } @Test - public void testQueryAai_QueryVnfById_Disabled() throws AaiException { - ControlLoopEventManager mgr = null; + public void testQueryAai_QueryVnfById_Disabled() { + onset.getAai().put(ControlLoopEventManager.GENERIC_VNF_VNF_ID, "disableClosedLoop"); - try { - onset.getAai().put(ControlLoopEventManager.GENERIC_VNF_VNF_ID, "disableClosedLoop"); + ControlLoopEventManager mgr = makeManager(onset); - mgr = makeManager(onset); - mgr.queryAai(onset); + assertThatThrownBy(() -> mgr.queryAai(onset)).isInstanceOf(AaiException.class) + .hasMessage("is-closed-loop-disabled is set to true (query by vnf-id)"); - fail("missing exception"); - - } catch (AaiException expected) { - assertEquals("is-closed-loop-disabled is set to true (query by vnf-id)", expected.getMessage()); - - assertNotNull(mgr.getVnfResponse()); - assertNull(mgr.getVserverResponse()); - } + assertNotNull(mgr.getVnfResponse()); + assertNull(mgr.getVserverResponse()); } @Test public void testQueryAai_QueryVserver() throws AaiException { - ControlLoopEventManager mgr = null; - onset.getAai().remove(ControlLoopEventManager.GENERIC_VNF_VNF_ID); onset.getAai().put(ControlLoopEventManager.VSERVER_VSERVER_NAME, "AVserver"); - mgr = makeManager(onset); + ControlLoopEventManager mgr = makeManager(onset); mgr.queryAai(onset); assertNull(mgr.getVnfResponse()); @@ -1088,30 +992,23 @@ public class ControlLoopEventManagerTest { } @Test - public void testQueryAai_QueryVserver_Disabled() throws AaiException { - ControlLoopEventManager mgr = null; - - try { - onset.getAai().remove(ControlLoopEventManager.GENERIC_VNF_VNF_ID); - onset.getAai().put(ControlLoopEventManager.VSERVER_VSERVER_NAME, "disableClosedLoop"); - - mgr = makeManager(onset); - mgr.queryAai(onset); + public void testQueryAai_QueryVserver_Disabled() { + onset.getAai().remove(ControlLoopEventManager.GENERIC_VNF_VNF_ID); + onset.getAai().put(ControlLoopEventManager.VSERVER_VSERVER_NAME, "disableClosedLoop"); - fail("missing exception"); + ControlLoopEventManager mgr = makeManager(onset); - } catch (AaiException expected) { - assertEquals("is-closed-loop-disabled is set to true (query by vserver-name)", expected.getMessage()); + assertThatThrownBy(() -> mgr.queryAai(onset)).isInstanceOf(AaiException.class) + .hasMessage("is-closed-loop-disabled is set to true (query by vserver-name)"); - assertNull(mgr.getVnfResponse()); - assertNotNull(mgr.getVserverResponse()); - } + assertNull(mgr.getVnfResponse()); + assertNotNull(mgr.getVserverResponse()); } @Test(expected = AaiException.class) public void testQueryAai_QueryException() throws AaiException { // Force AAI errors - PolicyEngine.manager.setEnvironmentProperty("aai.url", INVALID_URL); + PolicyEngine.manager.setEnvironmentProperty(AAI_URL, INVALID_URL); makeManager(onset).queryAai(onset); } @@ -1178,7 +1075,7 @@ public class ControlLoopEventManagerTest { svr.setIsClosedLoopDisabled(false); svr.setProvStatus(ControlLoopEventManager.PROV_STATUS_ACTIVE); - Whitebox.invokeMethod(ControlLoopEventManager.class, "processVServerResponse", resp); + Whitebox.invokeMethod(ControlLoopEventManager.class, PROCESS_VSERVER_RESPONSE, resp); } @Test @@ -1187,7 +1084,7 @@ public class ControlLoopEventManagerTest { thrown.expectMessage("AAI Response is null (query by vserver-name)"); AaiGetVserverResponse resp = null; - Whitebox.invokeMethod(ControlLoopEventManager.class, "processVServerResponse", resp); + Whitebox.invokeMethod(ControlLoopEventManager.class, PROCESS_VSERVER_RESPONSE, resp); } @Test @@ -1205,7 +1102,7 @@ public class ControlLoopEventManagerTest { svr.setIsClosedLoopDisabled(false); svr.setProvStatus(ControlLoopEventManager.PROV_STATUS_ACTIVE); - Whitebox.invokeMethod(ControlLoopEventManager.class, "processVServerResponse", resp); + Whitebox.invokeMethod(ControlLoopEventManager.class, PROCESS_VSERVER_RESPONSE, resp); } @Test @@ -1219,7 +1116,7 @@ public class ControlLoopEventManagerTest { svr.setIsClosedLoopDisabled(true); svr.setProvStatus(ControlLoopEventManager.PROV_STATUS_ACTIVE); - Whitebox.invokeMethod(ControlLoopEventManager.class, "processVServerResponse", resp); + Whitebox.invokeMethod(ControlLoopEventManager.class, PROCESS_VSERVER_RESPONSE, resp); } @Test @@ -1233,7 +1130,7 @@ public class ControlLoopEventManagerTest { svr.setIsClosedLoopDisabled(false); svr.setProvStatus("inactive1"); - Whitebox.invokeMethod(ControlLoopEventManager.class, "processVServerResponse", resp); + Whitebox.invokeMethod(ControlLoopEventManager.class, PROCESS_VSERVER_RESPONSE, resp); } @Test @@ -1310,7 +1207,7 @@ public class ControlLoopEventManagerTest { } @Test - public void testGetNqVserverFromAai() throws Exception { + public void testGetNqVserverFromAai() { // empty vserver name ControlLoopEventManager manager = makeManager(onset); @@ -1334,7 +1231,7 @@ public class ControlLoopEventManagerTest { // Force AAI error - PolicyEngine.manager.setEnvironmentProperty("aai.url", INVALID_URL); + PolicyEngine.manager.setEnvironmentProperty(AAI_URL, INVALID_URL); // re-create manager manager = makeManager(onset); @@ -1343,36 +1240,22 @@ public class ControlLoopEventManagerTest { } @Test - public void testGetCqResponseEmptyVserver() { - try { - ControlLoopEventManager mgr = null; - mgr = makeManager(onset); - mgr.queryAai(onset); - mgr.getCqResponse(onset); - fail(); - - - } catch (AaiException e) { - logger.error("testGetCqResponse Exception: ", e); - assertEquals(e.getMessage(), "Vserver name is missing"); - } + public void testGetCqResponseEmptyVserver() throws AaiException { + ControlLoopEventManager mgr = makeManager(onset); + mgr.queryAai(onset); + + assertThatThrownBy(() -> mgr.getCqResponse(onset)).isInstanceOf(AaiException.class) + .hasMessage("Vserver name is missing"); } @Test - public void testGetCqResponse() { - try { - ControlLoopEventManager mgr = null; - mgr = makeManager(onset); - mgr.queryAai(onset); - onset.getAai().put("vserver.vserver-name", "sample"); - AaiCqResponse aaiCqResponse = mgr.getCqResponse(onset); - assertNotNull(aaiCqResponse); - - - } catch (Exception e) { - logger.error("testGetCqResponse Exception: ", e); - fail(e.getMessage()); - } + public void testGetCqResponse() throws AaiException { + ControlLoopEventManager mgr = makeManager(onset); + mgr.queryAai(onset); + onset.getAai().put(VSERVER_NAME, "sample"); + + AaiCqResponse aaiCqResponse = mgr.getCqResponse(onset); + assertNotNull(aaiCqResponse); } diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManagerTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManagerTest.java index 568f8bcd4..835b4ac82 100644 --- a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManagerTest.java +++ b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManagerTest.java @@ -20,12 +20,12 @@ package org.onap.policy.controlloop.eventmanager; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import java.io.File; import java.io.FileInputStream; @@ -37,8 +37,6 @@ import java.util.HashMap; import java.util.UUID; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; -import javax.persistence.NoResultException; -import javax.persistence.NonUniqueResultException; import javax.persistence.Persistence; import javax.persistence.Query; import org.apache.commons.io.IOUtils; @@ -79,6 +77,21 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ControlLoopOperationManagerTest { + private static final String VSERVER_NAME = "vserver.vserver-name"; + private static final String TEST_YAML = "src/test/resources/test.yaml"; + private static final String ONSET_ONE = "onsetOne"; + private static final String VNF_NAME = "generic-vnf.vnf-name"; + private static final String VNF_ID = "generic-vnf.vnf-id"; + private static final String TWO_ONSET_TEST = "TwoOnsetTest"; + private static final String OPER_MSG = "The Wizard Escaped"; + private static final String OZ_VNF = "OzVNF"; + private static final String OPERATIONS_HISTORY_PU_TEST = "OperationsHistoryPUTest"; + private static final String OPERATIONS_HISTORY_PU = "OperationsHistoryPU"; + private static final String DOROTHY = "Dorothy"; + private static final String APPC_FAILURE_REASON = "AppC failed for some reason"; + private static final String ACCEPT = "ACCEPT"; + + private static final Logger logger = LoggerFactory.getLogger(ControlLoopOperationManagerTest.class); @@ -87,11 +100,11 @@ public class ControlLoopOperationManagerTest { static { onset = new VirtualControlLoopEvent(); onset.setRequestId(UUID.randomUUID()); - onset.setTarget("generic-vnf.vnf-name"); + onset.setTarget(VNF_NAME); onset.setTargetType(ControlLoopTargetType.VNF); onset.setClosedLoopAlarmStart(Instant.now()); onset.setAai(new HashMap<>()); - onset.getAai().put("generic-vnf.vnf-name", "testTriggerSource"); + onset.getAai().put(VNF_NAME, "testTriggerSource"); onset.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); /* Set environment properties */ @@ -109,14 +122,7 @@ public class ControlLoopOperationManagerTest { String sql = "select count(*) as count from operationshistory"; Query nq = em.createNativeQuery(sql); - int numEvents = -1; - try { - numEvents = ((Number) nq.getSingleResult()).intValue(); - } catch (NoResultException | NonUniqueResultException ex) { - logger.error("getCountFromDb threw: ", ex); - fail(ex.getMessage()); - } - return numEvents; + return ((Number) nq.getSingleResult()).intValue(); } @@ -124,16 +130,12 @@ public class ControlLoopOperationManagerTest { * Set up test class. */ @BeforeClass - public static void setUp() { + public static void setUp() throws Exception { - try { - org.onap.policy.simulators.Util.buildAaiSim(); - } catch (Exception e) { - fail(e.getMessage()); - } + org.onap.policy.simulators.Util.buildAaiSim(); // Set PU - System.setProperty("OperationsHistoryPU", "OperationsHistoryPUTest"); + System.setProperty(OPERATIONS_HISTORY_PU, OPERATIONS_HISTORY_PU_TEST); // Enter dummy props to avoid nullPointerException PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_URL, "a"); @@ -141,7 +143,7 @@ public class ControlLoopOperationManagerTest { PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_PASS, "c"); // Connect to in-mem db - emf = Persistence.createEntityManagerFactory("OperationsHistoryPUTest"); + emf = Persistence.createEntityManagerFactory(OPERATIONS_HISTORY_PU_TEST); em = emf.createEntityManager(); } @@ -157,232 +159,214 @@ public class ControlLoopOperationManagerTest { } @Test - public void testRetriesFail() { + public void testRetriesFail() throws Exception { // // Load up the policy // - final SupportUtil.Pair<ControlLoopPolicy, String> pair = SupportUtil.loadYaml("src/test/resources/test.yaml"); + final SupportUtil.Pair<ControlLoopPolicy, String> pair = SupportUtil.loadYaml(TEST_YAML); onset.setClosedLoopControlName(pair.key.getControlLoop().getControlLoopName()); - try { - // - // Create a processor - // - final ControlLoopProcessor processor = new ControlLoopProcessor(pair.value); - // - // create the manager - // - ControlLoopEventManager eventManager = - new ControlLoopEventManager(onset.getClosedLoopControlName(), onset.getRequestId()); - VirtualControlLoopNotification notification = eventManager.activate(onset); - - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - ControlLoopEventManager.NewEventStatus status = null; - try { - status = eventManager.onNewEvent(onset); - } catch (AaiException e) { - logger.warn(e.toString()); - fail("A&AI Query Failed"); - } - assertNotNull(status); - assertEquals(ControlLoopEventManager.NewEventStatus.FIRST_ONSET, status); - - ControlLoopOperationManager manager = - new ControlLoopOperationManager(onset, processor.getCurrentPolicy(), eventManager); - logger.debug("{}", manager); - // - // - // - assertFalse(manager.isOperationComplete()); - assertFalse(manager.isOperationRunning()); - // - // Start - // - Object request = manager.startOperation(onset); - logger.debug("{}", manager); - assertNotNull(request); - assertTrue(request instanceof LcmRequestWrapper); - LcmRequestWrapper dmaapRequest = (LcmRequestWrapper) request; - LcmRequest appcRequest = dmaapRequest.getBody(); - assertTrue(appcRequest.getCommonHeader().getSubRequestId().contentEquals("1")); - assertFalse(manager.isOperationComplete()); - assertTrue(manager.isOperationRunning()); - // - // Accept - // - LcmResponseWrapper dmaapResponse = new LcmResponseWrapper(); - LcmResponse appcResponse = new LcmResponse(appcRequest); - appcResponse.getStatus().setCode(100); - appcResponse.getStatus().setMessage("ACCEPT"); - dmaapResponse.setBody(appcResponse); - // - // - // - PolicyResult result = manager.onResponse(dmaapResponse); - logger.debug("{}", manager); - assertTrue(result == null); - assertFalse(manager.isOperationComplete()); - assertTrue(manager.isOperationRunning()); - // - // Now we are going to Fail it - // - appcResponse = new LcmResponse(appcRequest); - appcResponse.getStatus().setCode(401); - appcResponse.getStatus().setMessage("AppC failed for some reason"); - dmaapResponse.setBody(appcResponse); - result = manager.onResponse(dmaapResponse); - logger.debug("{}", manager); - assertTrue(result.equals(PolicyResult.FAILURE)); - assertFalse(manager.isOperationComplete()); - assertFalse(manager.isOperationRunning()); - // - // Retry it - // - request = manager.startOperation(onset); - logger.debug("{}", manager); - assertNotNull(request); - assertTrue(request instanceof LcmRequestWrapper); - dmaapRequest = (LcmRequestWrapper) request; - appcRequest = dmaapRequest.getBody(); - assertTrue(appcRequest.getCommonHeader().getSubRequestId().contentEquals("2")); - assertFalse(manager.isOperationComplete()); - assertTrue(manager.isOperationRunning()); - // - // - // - appcResponse = new LcmResponse(appcRequest); - logger.debug("{}", manager); - appcResponse.getStatus().setCode(100); - appcResponse.getStatus().setMessage("ACCEPT"); - dmaapResponse.setBody(appcResponse); - // - // - // - result = manager.onResponse(dmaapResponse); - logger.debug("{}", manager); - assertTrue(result == null); - assertFalse(manager.isOperationComplete()); - assertTrue(manager.isOperationRunning()); - // - // Now we are going to Fail it - // - appcResponse = new LcmResponse(appcRequest); - appcResponse.getStatus().setCode(401); - appcResponse.getStatus().setMessage("AppC failed for some reason"); - dmaapResponse.setBody(appcResponse); - result = manager.onResponse(dmaapResponse); - logger.debug("{}", manager); - assertTrue(result.equals(PolicyResult.FAILURE)); - // - // Should be complete now - // - assertTrue(manager.isOperationComplete()); - assertFalse(manager.isOperationRunning()); - assertNotNull(manager.getOperationResult()); - assertTrue(manager.getOperationResult().equals(PolicyResult.FAILURE_RETRIES)); - assertTrue(manager.getHistory().size() == 2); - } catch (ControlLoopException | AaiException e) { - fail(e.getMessage()); - } + + // + // Create a processor + // + final ControlLoopProcessor processor = new ControlLoopProcessor(pair.value); + // + // create the manager + // + ControlLoopEventManager eventManager = + new ControlLoopEventManager(onset.getClosedLoopControlName(), onset.getRequestId()); + VirtualControlLoopNotification notification = eventManager.activate(onset); + + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + ControlLoopEventManager.NewEventStatus status = eventManager.onNewEvent(onset); + assertNotNull(status); + assertEquals(ControlLoopEventManager.NewEventStatus.FIRST_ONSET, status); + + ControlLoopOperationManager manager = + new ControlLoopOperationManager(onset, processor.getCurrentPolicy(), eventManager); + logger.debug("{}", manager); + // + // + // + assertFalse(manager.isOperationComplete()); + assertFalse(manager.isOperationRunning()); + // + // Start + // + Object request = manager.startOperation(onset); + logger.debug("{}", manager); + assertNotNull(request); + assertTrue(request instanceof LcmRequestWrapper); + LcmRequestWrapper dmaapRequest = (LcmRequestWrapper) request; + LcmRequest appcRequest = dmaapRequest.getBody(); + assertTrue(appcRequest.getCommonHeader().getSubRequestId().contentEquals("1")); + assertFalse(manager.isOperationComplete()); + assertTrue(manager.isOperationRunning()); + // + // Accept + // + LcmResponseWrapper dmaapResponse = new LcmResponseWrapper(); + LcmResponse appcResponse = new LcmResponse(appcRequest); + appcResponse.getStatus().setCode(100); + appcResponse.getStatus().setMessage(ACCEPT); + dmaapResponse.setBody(appcResponse); + // + // + // + PolicyResult result = manager.onResponse(dmaapResponse); + logger.debug("{}", manager); + assertTrue(result == null); + assertFalse(manager.isOperationComplete()); + assertTrue(manager.isOperationRunning()); + // + // Now we are going to Fail it + // + appcResponse = new LcmResponse(appcRequest); + appcResponse.getStatus().setCode(401); + appcResponse.getStatus().setMessage(APPC_FAILURE_REASON); + dmaapResponse.setBody(appcResponse); + result = manager.onResponse(dmaapResponse); + logger.debug("{}", manager); + assertTrue(result.equals(PolicyResult.FAILURE)); + assertFalse(manager.isOperationComplete()); + assertFalse(manager.isOperationRunning()); + // + // Retry it + // + request = manager.startOperation(onset); + logger.debug("{}", manager); + assertNotNull(request); + assertTrue(request instanceof LcmRequestWrapper); + dmaapRequest = (LcmRequestWrapper) request; + appcRequest = dmaapRequest.getBody(); + assertTrue(appcRequest.getCommonHeader().getSubRequestId().contentEquals("2")); + assertFalse(manager.isOperationComplete()); + assertTrue(manager.isOperationRunning()); + // + // + // + appcResponse = new LcmResponse(appcRequest); + logger.debug("{}", manager); + appcResponse.getStatus().setCode(100); + appcResponse.getStatus().setMessage(ACCEPT); + dmaapResponse.setBody(appcResponse); + // + // + // + result = manager.onResponse(dmaapResponse); + logger.debug("{}", manager); + assertTrue(result == null); + assertFalse(manager.isOperationComplete()); + assertTrue(manager.isOperationRunning()); + // + // Now we are going to Fail it + // + appcResponse = new LcmResponse(appcRequest); + appcResponse.getStatus().setCode(401); + appcResponse.getStatus().setMessage(APPC_FAILURE_REASON); + dmaapResponse.setBody(appcResponse); + result = manager.onResponse(dmaapResponse); + logger.debug("{}", manager); + assertTrue(result.equals(PolicyResult.FAILURE)); + // + // Should be complete now + // + assertTrue(manager.isOperationComplete()); + assertFalse(manager.isOperationRunning()); + assertNotNull(manager.getOperationResult()); + assertTrue(manager.getOperationResult().equals(PolicyResult.FAILURE_RETRIES)); + assertTrue(manager.getHistory().size() == 2); } @Test - public void testTimeout() { + public void testTimeout() throws Exception { // // Load up the policy // - final SupportUtil.Pair<ControlLoopPolicy, String> pair = SupportUtil.loadYaml("src/test/resources/test.yaml"); + final SupportUtil.Pair<ControlLoopPolicy, String> pair = SupportUtil.loadYaml(TEST_YAML); onset.setClosedLoopControlName(pair.key.getControlLoop().getControlLoopName()); - try { - // - // Create a processor - // - final ControlLoopProcessor processor = new ControlLoopProcessor(pair.value); - // - // create the manager - // - ControlLoopEventManager eventManager = - new ControlLoopEventManager(onset.getClosedLoopControlName(), onset.getRequestId()); - VirtualControlLoopNotification notification = eventManager.activate(onset); - - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - ControlLoopEventManager.NewEventStatus status = null; - try { - status = eventManager.onNewEvent(onset); - } catch (AaiException e) { - logger.warn(e.toString()); - fail("A&AI Query Failed"); - } - assertNotNull(status); - assertEquals(ControlLoopEventManager.NewEventStatus.FIRST_ONSET, status); - - ControlLoopOperationManager manager = - new ControlLoopOperationManager(onset, processor.getCurrentPolicy(), eventManager); - // - // - // - logger.debug("{}", manager); - assertFalse(manager.isOperationComplete()); - assertFalse(manager.isOperationRunning()); - // - // Start - // - Object request = manager.startOperation(onset); - logger.debug("{}", manager); - assertNotNull(request); - assertTrue((request) instanceof LcmRequestWrapper); - LcmRequestWrapper dmaapRequest = (LcmRequestWrapper) request; - LcmRequest appcRequest = dmaapRequest.getBody(); - assertTrue((appcRequest).getCommonHeader().getSubRequestId().contentEquals("1")); - assertFalse(manager.isOperationComplete()); - assertTrue(manager.isOperationRunning()); - // - // Accept - // - LcmResponseWrapper dmaapResponse = new LcmResponseWrapper(); - LcmResponse appcResponse = new LcmResponse(appcRequest); - dmaapResponse.setBody(appcResponse); - appcResponse.getStatus().setCode(100); - appcResponse.getStatus().setMessage("ACCEPT"); - // - // - // - PolicyResult result = manager.onResponse(dmaapResponse); - logger.debug("{}", manager); - assertTrue(result == null); - assertFalse(manager.isOperationComplete()); - assertTrue(manager.isOperationRunning()); - // - // Now we are going to simulate Timeout - // - manager.setOperationHasTimedOut(); - logger.debug("{}", manager); - assertTrue(manager.isOperationComplete()); - assertFalse(manager.isOperationRunning()); - assertTrue(manager.getHistory().size() == 1); - assertTrue(manager.getOperationResult().equals(PolicyResult.FAILURE_TIMEOUT)); - // - // Now we are going to Fail the previous request - // - appcResponse = new LcmResponse(appcRequest); - appcResponse.getStatus().setCode(401); - appcResponse.getStatus().setMessage("AppC failed for some reason"); - dmaapResponse.setBody(appcResponse); - result = manager.onResponse(dmaapResponse); - logger.debug("{}", manager); - // - // - // - assertTrue(manager.isOperationComplete()); - assertFalse(manager.isOperationRunning()); - assertTrue(manager.getHistory().size() == 1); - assertTrue(manager.getOperationResult().equals(PolicyResult.FAILURE_TIMEOUT)); - } catch (ControlLoopException | AaiException e) { - fail(e.getMessage()); - } + + // + // Create a processor + // + final ControlLoopProcessor processor = new ControlLoopProcessor(pair.value); + // + // create the manager + // + ControlLoopEventManager eventManager = + new ControlLoopEventManager(onset.getClosedLoopControlName(), onset.getRequestId()); + VirtualControlLoopNotification notification = eventManager.activate(onset); + + assertNotNull(notification); + assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); + + ControlLoopEventManager.NewEventStatus status = eventManager.onNewEvent(onset); + assertNotNull(status); + assertEquals(ControlLoopEventManager.NewEventStatus.FIRST_ONSET, status); + + ControlLoopOperationManager manager = + new ControlLoopOperationManager(onset, processor.getCurrentPolicy(), eventManager); + // + // + // + logger.debug("{}", manager); + assertFalse(manager.isOperationComplete()); + assertFalse(manager.isOperationRunning()); + // + // Start + // + Object request = manager.startOperation(onset); + logger.debug("{}", manager); + assertNotNull(request); + assertTrue((request) instanceof LcmRequestWrapper); + LcmRequestWrapper dmaapRequest = (LcmRequestWrapper) request; + LcmRequest appcRequest = dmaapRequest.getBody(); + assertTrue((appcRequest).getCommonHeader().getSubRequestId().contentEquals("1")); + assertFalse(manager.isOperationComplete()); + assertTrue(manager.isOperationRunning()); + // + // Accept + // + LcmResponseWrapper dmaapResponse = new LcmResponseWrapper(); + LcmResponse appcResponse = new LcmResponse(appcRequest); + dmaapResponse.setBody(appcResponse); + appcResponse.getStatus().setCode(100); + appcResponse.getStatus().setMessage(ACCEPT); + // + // + // + PolicyResult result = manager.onResponse(dmaapResponse); + logger.debug("{}", manager); + assertTrue(result == null); + assertFalse(manager.isOperationComplete()); + assertTrue(manager.isOperationRunning()); + // + // Now we are going to simulate Timeout + // + manager.setOperationHasTimedOut(); + logger.debug("{}", manager); + assertTrue(manager.isOperationComplete()); + assertFalse(manager.isOperationRunning()); + assertTrue(manager.getHistory().size() == 1); + assertTrue(manager.getOperationResult().equals(PolicyResult.FAILURE_TIMEOUT)); + // + // Now we are going to Fail the previous request + // + appcResponse = new LcmResponse(appcRequest); + appcResponse.getStatus().setCode(401); + appcResponse.getStatus().setMessage(APPC_FAILURE_REASON); + dmaapResponse.setBody(appcResponse); + manager.onResponse(dmaapResponse); + logger.debug("{}", manager); + // + // + // + assertTrue(manager.isOperationComplete()); + assertFalse(manager.isOperationRunning()); + assertTrue(manager.getHistory().size() == 1); + assertTrue(manager.getOperationResult().equals(PolicyResult.FAILURE_TIMEOUT)); } @Test @@ -392,13 +376,13 @@ public class ControlLoopOperationManagerTest { UUID requestId = UUID.randomUUID(); VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); - onsetEvent.setClosedLoopControlName("TwoOnsetTest"); + onsetEvent.setClosedLoopControlName(TWO_ONSET_TEST); onsetEvent.setRequestId(requestId); - onsetEvent.setTarget("generic-vnf.vnf-id"); + onsetEvent.setTarget(VNF_ID); onsetEvent.setClosedLoopAlarmStart(Instant.now()); onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); onsetEvent.setAai(new HashMap<>()); - onsetEvent.getAai().put("generic-vnf.vnf-name", "onsetOne"); + onsetEvent.getAai().put(VNF_NAME, ONSET_ONE); ControlLoopEventManager manager = new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestId()); @@ -425,80 +409,55 @@ public class ControlLoopOperationManagerTest { final Target savedTarget = policy.getTarget(); policy.setTarget(null); - try { - clom.getTarget(policy); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("The target is null", e.getMessage()); - } + assertThatThrownBy(() -> clom.getTarget(policy)).hasMessage("The target is null"); policy.setTarget(new Target()); - try { - clom.getTarget(policy); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("The target type is null", e.getMessage()); - } + assertThatThrownBy(() -> clom.getTarget(policy)).hasMessage("The target type is null"); policy.setTarget(savedTarget); policy.getTarget().setType(TargetType.PNF); - try { - clom.getTarget(policy); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("PNF target is not supported", e.getMessage()); - } + assertThatThrownBy(() -> clom.getTarget(policy)).hasMessage("PNF target is not supported"); onsetEvent.setTarget("Oz"); - onsetEvent.getAai().remove("generic-vnf.vnf-name"); - onsetEvent.getAai().remove("generic-vnf.vnf-id"); - onsetEvent.getAai().remove("vserver.vserver-name"); + onsetEvent.getAai().remove(VNF_NAME); + onsetEvent.getAai().remove(VNF_ID); + onsetEvent.getAai().remove(VSERVER_NAME); policy.getTarget().setType(TargetType.VNF); - try { - clom.getTarget(policy); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("Target does not match target type", e.getMessage()); - } + assertThatThrownBy(() -> clom.getTarget(policy)).hasMessage("Target does not match target type"); - onsetEvent.setTarget("vserver.vserver-name"); - onsetEvent.getAai().put("vserver.vserver-name", "OzVServer"); + onsetEvent.setTarget(VSERVER_NAME); + onsetEvent.getAai().put(VSERVER_NAME, "OzVServer"); assertEquals("OzVServer", clom.getTarget(policy)); - onsetEvent.getAai().remove("vserver.vserver-name"); - onsetEvent.setTarget("generic-vnf.vnf-id"); - onsetEvent.getAai().put("generic-vnf.vnf-id", "OzVNF"); - assertEquals("OzVNF", clom.getTarget(policy)); + onsetEvent.getAai().remove(VSERVER_NAME); + onsetEvent.setTarget(VNF_ID); + onsetEvent.getAai().put(VNF_ID, OZ_VNF); + assertEquals(OZ_VNF, clom.getTarget(policy)); - onsetEvent.setTarget("generic-vnf.vnf-name"); - assertEquals("OzVNF", clom.getTarget(policy)); + onsetEvent.setTarget(VNF_NAME); + assertEquals(OZ_VNF, clom.getTarget(policy)); manager.onNewEvent(onsetEvent); - onsetEvent.getAai().remove("generic-vnf.vnf-id"); + onsetEvent.getAai().remove(VNF_ID); manager.getVnfResponse(); if (!Boolean.valueOf(PolicyEngine.manager.getEnvironmentProperty("aai.customQuery"))) { - clom.getEventManager().getVnfResponse().setVnfId("generic-vnf.vnf-id"); - assertEquals("generic-vnf.vnf-id", clom.getTarget(policy)); + clom.getEventManager().getVnfResponse().setVnfId(VNF_ID); + assertEquals(VNF_ID, clom.getTarget(policy)); } policy.getTarget().setType(TargetType.VFC); - try { - clom.getTarget(policy); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("The target type is not supported", e.getMessage()); - } + assertThatThrownBy(() -> clom.getTarget(policy)).hasMessage("The target type is not supported"); assertEquals(Integer.valueOf(20), clom.getOperationTimeout()); assertEquals("20s", clom.getOperationTimeoutString(100)); assertEquals(null, clom.getOperationMessage()); - assertEquals(null, clom.getOperationMessage("The Wizard Escaped")); + assertEquals(null, clom.getOperationMessage(OPER_MSG)); clom.startOperation(onsetEvent); @@ -506,8 +465,8 @@ public class ControlLoopOperationManagerTest { clom.getOperationMessage()); assertEquals( "actor=SO,operation=Restart,target=Target [type=VFC, resourceId=null],subRequestId=1, Guard result: " - + "The Wizard Escaped", - clom.getOperationMessage("The Wizard Escaped")); + + OPER_MSG, + clom.getOperationMessage(OPER_MSG)); assertEquals("actor=SO,operation=Restart,tar", clom.getOperationHistory().substring(0, 30)); @@ -517,18 +476,18 @@ public class ControlLoopOperationManagerTest { @Test public void testConstructor() throws IOException, ControlLoopException, AaiException { - InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + InputStream is = new FileInputStream(new File(TEST_YAML)); final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); UUID requestId = UUID.randomUUID(); VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); - onsetEvent.setClosedLoopControlName("TwoOnsetTest"); + onsetEvent.setClosedLoopControlName(TWO_ONSET_TEST); onsetEvent.setRequestId(requestId); - onsetEvent.setTarget("generic-vnf.vnf-id"); + onsetEvent.setTarget(VNF_ID); onsetEvent.setClosedLoopAlarmStart(Instant.now()); onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); onsetEvent.setAai(new HashMap<>()); - onsetEvent.getAai().put("generic-vnf.vnf-name", "onsetOne"); + onsetEvent.getAai().put(VNF_NAME, ONSET_ONE); ControlLoopEventManager manager = new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestId()); @@ -542,12 +501,8 @@ public class ControlLoopOperationManagerTest { policy.setRecipe("ModifyConfig"); policy.getTarget().setResourceID(UUID.randomUUID().toString()); - try { - new ControlLoopOperationManager(onsetEvent, policy, manager); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("Target vnf-id could not be found", e.getMessage()); - } + assertThatThrownBy(() -> new ControlLoopOperationManager(onsetEvent, policy, manager)) + .hasMessage("Target vnf-id could not be found"); policy.getTarget().setResourceID("82194af1-3c2c-485a-8f44-420e22a9eaa4"); clom = new ControlLoopOperationManager(onsetEvent, policy, manager); @@ -562,29 +517,25 @@ public class ControlLoopOperationManagerTest { clom = new ControlLoopOperationManager(onsetEvent, policy, manager); assertNotNull(clom); - policy.setActor("Dorothy"); - try { - new ControlLoopOperationManager(onsetEvent, policy, manager); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("ControlLoopEventManager: policy has an unknown actor.", e.getMessage()); - } + policy.setActor(DOROTHY); + assertThatThrownBy(() -> new ControlLoopOperationManager(onsetEvent, policy, manager)) + .hasMessage("ControlLoopEventManager: policy has an unknown actor."); } @Test public void testStartOperation() throws IOException, ControlLoopException, AaiException { - InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + InputStream is = new FileInputStream(new File(TEST_YAML)); final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); UUID requestId = UUID.randomUUID(); VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); - onsetEvent.setClosedLoopControlName("TwoOnsetTest"); + onsetEvent.setClosedLoopControlName(TWO_ONSET_TEST); onsetEvent.setRequestId(requestId); - onsetEvent.setTarget("generic-vnf.vnf-id"); + onsetEvent.setTarget(VNF_ID); onsetEvent.setClosedLoopAlarmStart(Instant.now()); onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); onsetEvent.setAai(new HashMap<>()); - onsetEvent.getAai().put("generic-vnf.vnf-name", "onsetOne"); + onsetEvent.getAai().put(VNF_NAME, ONSET_ONE); ControlLoopEventManager manager = new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestId()); @@ -597,13 +548,9 @@ public class ControlLoopOperationManagerTest { assertNotNull(clom); clom.startOperation(onsetEvent); - - try { - clom.startOperation(onsetEvent); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("current operation is not null (an operation is already running)", e.getMessage()); - } + ControlLoopOperationManager clom2 = clom; + assertThatThrownBy(() -> clom2.startOperation(onsetEvent)) + .hasMessage("current operation is not null (an operation is already running)"); clom = new ControlLoopOperationManager(onsetEvent, policy, manager); assertNotNull(clom); @@ -619,12 +566,9 @@ public class ControlLoopOperationManagerTest { clom.startOperation(onsetEvent); clom.setOperationHasTimedOut(); assertTrue(clom.isOperationComplete()); - try { - clom.startOperation(onsetEvent); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("current operation failed and retries are not allowed", e.getMessage()); - } + ControlLoopOperationManager clom3 = clom; + assertThatThrownBy(() -> clom3.startOperation(onsetEvent)) + .hasMessage("current operation failed and retries are not allowed"); policy.setRetry(0); clom = new ControlLoopOperationManager(onsetEvent, policy, manager); @@ -632,12 +576,9 @@ public class ControlLoopOperationManagerTest { clom.startOperation(onsetEvent); clom.setOperationHasTimedOut(); assertTrue(clom.isOperationComplete()); - try { - clom.startOperation(onsetEvent); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("current operation failed and retries are not allowed", e.getMessage()); - } + ControlLoopOperationManager clom4 = clom; + assertThatThrownBy(() -> clom4.startOperation(onsetEvent)) + .hasMessage("current operation failed and retries are not allowed"); policy.setRetry(1); clom = new ControlLoopOperationManager(onsetEvent, policy, manager); @@ -647,12 +588,9 @@ public class ControlLoopOperationManagerTest { clom.startOperation(onsetEvent); clom.setOperationHasTimedOut(); assertTrue(clom.isOperationComplete()); - try { - clom.startOperation(onsetEvent); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("current oepration has failed after 2 retries", e.getMessage()); - } + ControlLoopOperationManager clom5 = clom; + assertThatThrownBy(() -> clom5.startOperation(onsetEvent)) + .hasMessage("current oepration has failed after 2 retries"); clom = new ControlLoopOperationManager(onsetEvent, policy, manager); assertNotNull(clom); @@ -667,28 +605,25 @@ public class ControlLoopOperationManagerTest { clom = new ControlLoopOperationManager(onsetEvent, policy, manager); assertNotNull(clom); policy.setActor("Oz"); - try { - clom.startOperation(onsetEvent); - fail("test should throw an exception here"); - } catch (Exception e) { - assertEquals("invalid actor Oz on policy", e.getMessage()); - } + ControlLoopOperationManager clom6 = clom; + assertThatThrownBy(() -> clom6.startOperation(onsetEvent)) + .hasMessage("invalid actor Oz on policy"); } @Test public void testOnResponse() throws IOException, ControlLoopException, AaiException { - InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + InputStream is = new FileInputStream(new File(TEST_YAML)); final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); UUID requestId = UUID.randomUUID(); VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); - onsetEvent.setClosedLoopControlName("TwoOnsetTest"); + onsetEvent.setClosedLoopControlName(TWO_ONSET_TEST); onsetEvent.setRequestId(requestId); - onsetEvent.setTarget("generic-vnf.vnf-id"); + onsetEvent.setTarget(VNF_ID); onsetEvent.setClosedLoopAlarmStart(Instant.now()); onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); onsetEvent.setAai(new HashMap<>()); - onsetEvent.getAai().put("generic-vnf.vnf-name", "onsetOne"); + onsetEvent.getAai().put(VNF_NAME, ONSET_ONE); ControlLoopEventManager manager = new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestId()); @@ -770,18 +705,18 @@ public class ControlLoopOperationManagerTest { @Test public void testCompleteOperation() throws ControlLoopException, AaiException, IOException { - InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + InputStream is = new FileInputStream(new File(TEST_YAML)); final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); UUID requestId = UUID.randomUUID(); VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); - onsetEvent.setClosedLoopControlName("TwoOnsetTest"); + onsetEvent.setClosedLoopControlName(TWO_ONSET_TEST); onsetEvent.setRequestId(requestId); - onsetEvent.setTarget("generic-vnf.vnf-id"); + onsetEvent.setTarget(VNF_ID); onsetEvent.setClosedLoopAlarmStart(Instant.now()); onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); onsetEvent.setAai(new HashMap<>()); - onsetEvent.getAai().put("generic-vnf.vnf-name", "onsetOne"); + onsetEvent.getAai().put(VNF_NAME, ONSET_ONE); ControlLoopEventManager manager = new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestId()); @@ -801,34 +736,32 @@ public class ControlLoopOperationManagerTest { PolicyEngine.manager.setEnvironmentProperty("guard.disabled", "false"); PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_URL, "http://somewhere.over.the.rainbow"); - PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_USER, "Dorothy"); + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_USER, DOROTHY); PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_PASS, "Toto"); assertEquals(PolicyResult.FAILURE, clom.onResponse(soRw)); - System.setProperty("OperationsHistoryPU", "OperationsHistoryPUTest"); + System.setProperty(OPERATIONS_HISTORY_PU, OPERATIONS_HISTORY_PU_TEST); assertEquals(PolicyResult.FAILURE, clom.onResponse(soRw)); } @Test - public void testCommitAbatement() throws ControlLoopException, AaiException, IOException { + public void testCommitAbatement() throws Exception { String yamlString = null; - try (InputStream is = new FileInputStream(new File("src/test/resources/test.yaml"))) { + try (InputStream is = new FileInputStream(new File(TEST_YAML))) { yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - } catch (Exception e) { - fail(e.getMessage()); } UUID requestId = UUID.randomUUID(); VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); - onsetEvent.setClosedLoopControlName("TwoOnsetTest"); + onsetEvent.setClosedLoopControlName(TWO_ONSET_TEST); onsetEvent.setRequestId(requestId); - onsetEvent.setTarget("generic-vnf.vnf-id"); + onsetEvent.setTarget(VNF_ID); onsetEvent.setClosedLoopAlarmStart(Instant.now()); onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); onsetEvent.setAai(new HashMap<>()); - onsetEvent.getAai().put("generic-vnf.vnf-name", "onsetOne"); + onsetEvent.getAai().put(VNF_NAME, ONSET_ONE); ControlLoopEventManager manager = new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestId()); @@ -850,23 +783,24 @@ public class ControlLoopOperationManagerTest { int numEventsAfter = getCount(); logger.info("numEventsAfter={}", numEventsAfter); - assertEquals(1, numEventsAfter - numEventsBefore); + int diff = numEventsAfter - numEventsBefore; + assertEquals(1, diff); } @Test public void testSerialization() throws Exception { - InputStream is = new FileInputStream(new File("src/test/resources/test.yaml")); + InputStream is = new FileInputStream(new File(TEST_YAML)); final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); UUID requestId = UUID.randomUUID(); VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); - onsetEvent.setClosedLoopControlName("TwoOnsetTest"); + onsetEvent.setClosedLoopControlName(TWO_ONSET_TEST); onsetEvent.setRequestId(requestId); - onsetEvent.setTarget("generic-vnf.vnf-id"); + onsetEvent.setTarget(VNF_ID); onsetEvent.setClosedLoopAlarmStart(Instant.now()); onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); onsetEvent.setAai(new HashMap<>()); - onsetEvent.getAai().put("generic-vnf.vnf-name", "onsetOne"); + onsetEvent.getAai().put(VNF_NAME, ONSET_ONE); ControlLoopEventManager manager = new ControlLoopEventManager(onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestId()); @@ -891,7 +825,7 @@ public class ControlLoopOperationManagerTest { PolicyEngine.manager.setEnvironmentProperty("guard.disabled", "false"); PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_URL, "http://somewhere.over.the.rainbow"); - PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_USER, "Dorothy"); + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_USER, DOROTHY); PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_PASS, "Toto"); assertEquals(PolicyResult.FAILURE, clom.onResponse(soRw)); @@ -903,7 +837,7 @@ public class ControlLoopOperationManagerTest { assertFalse(clom.isOperationRunning()); assertEquals(1, clom.getHistory().size()); - System.setProperty("OperationsHistoryPU", "OperationsHistoryPUTest"); + System.setProperty(OPERATIONS_HISTORY_PU, OPERATIONS_HISTORY_PU_TEST); assertEquals(PolicyResult.FAILURE, clom.onResponse(soRw)); clom = Serializer.roundTrip(clom); diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/processor/ControlLoopProcessorTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/processor/ControlLoopProcessorTest.java index 2a6dc7bbd..84fe44914 100644 --- a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/processor/ControlLoopProcessorTest.java +++ b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/processor/ControlLoopProcessorTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * unit test * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,17 +20,15 @@ package org.onap.policy.controlloop.processor; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; - import org.apache.commons.io.IOUtils; import org.junit.Test; import org.onap.policy.controlloop.ControlLoopException; @@ -56,13 +54,8 @@ public class ControlLoopProcessorTest { InputStream is = new FileInputStream(new File("src/test/resources/string.yaml")); String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - try { - new ControlLoopProcessor(yamlString); - fail("test should thrown an exception"); - } catch (Exception e) { - assertEquals("Cannot create property=string for JavaBean=ControlLoopPolicy", - e.getMessage().substring(0, 60)); - } + assertThatThrownBy(() -> new ControlLoopProcessor(yamlString)) + .hasMessageStartingWith("Cannot create property=string for JavaBean=ControlLoopPolicy"); } @Test @@ -73,12 +66,8 @@ public class ControlLoopProcessorTest { ControlLoopProcessor clProcessor = new ControlLoopProcessor(yamlString); assertNull(clProcessor.getCurrentPolicy()); - try { - clProcessor.nextPolicyForResult(PolicyResult.SUCCESS); - fail("test shold throw an exception here"); - } catch (ControlLoopException e) { - assertEquals("There is no current policy to determine where to go to.", e.getMessage()); - } + assertThatThrownBy(() -> clProcessor.nextPolicyForResult(PolicyResult.SUCCESS)) + .hasMessageStartingWith("There is no current policy to determine where to go to."); } @Test @@ -87,13 +76,8 @@ public class ControlLoopProcessorTest { String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); ControlLoopProcessor clProcessor = new ControlLoopProcessor(yamlString); - - try { - clProcessor.getCurrentPolicy(); - fail("test shold throw an exception here"); - } catch (ControlLoopException e) { - assertEquals("There are no policies defined.", e.getMessage()); - } + assertThatThrownBy(clProcessor::getCurrentPolicy) + .hasMessage("There are no policies defined."); } @Test @@ -128,7 +112,7 @@ public class ControlLoopProcessorTest { /** * Test policies in the given yaml following the successfull path. - * + * * @param yaml yaml containing the policies to test * @throws ControlLoopException if an error occurs */ @@ -150,7 +134,7 @@ public class ControlLoopProcessorTest { /** * Test policies in the given yaml following the failure path. - * + * * @param yaml yaml containing the policies to test * @throws ControlLoopException if an error occurs */ diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/utils/ControlLoopUtilsTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/utils/ControlLoopUtilsTest.java index 72e51bae9..47907d9c3 100644 --- a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/utils/ControlLoopUtilsTest.java +++ b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/utils/ControlLoopUtilsTest.java @@ -22,12 +22,10 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; -import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Map; import org.junit.Test; -import org.onap.policy.common.utils.coder.CoderException; import org.onap.policy.common.utils.coder.StandardCoder; import org.onap.policy.controlloop.params.ControlLoopParams; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; @@ -35,7 +33,7 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; public class ControlLoopUtilsTest { @Test - public void toControlLoopParams() throws IOException, CoderException { + public void toControlLoopParams() throws Exception { String policy = new String(Files.readAllBytes(Paths.get("src/test/resources/tosca-policy-operational-restart.json"))); diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/drools/DroolsPolicyEngineTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/drools/DroolsPolicyEngineTest.java index dcf3e6c95..cc5302f61 100644 --- a/controlloop/common/eventmanager/src/test/java/org/onap/policy/drools/DroolsPolicyEngineTest.java +++ b/controlloop/common/eventmanager/src/test/java/org/onap/policy/drools/DroolsPolicyEngineTest.java @@ -3,6 +3,7 @@ * eventmanager * ================================================================================ * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,40 +35,43 @@ import org.onap.policy.controlloop.VirtualControlLoopNotification; import org.onap.policy.drools.impl.PolicyEngineJUnitImpl; public class DroolsPolicyEngineTest { + private static final String TOPIC = "TheWizardOfOz"; + private static final String OMNI_BUS = "OmniBus"; + @Test public void testDroolsPolicyEngine() { PolicyEngineJUnitImpl pe = new PolicyEngineJUnitImpl(); assertNotNull(pe); pe.addListener(new TestPolicyEngineListener()); - pe.notifyListeners("TheWizardOfOz"); + pe.notifyListeners(TOPIC); - pe.subscribe("OmniBus", "TheWizardOfOz"); + pe.subscribe(OMNI_BUS, TOPIC); - pe.deliver("OmniBus", "TheWizardOfOz", "Dorothy"); + pe.deliver(OMNI_BUS, TOPIC, "Dorothy"); - pe.subscribe("OmniBus", "TheWizardOfOz"); - pe.subscribe("OmniBus", "ThisTopicDoesNotExist"); + pe.subscribe(OMNI_BUS, TOPIC); + pe.subscribe(OMNI_BUS, "ThisTopicDoesNotExist"); ControlLoopNotification notification = new VirtualControlLoopNotification(); - pe.deliver("OmniBus", "TheWizardOfOz", notification); + pe.deliver(OMNI_BUS, TOPIC, notification); Request request = new Request(); request.setCommonHeader(new CommonHeader()); request.getCommonHeader().setSubRequestId("12321"); - pe.deliver("OmniBus", "TheWizardOfOz", request); + pe.deliver(OMNI_BUS, TOPIC, request); LcmRequestWrapper lcmRw = new LcmRequestWrapper(); lcmRw.setBody(new LcmRequest()); lcmRw.getBody().setCommonHeader(new LcmCommonHeader()); lcmRw.getBody().getCommonHeader().setSubRequestId("54321"); - pe.deliver("OmniBus", "TheWizardOfOz", lcmRw); + pe.deliver(OMNI_BUS, TOPIC, lcmRw); } private class TestPolicyEngineListener implements PolicyEngineListener { @Override public void newEventNotification(String topic) { - assertEquals("TheWizardOfOz", topic); + assertEquals(TOPIC, topic); } } } diff --git a/controlloop/common/eventmanager/src/test/resources/META-INF/persistence.xml b/controlloop/common/eventmanager/src/test/resources/META-INF/persistence.xml index e1aa93f51..07dafecbb 100644 --- a/controlloop/common/eventmanager/src/test/resources/META-INF/persistence.xml +++ b/controlloop/common/eventmanager/src/test/resources/META-INF/persistence.xml @@ -18,25 +18,25 @@ limitations under the License.
============LICENSE_END=========================================================
-->
-<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence persistence_1_0.xsd" version="1.0">
+<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://java.sun.com/xml/ns/persistence persistence_1_0.xsd" version="1.0">
<!-- In-mem DB for junit -->
- <persistence-unit name="OperationsHistoryPUTest"
- transaction-type="RESOURCE_LOCAL">
+ <persistence-unit name="OperationsHistoryPUTest" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
- <class>org.onap.policy.database.operationshistory.Dbao</class>
+ <class>org.onap.policy.database.operationshistory.Dbao</class>
<properties>
<property name="eclipselink.ddl-generation" value="create-tables" />
<property name="eclipselink.logging.level" value="FINE" />
- <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
+ <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:testdb;DATABASE_TO_UPPER=FALSE" />
<property name="javax.persistence.jdbc.user" value="policy" />
<property name="javax.persistence.jdbc.password" value="P01icY" />
- <property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
- <property name="javax.persistence.schema-generation.create-source" value="metadata"/>
+ <property name="javax.persistence.schema-generation.database.action" value="drop-and-create" />
+ <property name="javax.persistence.schema-generation.create-source" value="metadata" />
</properties>
</persistence-unit>
diff --git a/controlloop/common/feature-controlloop-management/pom.xml b/controlloop/common/feature-controlloop-management/pom.xml index acbbc737f..b3a3e3771 100644 --- a/controlloop/common/feature-controlloop-management/pom.xml +++ b/controlloop/common/feature-controlloop-management/pom.xml @@ -276,5 +276,15 @@ <version>3.0.0</version> <scope>test</scope> </dependency> + <dependency> + <groupId>org.powermock</groupId> + <artifactId>powermock-api-mockito</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.assertj</groupId> + <artifactId>assertj-core</artifactId> + <scope>test</scope> + </dependency> </dependencies> </project> diff --git a/controlloop/common/feature-controlloop-management/src/main/java/org/onap/policy/drools/apps/controlloop/feature/management/ControlLoopManagementFeature.java b/controlloop/common/feature-controlloop-management/src/main/java/org/onap/policy/drools/apps/controlloop/feature/management/ControlLoopManagementFeature.java index 800971a61..d78545a2d 100644 --- a/controlloop/common/feature-controlloop-management/src/main/java/org/onap/policy/drools/apps/controlloop/feature/management/ControlLoopManagementFeature.java +++ b/controlloop/common/feature-controlloop-management/src/main/java/org/onap/policy/drools/apps/controlloop/feature/management/ControlLoopManagementFeature.java @@ -7,9 +7,9 @@ * 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. @@ -34,6 +34,12 @@ public class ControlLoopManagementFeature implements PolicyEngineFeatureAPI { private static final int SEQNO = 1000; /** + * Factory for various objects. May be overridden by junit tests. + */ + private static Factory factory = new Factory(); + + + /** * retrieves control loops. * * @param controllerName controller name. @@ -41,7 +47,7 @@ public class ControlLoopManagementFeature implements PolicyEngineFeatureAPI { * @return control loops. */ public static Stream<ControlLoopParams> controlLoops(String controllerName, String sessionName) { - PolicyController controller = PolicyController.factory.get(controllerName); + PolicyController controller = factory.getController(controllerName); if (controller == null) { throw new IllegalArgumentException("Invalid Controller Name"); } @@ -89,4 +95,12 @@ public class ControlLoopManagementFeature implements PolicyEngineFeatureAPI { return FEATURE_NAME; } + /** + * Factory that can be overridden by junit tests. + */ + public static class Factory { + public PolicyController getController(String controllerName) { + return PolicyController.factory.get(controllerName); + } + } } diff --git a/controlloop/common/feature-controlloop-management/src/test/java/org/onap/policy/drools/apps/controlloop/feature/management/ControlLoopManagementFeatureTest.java b/controlloop/common/feature-controlloop-management/src/test/java/org/onap/policy/drools/apps/controlloop/feature/management/ControlLoopManagementFeatureTest.java index ac9bff93b..e5034017f 100644 --- a/controlloop/common/feature-controlloop-management/src/test/java/org/onap/policy/drools/apps/controlloop/feature/management/ControlLoopManagementFeatureTest.java +++ b/controlloop/common/feature-controlloop-management/src/test/java/org/onap/policy/drools/apps/controlloop/feature/management/ControlLoopManagementFeatureTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,13 +20,40 @@ package org.onap.policy.drools.apps.controlloop.feature.management; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Collections; +import org.junit.After; import org.junit.Assert; +import org.junit.BeforeClass; import org.junit.Test; +import org.onap.policy.drools.apps.controlloop.feature.management.ControlLoopManagementFeature.Factory; +import org.onap.policy.drools.controller.DroolsController; +import org.onap.policy.drools.system.PolicyController; +import org.powermock.reflect.Whitebox; /** * Control Loop Management Feature Test. */ public class ControlLoopManagementFeatureTest { + private static final String FACTORY_FIELD = "factory"; + private static final String SESSION_NAME = "my-session"; + private static final String CONTROLLER_NAME = "my-controller"; + + private static Factory saveFactory; + + @BeforeClass + public static void setUpBeforeClass() { + saveFactory = Whitebox.getInternalState(ControlLoopManagementFeature.class, FACTORY_FIELD); + } + + @After + public void tearDown() { + Whitebox.setInternalState(ControlLoopManagementFeature.class, FACTORY_FIELD, saveFactory); + } /** * Sequence Number Test. @@ -43,4 +70,33 @@ public class ControlLoopManagementFeatureTest { public void getName() { Assert.assertEquals("controlloop-management", new ControlLoopManagementFeature().getName()); } -}
\ No newline at end of file + + @Test + public void testControlLoops_InvalidArgs() { + Factory factory = mock(Factory.class); + Whitebox.setInternalState(ControlLoopManagementFeature.class, FACTORY_FIELD, factory); + + // returns null controller + when(factory.getController(any())).thenReturn(null); + assertThatIllegalArgumentException() + .isThrownBy(() -> ControlLoopManagementFeature.controlLoops(CONTROLLER_NAME, SESSION_NAME)) + .withMessage("Invalid Controller Name"); + + // non-matching session name + PolicyController ctlr = mock(PolicyController.class); + DroolsController drools = mock(DroolsController.class); + when(drools.getSessionNames()).thenReturn(Collections.emptyList()); + when(ctlr.getDrools()).thenReturn(drools); + when(factory.getController(any())).thenReturn(ctlr); + assertThatIllegalArgumentException() + .isThrownBy(() -> ControlLoopManagementFeature.controlLoops(CONTROLLER_NAME, SESSION_NAME)) + .withMessage("Invalid Session Name"); + } + + @Test + public void testFactoryGetController() { + // invoking controlLoops() will invoke the factory.getController() method + assertThatIllegalArgumentException().isThrownBy( + () -> ControlLoopManagementFeature.controlLoops("unknown-controller", SESSION_NAME)); + } +} diff --git a/controlloop/common/feature-controlloop-management/src/test/java/org/onap/policy/drools/server/restful/RestControlLoopManagerTest.java b/controlloop/common/feature-controlloop-management/src/test/java/org/onap/policy/drools/server/restful/RestControlLoopManagerTest.java index 3ed1adfe3..3d89e5a1e 100644 --- a/controlloop/common/feature-controlloop-management/src/test/java/org/onap/policy/drools/server/restful/RestControlLoopManagerTest.java +++ b/controlloop/common/feature-controlloop-management/src/test/java/org/onap/policy/drools/server/restful/RestControlLoopManagerTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -126,7 +126,6 @@ public class RestControlLoopManagerTest { Files.deleteIfExists(controllerPath); } catch (Exception ignored) { /* to satisfy checkstyle */ - ; } Path controllerBakPath = @@ -136,7 +135,6 @@ public class RestControlLoopManagerTest { Files.deleteIfExists(controllerBakPath); } catch (Exception ignored) { /* to satisfy checkstyle */ - ; } } diff --git a/controlloop/common/feature-controlloop-trans/src/main/java/org/onap/policy/drools/apps/controlloop/feature/trans/CacheBasedControlLoopMetricsManager.java b/controlloop/common/feature-controlloop-trans/src/main/java/org/onap/policy/drools/apps/controlloop/feature/trans/CacheBasedControlLoopMetricsManager.java index c5d6a32ac..672ff3fba 100644 --- a/controlloop/common/feature-controlloop-trans/src/main/java/org/onap/policy/drools/apps/controlloop/feature/trans/CacheBasedControlLoopMetricsManager.java +++ b/controlloop/common/feature-controlloop-trans/src/main/java/org/onap/policy/drools/apps/controlloop/feature/trans/CacheBasedControlLoopMetricsManager.java @@ -24,7 +24,6 @@ import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.cache.RemovalListener; -import com.google.common.cache.RemovalNotification; import java.time.Instant; import java.time.ZonedDateTime; @@ -47,6 +46,8 @@ import org.slf4j.LoggerFactory; */ class CacheBasedControlLoopMetricsManager implements ControlLoopMetrics { + private static final String UNEXPECTED_NOTIFICATION_TYPE = "unexpected notification type {} in notification {}"; + private static final Logger logger = LoggerFactory.getLogger(CacheBasedControlLoopMetricsManager.class); private LoadingCache<UUID, VirtualControlLoopNotification> cache; @@ -98,16 +99,12 @@ class CacheBasedControlLoopMetricsManager implements ControlLoopMetrics { } }; - RemovalListener<UUID, VirtualControlLoopNotification> listener = - new RemovalListener<UUID, VirtualControlLoopNotification>() { - @Override - public void onRemoval(RemovalNotification<UUID, VirtualControlLoopNotification> notification) { - if (notification.wasEvicted()) { - evicted(notification.getValue()); - } else { - logger.info("REMOVAL: {} because of {}", notification.getValue().getRequestId(), - notification.getCause().name()); - } + RemovalListener<UUID, VirtualControlLoopNotification> listener = notification -> { + if (notification.wasEvicted()) { + evicted(notification.getValue()); + } else { + logger.info("REMOVAL: {} because of {}", notification.getValue().getRequestId(), + notification.getCause().name()); } }; @@ -139,16 +136,11 @@ class CacheBasedControlLoopMetricsManager implements ControlLoopMetrics { @Override public void transactionEvent(PolicyController controller, VirtualControlLoopNotification notification) { - if (notification == null || notification.getRequestId() == null || notification.getNotification() == null) { - logger.warn("Invalid notification: {}", notification); + if (!isNotificationValid(notification)) { return; } - if (notification.getNotificationTime() == null) { - notification.setNotificationTime(ZonedDateTime.now()); - } - - notification.setFrom(notification.getFrom() + ":" + controller.getName()); + setNotificationValues(controller, notification); switch (notification.getNotification()) { case REJECTED: @@ -166,12 +158,29 @@ class CacheBasedControlLoopMetricsManager implements ControlLoopMetrics { break; default: /* unexpected */ - logger.warn("unexpected notification type {} in notification {}", - notification.getNotification().toString(), notification); + logger.warn(UNEXPECTED_NOTIFICATION_TYPE, + notification.getNotification(), notification); break; } } + private boolean isNotificationValid(VirtualControlLoopNotification notification) { + if (notification == null || notification.getRequestId() == null || notification.getNotification() == null) { + logger.warn("Invalid notification: {}", notification); + return false; + } + + return true; + } + + private void setNotificationValues(PolicyController controller, VirtualControlLoopNotification notification) { + if (notification.getNotificationTime() == null) { + notification.setNotificationTime(ZonedDateTime.now()); + } + + notification.setFrom(notification.getFrom() + ":" + controller.getName()); + } + @Override public VirtualControlLoopNotification getTransaction(UUID requestId) { return cache.getIfPresent(requestId); @@ -260,13 +269,7 @@ class CacheBasedControlLoopMetricsManager implements ControlLoopMetrics { trans.metric().resetTransaction(); break; case OPERATION: - trans.setStatusCode(true); - if (!operations.isEmpty()) { - ControlLoopOperation operation = operations.get(operations.size() - 1); - trans.setTargetEntity(operation.getTarget()); - trans.setTargetServiceName(operation.getActor()); - } - trans.metric().resetTransaction(); + metricOperation(trans, operations); break; case OPERATION_SUCCESS: trans.setStatusCode(true); @@ -280,12 +283,22 @@ class CacheBasedControlLoopMetricsManager implements ControlLoopMetrics { break; default: /* unexpected */ - logger.warn("unexpected notification type {} in notification {}", - notification.getNotification().toString(), notification); + logger.warn(UNEXPECTED_NOTIFICATION_TYPE, + notification.getNotification(), notification); break; } } + private void metricOperation(MDCTransaction trans, List<ControlLoopOperation> operations) { + trans.setStatusCode(true); + if (!operations.isEmpty()) { + ControlLoopOperation operation = operations.get(operations.size() - 1); + trans.setTargetEntity(operation.getTarget()); + trans.setTargetServiceName(operation.getActor()); + } + trans.metric().resetTransaction(); + } + protected void operation(MDCTransaction trans, List<ControlLoopOperation> operations) { if (!operations.isEmpty()) { ControlLoopOperation operation = operations.get(operations.size() - 1); @@ -340,7 +353,7 @@ class CacheBasedControlLoopMetricsManager implements ControlLoopMetrics { break; default: /* unexpected */ - logger.warn("unexpected notification type {} in notification {}", + logger.warn(UNEXPECTED_NOTIFICATION_TYPE, notification.getNotification(), notification); break; } diff --git a/controlloop/common/feature-controlloop-trans/src/test/java/org/onap/policy/drools/apps/controlloop/feature/trans/ControlLoopMetricsFeatureTest.java b/controlloop/common/feature-controlloop-trans/src/test/java/org/onap/policy/drools/apps/controlloop/feature/trans/ControlLoopMetricsFeatureTest.java index 1f1e9de39..661803315 100644 --- a/controlloop/common/feature-controlloop-trans/src/test/java/org/onap/policy/drools/apps/controlloop/feature/trans/ControlLoopMetricsFeatureTest.java +++ b/controlloop/common/feature-controlloop-trans/src/test/java/org/onap/policy/drools/apps/controlloop/feature/trans/ControlLoopMetricsFeatureTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +20,7 @@ package org.onap.policy.drools.apps.controlloop.feature.trans; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @@ -27,7 +28,6 @@ import static org.junit.Assert.assertTrue; import java.nio.file.Path; import java.util.UUID; - import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; @@ -43,6 +43,7 @@ import org.onap.policy.drools.system.PolicyEngine; */ public class ControlLoopMetricsFeatureTest { + private static final String POLICY_CL_MGT = "POLICY-CL-MGT"; private static final Path configPath = SystemPersistence.manager.getConfigurationPath(); private static PolicyController testController; @@ -63,46 +64,42 @@ public class ControlLoopMetricsFeatureTest { @Test public void cacheDefaults() { - assertTrue(ControlLoopMetrics.manager.getCacheSize() == 3); - assertTrue(ControlLoopMetrics.manager.getTransactionTimeout() == 10); - assertTrue(ControlLoopMetrics.manager.getCacheOccupancy() == 0); + assertEquals(3, ControlLoopMetrics.manager.getCacheSize()); + assertEquals(10, ControlLoopMetrics.manager.getTransactionTimeout()); + assertEquals(0, ControlLoopMetrics.manager.getCacheOccupancy()); } @Test public void invalidNotifications() { ControlLoopMetricsFeature feature = new ControlLoopMetricsFeature(); VirtualControlLoopNotification notification = new VirtualControlLoopNotification(); - feature.beforeDeliver(testController, CommInfrastructure.DMAAP, "POLICY-CL-MGT", notification); + feature.beforeDeliver(testController, CommInfrastructure.DMAAP, POLICY_CL_MGT, notification); this.cacheDefaults(); UUID requestId = UUID.randomUUID(); notification.setRequestId(requestId); - feature.beforeDeliver(testController, CommInfrastructure.DMAAP, "POLICY-CL-MGT", notification); + feature.beforeDeliver(testController, CommInfrastructure.DMAAP, POLICY_CL_MGT, notification); assertNull(ControlLoopMetrics.manager.getTransaction(requestId)); this.cacheDefaults(); } @Test - public void validActiveNotification() { + public void validActiveNotification() throws InterruptedException { ControlLoopMetricsFeature feature = new ControlLoopMetricsFeature(); VirtualControlLoopNotification notification = new VirtualControlLoopNotification(); UUID requestId = UUID.randomUUID(); notification.setRequestId(requestId); notification.setNotification(ControlLoopNotificationType.ACTIVE); - feature.beforeDeliver(testController, CommInfrastructure.DMAAP, "POLICY-CL-MGT", notification); + feature.beforeDeliver(testController, CommInfrastructure.DMAAP, POLICY_CL_MGT, notification); assertNotNull(ControlLoopMetrics.manager.getTransaction(requestId)); assertTrue(ControlLoopMetrics.manager.getTransaction(requestId).getFrom().contains(testController.getName())); assertNotNull(ControlLoopMetrics.manager.getTransaction(requestId).getNotificationTime()); assertTrue(ControlLoopMetrics.manager.getCacheOccupancy() == 1); /* let the entries expire */ - try { - Thread.sleep((ControlLoopMetrics.manager.getTransactionTimeout() + 5) * 1000L); - } catch (InterruptedException e) { - /* nothing to do */ - } + Thread.sleep((ControlLoopMetrics.manager.getTransactionTimeout() + 1) * 1000L); assertNull(ControlLoopMetrics.manager.getTransaction(requestId)); this.cacheDefaults(); @@ -111,7 +108,7 @@ public class ControlLoopMetricsFeatureTest { @Test public void reset() { VirtualControlLoopNotification notification = this.generateNotification(); - new ControlLoopMetricsFeature().beforeDeliver(testController, CommInfrastructure.DMAAP, "POLICY-CL-MGT", + new ControlLoopMetricsFeature().beforeDeliver(testController, CommInfrastructure.DMAAP, POLICY_CL_MGT, notification); assertNotNull(ControlLoopMetrics.manager.getTransaction(notification.getRequestId())); @@ -135,19 +132,19 @@ public class ControlLoopMetricsFeatureTest { } @Test - public void eviction() { + public void eviction() throws InterruptedException { ControlLoopMetricsFeature feature = new ControlLoopMetricsFeature(); for (int i = 0; i < ControlLoopMetrics.manager.getCacheSize(); i++) { VirtualControlLoopNotification notification = generateNotification(); - feature.beforeDeliver(testController, CommInfrastructure.DMAAP, "POLICY-CL-MGT", notification); + feature.beforeDeliver(testController, CommInfrastructure.DMAAP, POLICY_CL_MGT, notification); assertNotNull(ControlLoopMetrics.manager.getTransaction(notification.getRequestId())); } - assertTrue(ControlLoopMetrics.manager.getCacheOccupancy() == ControlLoopMetrics.manager.getCacheOccupancy()); + assertEquals(ControlLoopMetrics.manager.getCacheOccupancy(), ControlLoopMetrics.manager.getCacheOccupancy()); VirtualControlLoopNotification overflowNotification = generateNotification(); - feature.beforeDeliver(testController, CommInfrastructure.DMAAP, "POLICY-CL-MGT", overflowNotification); - assertTrue(ControlLoopMetrics.manager.getCacheOccupancy() == ControlLoopMetrics.manager.getCacheOccupancy()); + feature.beforeDeliver(testController, CommInfrastructure.DMAAP, POLICY_CL_MGT, overflowNotification); + assertEquals(ControlLoopMetrics.manager.getCacheOccupancy(), ControlLoopMetrics.manager.getCacheOccupancy()); assertNotNull(ControlLoopMetrics.manager.getTransaction(overflowNotification.getRequestId())); assertTrue(ControlLoopMetrics.manager.getTransactionIds().size() == ControlLoopMetrics.manager.getCacheSize()); assertTrue(ControlLoopMetrics.manager.getCacheOccupancy() == ControlLoopMetrics.manager.getCacheSize()); @@ -155,11 +152,7 @@ public class ControlLoopMetricsFeatureTest { assertFalse(ControlLoopMetrics.manager.getTransactions().isEmpty()); /* let the entries expire */ - try { - Thread.sleep((ControlLoopMetrics.manager.getTransactionTimeout() + 5) * 1000L); - } catch (InterruptedException e) { - /* nothing to do */ - } + Thread.sleep((ControlLoopMetrics.manager.getTransactionTimeout() + 1) * 1000L); ControlLoopMetrics.manager.refresh(); assertTrue(ControlLoopMetrics.manager.getTransactionIds().size() == ControlLoopMetrics.manager diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/PnfTargetLock.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/PnfTargetLock.java index c1ad34a22..8ddb5ffcf 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/PnfTargetLock.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/PnfTargetLock.java @@ -7,9 +7,9 @@ * 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. @@ -20,70 +20,28 @@ package org.onap.policy.guard.impl; -import java.io.Serializable; import java.util.UUID; - import org.onap.policy.controlloop.policy.TargetType; import org.onap.policy.guard.LockCallback; -import org.onap.policy.guard.TargetLock; -public class PnfTargetLock implements TargetLock, Serializable { +public class PnfTargetLock extends TargetLockImpl { private static final long serialVersionUID = 2335897394577202732L; - private final UUID lockId; - private final TargetType targetType; - private final String target; - private final UUID requestId; - private final transient LockCallback callback; - /** * Construct an instance. - * + * * @param type the target type * @param target the target * @param requestId the request Id * @param callback the callback */ public PnfTargetLock(TargetType type, String target, UUID requestId, LockCallback callback) { - this.lockId = UUID.randomUUID(); - this.targetType = type; - this.target = target; - this.requestId = requestId; - this.callback = callback; - } - - @Override - public UUID getLockId() { - return this.lockId; - } - - - @Override - public TargetType getTargetType() { - return targetType; - } - - @Override - public String getTargetInstance() { - return target; - } - - @Override - public UUID getRequestId() { - return this.requestId; - } - - public LockCallback getCallback() { - return this.callback; + super(type, target, requestId, callback); } @Override public String toString() { - return "PnfTargetLock [lockId=" + lockId + ", targetType=" + targetType + ", target=" + target + ", requestId=" - + requestId + "]"; + return "PnfTargetLock [" + super.toString() + "]"; } - - - } diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/TargetLockImpl.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/TargetLockImpl.java new file mode 100644 index 000000000..d406999f4 --- /dev/null +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/TargetLockImpl.java @@ -0,0 +1,86 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard.impl; + +import java.io.Serializable; +import java.util.UUID; + +import org.onap.policy.controlloop.policy.TargetType; +import org.onap.policy.guard.LockCallback; +import org.onap.policy.guard.TargetLock; + +public class TargetLockImpl implements TargetLock, Serializable { + + private static final long serialVersionUID = 2335897394577202732L; + + private final UUID lockId; + private final TargetType targetType; + private final String target; + private final UUID requestId; + private final transient LockCallback callback; + + /** + * Construct an instance. + * + * @param type the target type + * @param target the target + * @param requestId the request Id + * @param callback the callback + */ + public TargetLockImpl(TargetType type, String target, UUID requestId, LockCallback callback) { + this.lockId = UUID.randomUUID(); + this.targetType = type; + this.target = target; + this.requestId = requestId; + this.callback = callback; + } + + @Override + public UUID getLockId() { + return this.lockId; + } + + + @Override + public TargetType getTargetType() { + return targetType; + } + + @Override + public String getTargetInstance() { + return target; + } + + @Override + public UUID getRequestId() { + return this.requestId; + } + + public LockCallback getCallback() { + return this.callback; + } + + @Override + public String toString() { + return "lockId=" + lockId + ", targetType=" + targetType + ", target=" + target + ", requestId=" + + requestId; + } +} diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/VmTargetLock.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/VmTargetLock.java index 301c6ec7c..2e612a03a 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/VmTargetLock.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/VmTargetLock.java @@ -7,9 +7,9 @@ * 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. @@ -20,66 +20,28 @@ package org.onap.policy.guard.impl; -import java.io.Serializable; import java.util.UUID; - import org.onap.policy.controlloop.policy.TargetType; import org.onap.policy.guard.LockCallback; -import org.onap.policy.guard.TargetLock; -public class VmTargetLock implements TargetLock, Serializable { +public class VmTargetLock extends TargetLockImpl { - private static final long serialVersionUID = -8795145054334409724L; - private final UUID lockId; - private final TargetType targetType; - private final String target; - private final UUID requestId; - private final transient LockCallback callback; + private static final long serialVersionUID = 2335897394577202732L; /** - * Create an instance. - * - * @param targetType the target type + * Construct an instance. + * + * @param type the target type * @param target the target * @param requestId the request Id * @param callback the callback */ - public VmTargetLock(TargetType targetType, String target, UUID requestId, LockCallback callback) { - this.lockId = UUID.randomUUID(); - this.targetType = targetType; - this.target = target; - this.requestId = requestId; - this.callback = callback; - } - - @Override - public UUID getLockId() { - return this.lockId; - } - - @Override - public TargetType getTargetType() { - return targetType; - } - - @Override - public String getTargetInstance() { - return target; - } - - @Override - public UUID getRequestId() { - return this.requestId; - } - - public LockCallback getCallback() { - return this.callback; + public VmTargetLock(TargetType type, String target, UUID requestId, LockCallback callback) { + super(type, target, requestId, callback); } @Override public String toString() { - return "VmTargetLock [lockId=" + lockId + ", targetType=" + targetType + ", target=" + target + ", requestId=" - + requestId + "]"; + return "VmTargetLock [" + super.toString() + "]"; } - } diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/VnfTargetLock.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/VnfTargetLock.java index 2e3fc28b1..2912c7ad4 100644 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/VnfTargetLock.java +++ b/controlloop/common/guard/src/main/java/org/onap/policy/guard/impl/VnfTargetLock.java @@ -7,9 +7,9 @@ * 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. @@ -20,70 +20,28 @@ package org.onap.policy.guard.impl; -import java.io.Serializable; import java.util.UUID; - import org.onap.policy.controlloop.policy.TargetType; import org.onap.policy.guard.LockCallback; -import org.onap.policy.guard.TargetLock; -public class VnfTargetLock implements TargetLock, Serializable { +public class VnfTargetLock extends TargetLockImpl { private static final long serialVersionUID = 2335897394577202732L; - private final UUID lockId; - private final TargetType targetType; - private final String target; - private final UUID requestId; - private final transient LockCallback callback; - /** - * Create an instance. - * - * @param type the type + * Construct an instance. + * + * @param type the target type * @param target the target * @param requestId the request Id * @param callback the callback */ public VnfTargetLock(TargetType type, String target, UUID requestId, LockCallback callback) { - this.lockId = UUID.randomUUID(); - this.targetType = type; - this.target = target; - this.requestId = requestId; - this.callback = callback; - } - - @Override - public UUID getLockId() { - return this.lockId; - } - - - @Override - public TargetType getTargetType() { - return targetType; - } - - @Override - public String getTargetInstance() { - return target; - } - - @Override - public UUID getRequestId() { - return this.requestId; - } - - public LockCallback getCallback() { - return this.callback; + super(type, target, requestId, callback); } @Override public String toString() { - return "VnfTargetLock [lockId=" + lockId + ", targetType=" + targetType + ", target=" + target + ", requestId=" - + requestId + "]"; + return "VnfTargetLock [" + super.toString() + "]"; } - - - } diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/GuardUtilTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/GuardUtilTest.java index 2ee514abd..e17207634 100644 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/GuardUtilTest.java +++ b/controlloop/common/guard/src/test/java/org/onap/policy/guard/GuardUtilTest.java @@ -24,11 +24,9 @@ package org.onap.policy.guard; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; -import com.att.aft.dme2.internal.google.common.io.Files; - +import com.google.common.io.Files; import java.io.File; import java.io.IOException; - import org.junit.Test; import org.onap.policy.controlloop.policy.ControlLoopPolicy; import org.onap.policy.controlloop.policy.guard.ControlLoopGuard; @@ -40,6 +38,7 @@ public class GuardUtilTest { @Test public void testLoadYamlOk() throws IOException { File tempYamlFile = File.createTempFile("ONAPPF", "yaml"); + tempYamlFile.deleteOnExit(); ControlLoopPolicy clPolicy = new ControlLoopPolicy(); @@ -52,23 +51,21 @@ public class GuardUtilTest { assertEquals(clPolicy, result.parameterA); assertEquals(clYamlString, result.parameterB); - - tempYamlFile.delete(); } @Test public void testLoadYamlError() throws IOException { File tempDir = Files.createTempDir(); + tempDir.deleteOnExit(); // Read from a directory forces an IO exception assertNull(Util.loadYaml(tempDir.getCanonicalPath())); - - tempDir.delete(); } @Test public void testLoadGuardYamlOk() throws IOException { File tempYamlFile = File.createTempFile("ONAPPF", "yaml"); + tempYamlFile.deleteOnExit(); ControlLoopGuard clGuardPolicy = new ControlLoopGuard(); @@ -80,18 +77,15 @@ public class GuardUtilTest { ControlLoopGuard result = Util.loadYamlGuard(tempYamlFile.getCanonicalPath()); assertEquals(clGuardPolicy, result); - - tempYamlFile.delete(); } @Test public void testLoadGuardYamlError() throws IOException { File tempDir = Files.createTempDir(); + tempDir.deleteOnExit(); // Read from a directory forces an IO exception assertNull(Util.loadYamlGuard(tempDir.getCanonicalPath())); - - tempDir.delete(); } @Test diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardRequestTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardRequestTest.java index 3b0441fc2..2be0e06ec 100644 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardRequestTest.java +++ b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardRequestTest.java @@ -31,25 +31,29 @@ import org.junit.Test; public class PolicyGuardRequestTest { + private static final String KANSAS = "Kansas"; + private static final String GET_BACK_HOME = "GetBackHome"; + private static final String DOROTHY = "Dorothy"; + @Test public void policyGuardRequestTest() { UUID requestId = UUID.randomUUID(); assertNotNull(new PolicyGuardRequest(null, null, null, null)); - PolicyGuardRequest request = new PolicyGuardRequest("Dorothy", "Kansas", requestId, "GetBackHome"); + PolicyGuardRequest request = new PolicyGuardRequest(DOROTHY, KANSAS, requestId, GET_BACK_HOME); request.setRequestId(requestId); assertEquals(requestId, request.getRequestId()); - request.setActor("Dorothy"); - assertEquals("Dorothy", request.getActor()); + request.setActor(DOROTHY); + assertEquals(DOROTHY, request.getActor()); - request.setTarget("Kansas"); - assertEquals("Kansas", request.getTarget()); + request.setTarget(KANSAS); + assertEquals(KANSAS, request.getTarget()); - request.setOperation("GetBackHome"); - assertEquals("GetBackHome", request.getOperation()); + request.setOperation(GET_BACK_HOME); + assertEquals(GET_BACK_HOME, request.getOperation()); assertEquals("PolicyGuardRequest [actor=Dorothy", request.toString().substring(0, 33)); } diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardResponseTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardResponseTest.java index b30ae0210..14e7a3ad0 100644 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardResponseTest.java +++ b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardResponseTest.java @@ -31,22 +31,25 @@ import org.junit.Test; public class PolicyGuardResponseTest { + private static final String GET_BACK_HOME = "GetBackHome"; + private static final String BACK_HOME = "BackHome"; + @Test public void policyGuardResponseTest() { UUID requestId = UUID.randomUUID(); assertNotNull(new PolicyGuardResponse(null, null, null)); - PolicyGuardResponse response = new PolicyGuardResponse("BackHome", requestId, "GetBackHome"); + PolicyGuardResponse response = new PolicyGuardResponse(BACK_HOME, requestId, GET_BACK_HOME); response.setRequestId(requestId); assertEquals(requestId, response.getRequestId()); - response.setResult("BackHome"); - assertEquals("BackHome", response.getResult()); + response.setResult(BACK_HOME); + assertEquals(BACK_HOME, response.getResult()); - response.setOperation("GetBackHome"); - assertEquals("GetBackHome", response.getOperation()); + response.setOperation(GET_BACK_HOME); + assertEquals(GET_BACK_HOME, response.getOperation()); assertEquals("PolicyGuardResponse [requestId=", response.toString().substring(0, 31)); } diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardTest.java index 87303623c..5f77d0331 100644 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardTest.java +++ b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardTest.java @@ -46,9 +46,9 @@ import org.onap.policy.guard.impl.VnfTargetLock; public class PolicyGuardTest { private static final String INSTANCENAME = "targetInstance"; private static final int LOCK_SEC = 10; - + private static Factory saveFactory; - + private Factory factory; private PolicyResourceLockManager mgr; private UUID uuid; @@ -69,12 +69,12 @@ public class PolicyGuardTest { private class DummyTargetLock implements TargetLock { private TargetType type; private UUID reqid; - + public DummyTargetLock(TargetType type, UUID reqid) { this.type = type; this.reqid = reqid; } - + @Override public UUID getLockId() { return null; @@ -95,17 +95,17 @@ public class PolicyGuardTest { return reqid; } } - + @BeforeClass public static void setUpBeforeClass() { saveFactory = PolicyGuard.getFactory(); } - + @AfterClass public static void tearDownAfterClass() { PolicyGuard.setFactory(saveFactory); } - + /** * Setup method. */ @@ -117,10 +117,10 @@ public class PolicyGuardTest { * manager is protected; this gets around that */ }); - + factory = mock(Factory.class); when(factory.getManager()).thenReturn(mgr); - + uuid = UUID.randomUUID(); dlcb = new DummyLockCallback(); @@ -279,7 +279,7 @@ public class PolicyGuardTest { } @Test - public void testLockTargetTargetTypeStringUuidLockCallbackInt() throws Exception { + public void testLockTargetTargetTypeStringUuidLockCallbackInt() { TargetType type = TargetType.VM; LockResult<GuardResult, TargetLock> result; @@ -299,7 +299,7 @@ public class PolicyGuardTest { } @Test - public void testLockTargetTargetLockInt() throws Exception { + public void testLockTargetTargetLockInt() { TargetType type = TargetType.VM; LockResult<GuardResult, TargetLock> result; @@ -309,16 +309,16 @@ public class PolicyGuardTest { verify(mgr).lock(INSTANCENAME, type + ":" + uuid, LOCK_SEC); assertEquals(GuardResult.LOCK_ACQUIRED, result.getA()); assertEquals(VmTargetLock.class, result.getB().getClass()); - + TargetLock lock = result.getB(); - + // refresh - re-acquired assertEquals(GuardResult.LOCK_ACQUIRED, PolicyGuard.lockTarget(lock, LOCK_SEC + 1)); verify(mgr).refresh(INSTANCENAME, type + ":" + uuid, LOCK_SEC + 1); - + // unlock PolicyGuard.unlockTarget(lock); - + // refresh - denied, as we no longer own the lock assertEquals(GuardResult.LOCK_DENIED, PolicyGuard.lockTarget(lock, LOCK_SEC + 2)); } diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlHelperTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlHelperTest.java index 2418ac663..19fed30a0 100644 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlHelperTest.java +++ b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlHelperTest.java @@ -22,10 +22,8 @@ package org.onap.policy.guard; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; import java.util.Properties; - import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; @@ -35,21 +33,24 @@ import org.onap.policy.drools.utils.logging.LoggerUtil; public class PolicyGuardXacmlHelperTest { + private static final String TARGET = "target"; + private static final String REQUEST_ID = "requestId"; + private static final String RECIPE = "recipe"; + private static final String GUARD_URL = "guard.url"; + private static final String ACTOR = "actor"; private static final Integer VF_COUNT = 100; /** * Set up test class. */ @BeforeClass - public static void setupSimulator() { + public static void setupSimulator() throws Exception { LoggerUtil.setLevel("ROOT", "INFO"); LoggerUtil.setLevel("org.eclipse.jetty", "WARN"); - try { - HttpServletServer.factory.destroy(); - org.onap.policy.simulators.Util.buildGuardSim(); - } catch (Exception e) { - fail(e.getMessage()); - } + + HttpServletServer.factory.destroy(); + org.onap.policy.simulators.Util.buildGuardSim(); + // // Set guard properties // @@ -65,8 +66,8 @@ public class PolicyGuardXacmlHelperTest { // Null/ Bad Connection Case PolicyGuardXacmlRequestAttributes xacmlReq = new PolicyGuardXacmlRequestAttributes( - org.onap.policy.simulators.GuardSimulatorJaxRs.DENY_CLNAME, "actor", "recipe", "target", - "requestId", VF_COUNT); + org.onap.policy.simulators.GuardSimulatorJaxRs.DENY_CLNAME, ACTOR, RECIPE, TARGET, + REQUEST_ID, VF_COUNT); String rawDecision = new PolicyGuardXacmlHelper().callPdp(xacmlReq); assertNotNull(rawDecision); assertEquals(Util.DENY, rawDecision); @@ -88,14 +89,14 @@ public class PolicyGuardXacmlHelperTest { public void testCallPdp() { // Deny Case PolicyGuardXacmlRequestAttributes xacmlReq = new PolicyGuardXacmlRequestAttributes( - org.onap.policy.simulators.GuardSimulatorJaxRs.DENY_CLNAME, "actor", "recipe", "target", - "requestId", VF_COUNT); + org.onap.policy.simulators.GuardSimulatorJaxRs.DENY_CLNAME, ACTOR, RECIPE, TARGET, + REQUEST_ID, VF_COUNT); String rawDecision = new PolicyGuardXacmlHelper().callPdp(xacmlReq); assertNotNull(rawDecision); assertEquals(Util.DENY, rawDecision); // Permit Case - xacmlReq = new PolicyGuardXacmlRequestAttributes("clname", "actor", "recipe", "target", "requestId", VF_COUNT); + xacmlReq = new PolicyGuardXacmlRequestAttributes("clname", ACTOR, RECIPE, TARGET, REQUEST_ID, VF_COUNT); rawDecision = new PolicyGuardXacmlHelper().callPdp(xacmlReq); assertNotNull(rawDecision); assertEquals(Util.PERMIT, rawDecision); @@ -109,15 +110,15 @@ public class PolicyGuardXacmlHelperTest { assertNotNull(new PolicyGuardXacmlHelper()); - PolicyEngine.manager.getEnvironment().setProperty("guard.url", + PolicyEngine.manager.getEnvironment().setProperty(GUARD_URL, "http://localhost:6669/pdp/api/getDecision,Dorothy"); assertNotNull(new PolicyGuardXacmlHelper()); - PolicyEngine.manager.getEnvironment().setProperty("guard.url", + PolicyEngine.manager.getEnvironment().setProperty(GUARD_URL, "http://localhost:6669/pdp/api/getDecision,Dorothy,Toto"); assertNotNull(new PolicyGuardXacmlHelper()); - PolicyEngine.manager.getEnvironment().setProperty("guard.url", + PolicyEngine.manager.getEnvironment().setProperty(GUARD_URL, "http://localhost:6969/policy/pdpx/v1/decision"); PolicyEngine.manager.getEnvironment().setProperty("pdpx.timeout", "thisIsNotANumber"); @@ -132,7 +133,7 @@ public class PolicyGuardXacmlHelperTest { PolicyEngine.manager.getEnvironment().setProperty("pdpx.username", "python"); assertNotNull(new PolicyGuardXacmlHelper()); - PolicyEngine.manager.getEnvironment().setProperty("guard.url", "///"); + PolicyEngine.manager.getEnvironment().setProperty(GUARD_URL, "///"); assertNotNull(new PolicyGuardXacmlHelper()); PolicyEngine.manager.getEnvironment().setProperty("guard.disabled", ""); diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardYamlToXacmlTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardYamlToXacmlTest.java index a35696dec..75dc73c27 100644 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardYamlToXacmlTest.java +++ b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardYamlToXacmlTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * guard * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,6 +41,16 @@ import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; public class PolicyGuardYamlToXacmlTest { + private static final String SOME_START_TIME = "someStartTime"; + private static final String SOME_END_TIME = "someEndTime"; + private static final String HOURS = "hours"; + private static final String TARGET2 = "WickedWitchOfTheWest"; + private static final String TARGET1 = "Wizard"; + private static final String ONAPPF_FILE = "ONAPPF"; + private static final String RECIPE = "GoToOz"; + private static final String TEXT1 = "WestWitches"; + private static final String TEXT2 = "EastWitches"; + private static final String OUT_XACML = ".out.xacml"; private ControlLoopGuard clGuard; /** @@ -52,10 +62,10 @@ public class PolicyGuardYamlToXacmlTest { MatchParameters matchParameters = new MatchParameters(); matchParameters.setControlLoopName("WizardOfOz"); matchParameters.setActor("Dorothy"); - matchParameters.setRecipe("GoToOz"); + matchParameters.setRecipe(RECIPE); List<String> targets = new ArrayList<>(); - targets.add("Wizard"); - targets.add("WickedWitchOfTheWest"); + targets.add(TARGET1); + targets.add(TARGET2); matchParameters.setTargets(targets); GuardPolicy guardPolicy = new GuardPolicy(); guardPolicy.setMatch_parameters(matchParameters); @@ -63,11 +73,11 @@ public class PolicyGuardYamlToXacmlTest { limitConstraint.setFreq_limit_per_target(5); Map<String, String> timeWindow = new HashMap<>(); timeWindow.put("value", "10"); - timeWindow.put("units", "hours"); + timeWindow.put("units", HOURS); limitConstraint.setTime_window(timeWindow); Map<String, String> activeTimeRange = new HashMap<>(); - activeTimeRange.put("start", "someStartTime"); - activeTimeRange.put("end", "someEndTime"); + activeTimeRange.put("start", SOME_START_TIME); + activeTimeRange.put("end", SOME_END_TIME); limitConstraint.setActive_time_range(activeTimeRange); LinkedList<Constraint> limitConstraints = new LinkedList<>(); limitConstraints.add(limitConstraint); @@ -79,9 +89,13 @@ public class PolicyGuardYamlToXacmlTest { @Test public void testGenerateXacmlGuardFull() throws IOException { - File tempYamlFile = File.createTempFile("ONAPPF", "yaml"); + File tempYamlFile = File.createTempFile(ONAPPF_FILE, "yaml"); + tempYamlFile.deleteOnExit(); + File tempXacmlTemplateFile = new File("src/test/resources/frequency_limiter_template.xml"); - File tempXacmlOutputFile = File.createTempFile("ONAPPF", ".out.xacml"); + + File tempXacmlOutputFile = File.createTempFile(ONAPPF_FILE, OUT_XACML); + tempXacmlOutputFile.deleteOnExit(); Yaml clYaml = new Yaml(new Constructor(ControlLoopGuard.class)); String clYamlString = clYaml.dump(clGuard); @@ -98,23 +112,24 @@ public class PolicyGuardYamlToXacmlTest { // Assert all substitutions are made assertTrue(result.contains("cl")); assertTrue(result.contains("actor")); - assertTrue(result.contains("GoToOz")); - assertTrue(result.contains("Wizard")); - assertTrue(result.contains("WickedWitchOfTheWest")); + assertTrue(result.contains(RECIPE)); + assertTrue(result.contains(TARGET1)); + assertTrue(result.contains(TARGET2)); assertTrue(result.contains("10")); - assertTrue(result.contains("hours")); - assertTrue(result.contains("someStartTime")); - assertTrue(result.contains("someEndTime")); - - tempYamlFile.delete(); - tempXacmlOutputFile.delete(); + assertTrue(result.contains(HOURS)); + assertTrue(result.contains(SOME_START_TIME)); + assertTrue(result.contains(SOME_END_TIME)); } @Test public void testGenerateXacmlGuardPartial() throws IOException { - final File tempYamlFile = File.createTempFile("ONAPPF", "yaml"); + final File tempYamlFile = File.createTempFile(ONAPPF_FILE, "yaml"); + tempYamlFile.deleteOnExit(); + final File tempXacmlTemplateFile = new File("src/test/resources/frequency_limiter_template.xml"); - final File tempXacmlOutputFile = File.createTempFile("ONAPPF", ".out.xacml"); + + final File tempXacmlOutputFile = File.createTempFile(ONAPPF_FILE, OUT_XACML); + tempXacmlOutputFile.deleteOnExit(); MatchParameters matchParameters = clGuard.getGuards().get(0).getMatch_parameters(); matchParameters.setControlLoopName(null); @@ -137,16 +152,13 @@ public class PolicyGuardYamlToXacmlTest { // Assert all substitutions are made assertTrue(result.contains("cl")); assertTrue(result.contains("actor")); - assertFalse(result.contains("GoToOz")); - assertFalse(result.contains("Wizard")); - assertFalse(result.contains("WickedWitchOfTheWest")); + assertFalse(result.contains(RECIPE)); + assertFalse(result.contains(TARGET1)); + assertFalse(result.contains(TARGET2)); assertTrue(result.contains("10")); - assertTrue(result.contains("hours")); - assertTrue(result.contains("someStartTime")); - assertTrue(result.contains("someEndTime")); - - tempYamlFile.delete(); - tempXacmlOutputFile.delete(); + assertTrue(result.contains(HOURS)); + assertTrue(result.contains(SOME_START_TIME)); + assertTrue(result.contains(SOME_END_TIME)); } @Test @@ -173,13 +185,17 @@ public class PolicyGuardYamlToXacmlTest { @Test public void testGenerateXacmlGuardBlacklist() throws IOException { - final File tempYamlFile = File.createTempFile("ONAPPF", "yaml"); + final File tempYamlFile = File.createTempFile(ONAPPF_FILE, "yaml"); + tempYamlFile.deleteOnExit(); + final File tempXacmlTemplateFile = new File("src/test/resources/blacklist_template.xml"); - final File tempXacmlOutputFile = File.createTempFile("ONAPPF", ".out.xacml"); + + final File tempXacmlOutputFile = File.createTempFile(ONAPPF_FILE, OUT_XACML); + tempXacmlOutputFile.deleteOnExit(); List<String> blacklist = new ArrayList<>(); - blacklist.add("WestWitches"); - blacklist.add("EastWitches"); + blacklist.add(TEXT1); + blacklist.add(TEXT2); clGuard.getGuards().get(0).getLimit_constraints().get(0).setBlacklist(blacklist); Yaml clYaml = new Yaml(new Constructor(ControlLoopGuard.class)); @@ -190,27 +206,27 @@ public class PolicyGuardYamlToXacmlTest { tempXacmlTemplateFile.getCanonicalPath(), tempXacmlOutputFile.getCanonicalPath()); String result = SupportTextFileUtils.getTextFileAsString(tempXacmlOutputFile.getCanonicalPath()); - System.err.println(result); // Assert no mote "${}" are left assertFalse(result.contains("${")); assertFalse(result.contains("}")); // Assert all substitutions are made - assertTrue(result.contains("WestWitches")); - assertTrue(result.contains("EastWitches")); - - tempYamlFile.delete(); - tempXacmlOutputFile.delete(); + assertTrue(result.contains(TEXT1)); + assertTrue(result.contains(TEXT2)); } @Test public void testGenerateXacmlGuardBlacklistPartial() throws IOException { - final File tempYamlFile = File.createTempFile("ONAPPF", "yaml"); + final File tempYamlFile = File.createTempFile(ONAPPF_FILE, "yaml"); + tempYamlFile.deleteOnExit(); + final File tempXacmlTemplateFile = new File("src/test/resources/blacklist_template.xml"); - final File tempXacmlOutputFile = File.createTempFile("ONAPPF", ".out.xacml"); + + final File tempXacmlOutputFile = File.createTempFile(ONAPPF_FILE, OUT_XACML); + tempXacmlOutputFile.deleteOnExit(); List<String> blacklist = new ArrayList<>(); - blacklist.add("WestWitches"); - blacklist.add("EastWitches"); + blacklist.add(TEXT1); + blacklist.add(TEXT2); GuardPolicy guardPolicy = clGuard.getGuards().get(0); guardPolicy.getLimit_constraints().get(0).setBlacklist(blacklist); @@ -228,15 +244,11 @@ public class PolicyGuardYamlToXacmlTest { tempXacmlTemplateFile.getCanonicalPath(), tempXacmlOutputFile.getCanonicalPath()); String result = SupportTextFileUtils.getTextFileAsString(tempXacmlOutputFile.getCanonicalPath()); - System.err.println(result); // Assert no mote "${}" are left assertFalse(result.contains("${")); assertFalse(result.contains("}")); // Assert all substitutions are made - assertTrue(result.contains("WestWitches")); - assertTrue(result.contains("EastWitches")); - - tempYamlFile.delete(); - tempXacmlOutputFile.delete(); + assertTrue(result.contains(TEXT1)); + assertTrue(result.contains(TEXT2)); } } diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/SupportTextFileUtils.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/SupportTextFileUtils.java index 03260ada9..98c33c761 100644 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/SupportTextFileUtils.java +++ b/controlloop/common/guard/src/test/java/org/onap/policy/guard/SupportTextFileUtils.java @@ -3,6 +3,7 @@ * guard * ================================================================================ * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,9 +22,10 @@ package org.onap.policy.guard; import java.io.File; -import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; +import java.nio.charset.StandardCharsets; +import org.drools.core.util.IoUtils; /** * The Class TextFileUtils is class that provides useful functions for handling text files. @@ -31,7 +33,12 @@ import java.io.IOException; * * @author Liam Fallon (liam.fallon@ericsson.com) */ -public abstract class SupportTextFileUtils { +public class SupportTextFileUtils { + + private SupportTextFileUtils() { + // do nothing + } + /** * Method to return the contents of a text file as a string. * @@ -39,13 +46,8 @@ public abstract class SupportTextFileUtils { * @return A string containing the contents of the file * @throws IOException on errors reading text from the file */ - public static String getTextFileAsString(final String textFilePath) throws IOException { - final File textFile = new File(textFilePath); - final FileInputStream textFileInputStream = new FileInputStream(textFile); - final byte[] textData = new byte[(int) textFile.length()]; - textFileInputStream.read(textData); - textFileInputStream.close(); - return new String(textData); + public static String getTextFileAsString(final String textFilePath) { + return IoUtils.readFileAsString(new File(textFilePath)); } /** @@ -56,8 +58,8 @@ public abstract class SupportTextFileUtils { * @throws IOException on errors reading text from the file */ public static void putStringAsFile(final String outString, final File textFile) throws IOException { - final FileOutputStream textFileOutputStream = new FileOutputStream(textFile); - textFileOutputStream.write(outString.getBytes()); - textFileOutputStream.close(); + try (final FileOutputStream textFileOutputStream = new FileOutputStream(textFile)) { + textFileOutputStream.write(outString.getBytes(StandardCharsets.UTF_8)); + } } } |