diff options
author | Tej, Tarun <tt3868@att.com> | 2017-09-15 00:52:13 -0400 |
---|---|---|
committer | Tej, Tarun <tt3868@att.com> | 2017-09-15 01:37:52 -0400 |
commit | e0385921034ae9ce860038ea65d2d13259f7cc4c (patch) | |
tree | fa9461d587584fca27fc9a4a81614c91dcac6231 /PolicyEngineUtils | |
parent | e9e7bef3c130f7525a5ad250f365ee910bebe85a (diff) |
Adding Junits for policy engine
Adding Junits to Policy Engine Utils project, removed duplicates, fixed
few defects along the way and fixes to projects.
Issue-Id: POLICY-52
Change-Id: Ia0598300f9bd60f5372b9ef7d8984657478a1611
Signed-off-by: Tej, Tarun <tt3868@att.com>
Diffstat (limited to 'PolicyEngineUtils')
20 files changed, 1190 insertions, 341 deletions
diff --git a/PolicyEngineUtils/pom.xml b/PolicyEngineUtils/pom.xml index af2664305..c0837055f 100644 --- a/PolicyEngineUtils/pom.xml +++ b/PolicyEngineUtils/pom.xml @@ -30,12 +30,12 @@ <dependency> <groupId>org.onap.policy.common</groupId> <artifactId>integrity-monitor</artifactId> - <version>${common-modules.version}</version> + <version>${common-modules.version}</version> </dependency> <dependency> <groupId>org.onap.policy.common</groupId> <artifactId>integrity-audit</artifactId> - <version>${common-modules.version}</version> + <version>${common-modules.version}</version> </dependency> <dependency> <groupId>org.onap.policy.common</groupId> @@ -97,6 +97,12 @@ <groupId>org.drools</groupId> <artifactId>drools-verifier</artifactId> <version>6.3.0.Final</version> + <exclusions> + <exclusion> + <groupId>com.google.guava</groupId> + <artifactId>guava</artifactId> + </exclusion> + </exclusions> </dependency> <dependency> <groupId>com.att.cadi</groupId> @@ -104,20 +110,9 @@ <version>1.3.0</version> </dependency> <dependency> - <groupId>com.att.aft</groupId> - <artifactId>dme2</artifactId> - <version>3.1.200</version> - </dependency> - <dependency> - <groupId>com.att.nsa</groupId> - <artifactId>cambriaClient</artifactId> - <version>0.0.1</version> - <exclusions> - <exclusion> - <groupId>org.slf4j</groupId> - <artifactId>slf4j-log4j12</artifactId> - </exclusion> - </exclusions> + <groupId>com.att.aft</groupId> + <artifactId>dme2</artifactId> + <version>3.1.200</version> </dependency> <dependency> <groupId>com.att.nsa</groupId> diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/std/StdLoadedPolicy.java b/PolicyEngineUtils/src/main/java/org/onap/policy/std/StdLoadedPolicy.java index c1f4fed7f..10268f658 100644 --- a/PolicyEngineUtils/src/main/java/org/onap/policy/std/StdLoadedPolicy.java +++ b/PolicyEngineUtils/src/main/java/org/onap/policy/std/StdLoadedPolicy.java @@ -34,7 +34,7 @@ public class StdLoadedPolicy implements LoadedPolicy{ @Override public String getPolicyName() { if(policyName!=null && policyName.contains(".xml")){ - return (policyName.substring(0, policyName.substring(0, policyName.lastIndexOf(".")).lastIndexOf("."))); + return (policyName.substring(0, policyName.substring(0, policyName.lastIndexOf('.')).lastIndexOf('.'))); } return this.policyName; } diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/std/StdRemovedPolicy.java b/PolicyEngineUtils/src/main/java/org/onap/policy/std/StdRemovedPolicy.java index bdce33a3b..5430e24ef 100644 --- a/PolicyEngineUtils/src/main/java/org/onap/policy/std/StdRemovedPolicy.java +++ b/PolicyEngineUtils/src/main/java/org/onap/policy/std/StdRemovedPolicy.java @@ -38,7 +38,7 @@ public class StdRemovedPolicy implements RemovedPolicy{ @Override public String getPolicyName() { if(policyName!=null && policyName.contains(".xml")){ - return (policyName.substring(0, policyName.substring(0, policyName.lastIndexOf(".")).lastIndexOf("."))); + return (policyName.substring(0, policyName.substring(0, policyName.lastIndexOf('.')).lastIndexOf('.'))); } return this.policyName; } diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyClientImpl.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyClientImpl.java index 0f4876051..ecb51b286 100644 --- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyClientImpl.java +++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyClientImpl.java @@ -65,9 +65,6 @@ public class AAFPolicyClientImpl implements AAFPolicyClient{ private static Access access = null; private AAFPolicyClientImpl(Properties properties) throws AAFPolicyException{ - if(instance == null){ - instance = this; - } setup(properties); } @@ -93,7 +90,6 @@ public class AAFPolicyClientImpl implements AAFPolicyClient{ props.setProperty("AFT_LATITUDE", properties.getProperty("AFT_LATITUDE", DEFAULT_AFT_LATITUDE)); props.setProperty("AFT_LONGITUDE", properties.getProperty("AFT_LONGITUDE", DEFAULT_AFT_LONGITUDE)); String aftEnv = TEST_AFT_ENVIRONMENT; - //props.setProperty(Config.CADI_KEYFILE,"keyfile"); props.setProperty("aaf_id",properties.getProperty("aaf_id", "aafID")); props.setProperty("aaf_password", properties.getProperty("aaf_password", "aafPass")); if(properties.containsKey(Config.AAF_URL)){ @@ -203,8 +199,8 @@ public class AAFPolicyClientImpl implements AAFPolicyClient{ private static boolean setUpAAF(){ try { aafCon = new AAFConDME2(access); - aafLurPerm = aafCon.newLur();//new AAFLurPerm(aafCon); - aafAuthn = aafCon.newAuthn(aafLurPerm);//new AAFAuthn(aafCon, aafLurPerm); + aafLurPerm = aafCon.newLur(); + aafAuthn = aafCon.newAuthn(aafLurPerm); return true; } catch (Exception e) { logger.error("Error while setting up AAF Connection " + e.getMessage() + e); diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpMonitor.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpMonitor.java index d4f111637..3cdb51577 100644 --- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpMonitor.java +++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpMonitor.java @@ -53,8 +53,11 @@ import com.github.fge.jsonpatch.diff.JsonDiff; */ public class BackUpMonitor { private static final Logger LOGGER = Logger.getLogger(BackUpMonitor.class.getName()); - private static final int DEFAULT_PING = 15000; // Value is in milliseconds. - + private static final int DEFAULT_PING = 500; // Value is in milliseconds. + private static final String PING_INTERVAL = "ping_interval"; + private static final String MASTER = "MASTER"; + private static final String SLAVE = "SLAVE"; + private static BackUpMonitor instance = null; private static String resourceName = null; private static String resourceNodeName = null; @@ -65,6 +68,8 @@ public class BackUpMonitor { private static Object lock = new Object(); private static Object notificationLock = new Object(); private static BackUpHandler handler = null; + private static Boolean stopFlag = false; + private static Thread t = null; private EntityManager em; private EntityManagerFactory emf; @@ -77,14 +82,11 @@ public class BackUpMonitor { private BackUpMonitor(String resourceNodeName, String resourceName, Properties properties, BackUpHandler handler) throws BackUpMonitorException { - if (instance == null) { - instance = this; - } - BackUpMonitor.resourceNodeName = resourceNodeName; - BackUpMonitor.resourceName = resourceName; - BackUpMonitor.handler = handler; + init(resourceName, resourceNodeName, handler); // Create Persistence Entity - properties.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, "META-INF/persistencePU.xml"); + if(!properties.containsKey(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML)){ + properties.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, "META-INF/persistencePU.xml"); + } emf = Persistence.createEntityManagerFactory("PolicyEngineUtils", properties); if (emf == null) { LOGGER.error("Unable to create Entity Manger Factory "); @@ -94,12 +96,31 @@ public class BackUpMonitor { // Check Database if this is Master or Slave. checkDataBase(); - // Start thread. - Thread t = new Thread(new BMonitor()); + startThread(new BMonitor()); + } + + private static void startThread(BMonitor bMonitor) { + t = new Thread(bMonitor); t.start(); } + public static void stop() throws InterruptedException{ + stopFlag = true; + if(t!=null){ + t.interrupt(); + t.join(); + } + instance = null; + } + + private static void init(String resourceName, String resourceNodeName, BackUpHandler handler) { + BackUpMonitor.resourceNodeName = resourceNodeName; + BackUpMonitor.resourceName = resourceName; + BackUpMonitor.handler = handler; + stopFlag = false; + } + /** * Gets the BackUpMonitor Instance if given proper resourceName and properties. Else returns null. * @@ -142,17 +163,12 @@ public class BackUpMonitor { LOGGER.error("javax.persistence.jdbc.user property is empty"); return false; } - if (properties.getProperty("javax.persistence.jdbc.password") == null - || properties.getProperty("javax.persistence.jdbc.password").trim().equals("")) { - LOGGER.error("javax.persistence.jdbc.password property is empty"); - return false; - } - if (properties.getProperty("ping_interval") == null - || properties.getProperty("ping_interval").trim().equals("")) { + if (properties.getProperty(PING_INTERVAL) == null + || properties.getProperty(PING_INTERVAL).trim().equals("")) { LOGGER.info("ping_interval property not specified. Taking default value"); } else { try { - pingInterval = Integer.parseInt(properties.getProperty("ping_interval").trim()); + pingInterval = Integer.parseInt(properties.getProperty(PING_INTERVAL).trim()); } catch (NumberFormatException e) { LOGGER.warn("Ignored invalid proeprty ping_interval. Taking default value: " + pingInterval); pingInterval = DEFAULT_PING; @@ -185,7 +201,7 @@ public class BackUpMonitor { @Override public void run() { LOGGER.info("Starting BackUpMonitor Thread.. "); - while (true) { + while (!stopFlag) { try { TimeUnit.MILLISECONDS.sleep(pingInterval); checkDataBase(); @@ -198,26 +214,27 @@ public class BackUpMonitor { // Set Master private static BackUpMonitorEntity setMaster(BackUpMonitorEntity bMEntity) { - bMEntity.setFlag("MASTER"); + bMEntity.setFlag(MASTER); setFlag(true); return bMEntity; } // Set Slave private static BackUpMonitorEntity setSlave(BackUpMonitorEntity bMEntity) { - bMEntity.setFlag("SLAVE"); + bMEntity.setFlag(SLAVE); setFlag(false); return bMEntity; } // Check Database and set the Flag. private void checkDataBase() throws BackUpMonitorException { - EntityTransaction et = em.getTransaction(); - setNotificationRecord(); - // Clear Cache. - LOGGER.info("Clearing Cache"); - em.getEntityManagerFactory().getCache().evictAll(); + EntityTransaction et = null; try { + et = em.getTransaction(); + setNotificationRecord(); + // Clear Cache. + LOGGER.info("Clearing Cache"); + em.getEntityManagerFactory().getCache().evictAll(); LOGGER.info("Checking Datatbase for BackUpMonitor.. "); et.begin(); Query query = em.createQuery("select b from BackUpMonitorEntity b where b.resourceNodeName = :nn"); @@ -247,7 +264,7 @@ public class BackUpMonitor { BackUpMonitorEntity bMEntity = (BackUpMonitorEntity) bMList.get(i); LOGGER.info("Refreshing Entity. "); em.refresh(bMEntity); - if (bMEntity.getFlag().equalsIgnoreCase("MASTER")) { + if (bMEntity.getFlag().equalsIgnoreCase(MASTER)) { masterEntities.add(bMEntity); } if (bMEntity.getResourceName().equals(resourceName)) { @@ -256,7 +273,7 @@ public class BackUpMonitor { } if (selfEntity != null) { LOGGER.info("Resource Name already Exists: " + resourceName); - if (selfEntity.getFlag().equalsIgnoreCase("MASTER")) { + if (selfEntity.getFlag().equalsIgnoreCase(MASTER)) { // Already Master Mode. setFlag(true); LOGGER.info(resourceName + " is on Master Mode"); @@ -306,19 +323,19 @@ public class BackUpMonitor { // Slave. BackUpMonitorEntity masterEntity = null; for (BackUpMonitorEntity currentEntity : masterEntities) { - if (currentEntity.getFlag().equalsIgnoreCase("MASTER")) { + if (currentEntity.getFlag().equalsIgnoreCase(MASTER)) { if (masterEntity == null) { masterEntity = currentEntity; } else if (currentEntity.getTimeStamp().getTime() > masterEntity.getTimeStamp() .getTime()) { // False Master, Update master to slave and take currentMaster as Master. - masterEntity.setFlag("SLAVE"); + masterEntity.setFlag(SLAVE); masterEntity.setTimeStamp(new Date()); em.persist(masterEntity); em.flush(); masterEntity = currentEntity; } else { - currentEntity.setFlag("SLAVE"); + currentEntity.setFlag(SLAVE); currentEntity.setTimeStamp(new Date()); em.persist(currentEntity); em.flush(); @@ -339,7 +356,7 @@ public class BackUpMonitor { if (timeDiff > (pingInterval + 1500)) { // This is down or has an issue and we need to become Master while turning the // Master to slave. - masterEntity.setFlag("SLAVE"); + masterEntity.setFlag(SLAVE); String lastNotification = null; if (masterEntity.getNotificationRecord() != null) { lastNotification = calculatePatch(masterEntity.getNotificationRecord()); @@ -366,7 +383,7 @@ public class BackUpMonitor { et.commit(); } catch (Exception e) { LOGGER.error("failed Database Operation " + e.getMessage(), e); - if (et.isActive()) { + if (et!=null && et.isActive()) { et.rollback(); } throw new BackUpMonitorException(e); diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusConsumer.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusConsumer.java index 1b31394d0..2c867a3d1 100644 --- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusConsumer.java +++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusConsumer.java @@ -70,7 +70,7 @@ public interface BusConsumer { public DmaapConsumerWrapper(List<String> servers, String topic, String aafLogin, String aafPassword, String consumerGroup, String consumerInstance, - int fetchTimeout, int fetchLimit) throws MalformedURLException{ + int fetchTimeout, int fetchLimit) throws MalformedURLException{ this.consumer = new MRConsumerImpl(servers, topic, consumerGroup, consumerInstance, diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusPublisher.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusPublisher.java index 3190aa035..3a12122bf 100644 --- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusPublisher.java +++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusPublisher.java @@ -42,7 +42,7 @@ public interface BusPublisher { * @return true if success, false otherwise * @throws IllegalArgumentException if no message provided */ - public boolean send(String partitionId, String message) throws IllegalArgumentException; + public boolean send(String partitionId, String message); /** * closes the publisher @@ -114,8 +114,7 @@ public interface BusPublisher { * {@inheritDoc} */ @Override - public boolean send(String partitionId, String message) - throws IllegalArgumentException { + public boolean send(String partitionId, String message){ if (message == null) throw new IllegalArgumentException("No message provided"); diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PolicyUtils.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PolicyUtils.java index 8bc83dcb8..b74bd28cc 100644 --- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PolicyUtils.java +++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PolicyUtils.java @@ -26,96 +26,142 @@ import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.Base64; import java.util.List; +import java.util.Scanner; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; + import org.drools.core.io.impl.ReaderResource; import org.drools.verifier.Verifier; import org.drools.verifier.VerifierError; import org.drools.verifier.builder.VerifierBuilder; import org.drools.verifier.builder.VerifierBuilderFactory; import org.kie.api.io.ResourceType; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.xml.sax.InputSource; +import org.xml.sax.XMLReader; +import com.att.aft.dme2.internal.gson.JsonParser; +import com.att.aft.dme2.internal.gson.JsonSyntaxException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.CharMatcher; public class PolicyUtils { - - public static final String EMAIL_PATTERN = + private static final Logger LOGGER = FlexLogger.getLogger(PolicyUtils.class); + + public static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; - private static final String PACKAGE_ERROR = "mismatched input '{' expecting one of the following tokens: '[package"; - private static final String SUCCESS = "success"; - - private PolicyUtils(){ - // Private Constructor - } - public static String objectToJsonString(Object o) throws JsonProcessingException{ - ObjectMapper mapper = new ObjectMapper(); - return mapper.writeValueAsString(o); - } - - public static <T> T jsonStringToObject(String jsonString, Class<T> className) throws IOException{ - ObjectMapper mapper = new ObjectMapper(); - return mapper.readValue(jsonString, className); - } - - public static String decode(String encodedString) throws UnsupportedEncodingException { - if(encodedString!=null && !encodedString.isEmpty()){ - return new String(Base64.getDecoder().decode(encodedString) ,"UTF-8"); - }else{ - return null; - } - } - - public static String[] decodeBasicEncoding(String encodedValue) throws UnsupportedEncodingException { - if(encodedValue!=null && encodedValue.contains("Basic ")){ - String encodedUserPassword = encodedValue.replaceFirst("Basic" + " ", ""); - String usernameAndPassword = null; - byte[] decodedBytes = Base64.getDecoder().decode(encodedUserPassword); - usernameAndPassword = new String(decodedBytes, "UTF-8"); - StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":"); - String username = tokenizer.nextToken(); - String password = tokenizer.nextToken(); - return new String[]{username, password}; - }else{ - return new String[]{}; - } - } - - public static String emptyPolicyValidator(String field){ + private static final String PACKAGE_ERROR = "mismatched input '{' expecting one of the following tokens: '[package"; + private static final String SUCCESS = "success"; + + private PolicyUtils(){ + // Private Constructor + } + + /** + * Converts an Object to JSON String + * + * @param o Object + * @return String format of Object JSON. + * @throws JsonProcessingException + */ + public static String objectToJsonString(Object o) throws JsonProcessingException{ + ObjectMapper mapper = new ObjectMapper(); + return mapper.writeValueAsString(o); + } + + /** + * Converts JSON string into Object + * + * @param jsonString + * @param className equivalent Class of the given JSON string + * @return T instance of the class given. + * @throws IOException + */ + public static <T> T jsonStringToObject(String jsonString, Class<T> className) throws IOException{ + ObjectMapper mapper = new ObjectMapper(); + return mapper.readValue(jsonString, className); + } + + /** + * Decode a base64 string + * + * @param encodedString + * @return String + * @throws UnsupportedEncodingException + */ + public static String decode(String encodedString) throws UnsupportedEncodingException { + if(encodedString!=null && !encodedString.isEmpty()){ + return new String(Base64.getDecoder().decode(encodedString) ,"UTF-8"); + }else{ + return null; + } + } + + /** + * Decodes Basic Authentication + * + * @param encodedValue + * @return + * @throws UnsupportedEncodingException + */ + public static String[] decodeBasicEncoding(String encodedValue) throws UnsupportedEncodingException { + if(encodedValue!=null && encodedValue.contains("Basic ")){ + String encodedUserPassword = encodedValue.replaceFirst("Basic" + " ", ""); + String usernameAndPassword = null; + byte[] decodedBytes = Base64.getDecoder().decode(encodedUserPassword); + usernameAndPassword = new String(decodedBytes, "UTF-8"); + StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":"); + String username = tokenizer.nextToken(); + String password = tokenizer.nextToken(); + return new String[]{username, password}; + }else{ + return new String[]{}; + } + } + + /** + * Validate a field if contains space or unacceptable policy input and return "success" if good. + * + * @param field + * @return + */ + public static String policySpecialCharValidator(String field){ String error; if ("".equals(field) || field.contains(" ") || !field.matches("^[a-zA-Z0-9_]*$")) { error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations"; - return error; - } else { - if(CharMatcher.ASCII.matchesAllOf((CharSequence) field)){ - error = SUCCESS; - }else{ - error = "The Value Contains Non ASCII Characters"; - return error; - } + return error; } - return error; + return SUCCESS; } - public static String emptyPolicyValidatorWithSpaceAllowed(String field){ + /** + * Validate a field (accepts space) if it contains unacceptable policy input and return "success" if good. + * + * @param field + * @return + */ + public static String policySpecialCharWithSpaceValidator(String field){ String error; if ("".equals(field) || !field.matches("^[a-zA-Z0-9_ ]*$")) { error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations"; return error; - } else { - if(CharMatcher.ASCII.matchesAllOf((CharSequence) field)){ - error = SUCCESS; - }else{ - error = "The Value Contains Non ASCII Characters"; - return error; - } } - return error; + return SUCCESS; } + + /** + * Validate the XACML description tag and return "success" if good. + * + * @param field + * @return + */ public static String descriptionValidator(String field) { String error; if (field.contains("@CreatedBy:") || field.contains("@ModifiedBy:")) { @@ -127,15 +173,38 @@ public class PolicyUtils { return error; } + /** + * Validate if string contains non ASCII characters + * + * @param value + * @return + */ + public static boolean containsNonAsciiEmptyChars(String value) { + return (value == null|| value.contains(" ") || "".equals(value.trim())|| !CharMatcher.ASCII.matchesAllOf((CharSequence) value))? true:false; + } + + /** + * Validate if given string is an integer. + * + * @param number + * @return + */ public static Boolean isInteger(String number){ - try{ - Integer.parseInt(number); - }catch(NumberFormatException e){ - return false; - } - return true; + if(number==null) { + return false; + } + for (char c : number.toCharArray()){ + if (!Character.isDigit(c)) return false; + } + return true; } + /** + * Validate Email Address and return "success" if good. + * + * @param emailAddressValue + * @return + */ public static String validateEmailAddress(String emailAddressValue) { String error = SUCCESS; List<String> emailList = Arrays.asList(emailAddressValue.split(",")); @@ -152,8 +221,11 @@ public class PolicyUtils { return error; } - /* - * Check for "[ERR" to see if there are any errors. + /** + * Validates BRMS rule as per Policy Platform and return string contains "[ERR" if there are any errors. + * + * @param rule + * @return String error message */ public static String brmsRawValidate(String rule){ VerifierBuilder vBuilder = VerifierBuilderFactory.newVerifierBuilder(); @@ -161,19 +233,19 @@ public class PolicyUtils { verifier.addResourcesToVerify(new ReaderResource(new StringReader(rule)), ResourceType.DRL); // Check if there are any Errors in Verification. if(!verifier.getErrors().isEmpty()){ - boolean ignore = false; + boolean ignore = false; StringBuilder message = new StringBuilder("Not a Valid DRL rule"); for(VerifierError error: verifier.getErrors()){ // Ignore annotations Error Messages if(!error.getMessage().contains("'@'") && !error.getMessage().contains(PACKAGE_ERROR)){ - ignore= true; + ignore= true; message.append("\n" + error.getMessage()); } } - // Ignore new package names with { + // Ignore new package names with '{' // More checks for message to check if its a package error. if(ignore && !message.toString().contains("Parser returned a null Package")){ - message.append("[ERR 107]"); + message.append("[ERR 107]"); } return message.toString(); } @@ -181,21 +253,90 @@ public class PolicyUtils { } /** - * Given a version string consisting of integers with dots between them, convert it into an array of ints. - * - * @param version - * @return - * @throws NumberFormatException - */ - public static int[] versionStringToArray(String version) throws NumberFormatException { - if (version == null || version.length() == 0) { - return new int[0]; - } - String[] stringArray = version.split("\\."); - int[] resultArray = new int[stringArray.length]; - for (int i = 0; i < stringArray.length; i++) { - resultArray[i] = Integer.parseInt(stringArray[i]); - } - return resultArray; - } -} + * Validates if the given string is proper JSON format. + * + * @param data + * @return + */ + public static boolean isJSONValid(String data) { + try{ + JsonParser parser = new JsonParser(); + parser.parse(data); + }catch(JsonSyntaxException e){ + LOGGER.error("Exception Occurred While Validating"+e); + return false; + } + return true; + } + + /** + * Validates if the given string is proper XML format. + * + * @param data + * @return + */ + public static boolean isXMLValid(String data) { + SAXParserFactory factory = SAXParserFactory.newInstance(); + factory.setValidating(false); + factory.setNamespaceAware(true); + try { + SAXParser parser = factory.newSAXParser(); + XMLReader reader = parser.getXMLReader(); + reader.setErrorHandler(new XMLErrorHandler()); + reader.parse(new InputSource(new StringReader(data))); + } catch (Exception e) { + LOGGER.error("Exception Occured While Validating"+e); + return false; + } + return true; + } + + /** + * Validates if given string is valid Properties format. + * + * @param prop + * @return + */ + public static boolean isPropValid(String prop) { + Scanner scanner = new Scanner(prop); + while (scanner.hasNextLine()) { + String line = scanner.nextLine(); + line = line.replaceAll("\\s+", ""); + if (line.startsWith("#")) { + continue; + } else { + if (line.contains("=")) { + String[] parts = line.split("="); + if (parts.length < 2) { + scanner.close(); + return false; + } + } else if(!line.trim().isEmpty()){ + scanner.close(); + return false; + } + } + } + scanner.close(); + return true; + } + + /** + * Given a version string consisting of integers with dots between them, convert it into an array of integers. + * + * @param version + * @return + * @throws NumberFormatException + */ + public static int[] versionStringToArray(String version){ + if (version == null || version.length() == 0) { + return new int[0]; + } + String[] stringArray = version.split("\\."); + int[] resultArray = new int[stringArray.length]; + for (int i = 0; i < stringArray.length; i++) { + resultArray[i] = Integer.parseInt(stringArray[i].trim()); + } + return resultArray; + } +}
\ No newline at end of file diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/XMLErrorHandler.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/XMLErrorHandler.java new file mode 100644 index 000000000..3037a423c --- /dev/null +++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/XMLErrorHandler.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineUtils + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.utils; + +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.xml.sax.ErrorHandler; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; + +public class XMLErrorHandler implements ErrorHandler { + private static final Logger LOGGER = FlexLogger.getLogger(XMLErrorHandler.class); + + @Override + public void warning(SAXParseException exception) throws SAXException { + LOGGER.debug(exception); + } + + @Override + public void error(SAXParseException exception) throws SAXException { + LOGGER.error(exception); + } + + @Override + public void fatalError(SAXParseException exception) throws SAXException { + LOGGER.error(exception); + } + +} diff --git a/PolicyEngineUtils/src/test/java/org/onap/policy/test/PolicyUtilsTest.java b/PolicyEngineUtils/src/test/java/org/onap/policy/test/PolicyUtilsTest.java deleted file mode 100644 index 50ae3feae..000000000 --- a/PolicyEngineUtils/src/test/java/org/onap/policy/test/PolicyUtilsTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineUtils - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.test; - -import static org.junit.Assert.assertEquals; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -import org.junit.Test; -import org.onap.policy.api.NotificationType; -import org.onap.policy.api.PDPNotification; -import org.onap.policy.api.UpdateType; -import org.onap.policy.std.StdLoadedPolicy; -import org.onap.policy.std.StdPDPNotification; -import org.onap.policy.std.StdRemovedPolicy; -import org.onap.policy.utils.PolicyUtils; - -public class PolicyUtilsTest { - - @Test - public void testJsonConversions() throws Exception{ - StdPDPNotification notification = new StdPDPNotification(); - notification.setNotificationType(NotificationType.BOTH); - Collection<StdRemovedPolicy> removedPolicies = new ArrayList<>(); - Collection<StdLoadedPolicy> loadedPolicies = new ArrayList<>(); - StdRemovedPolicy removedPolicy = new StdRemovedPolicy(); - StdLoadedPolicy updatedPolicy = new StdLoadedPolicy(); - removedPolicy.setPolicyName("Test"); - removedPolicy.setVersionNo("1"); - removedPolicies.add(removedPolicy); - updatedPolicy.setPolicyName("Testing"); - updatedPolicy.setVersionNo("1"); - updatedPolicy.setUpdateType(UpdateType.NEW); - Map<String, String> matches = new HashMap<>(); - matches.put("key", "value"); - updatedPolicy.setMatches(matches); - loadedPolicies.add(updatedPolicy); - notification.setRemovedPolicies(removedPolicies); - notification.setLoadedPolicies(loadedPolicies); - - String json = PolicyUtils.objectToJsonString(notification); - PDPNotification getBackObject = PolicyUtils.jsonStringToObject(json, StdPDPNotification.class); - assertEquals(0,getBackObject.getNotificationType().compareTo(notification.getNotificationType())); - - } -} diff --git a/PolicyEngineUtils/src/test/java/org/onap/policy/test/testBackUpMonitor.java b/PolicyEngineUtils/src/test/java/org/onap/policy/test/testBackUpMonitor.java deleted file mode 100644 index 4cdb81873..000000000 --- a/PolicyEngineUtils/src/test/java/org/onap/policy/test/testBackUpMonitor.java +++ /dev/null @@ -1,121 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineUtils - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.test; - -import static org.junit.Assert.assertNull; -import java.util.Properties; - -import org.junit.Test; -import org.onap.policy.utils.BackUpMonitor; - - -public class testBackUpMonitor { - - @Test - public void backUpMonitorTestFail() throws Exception{ - Properties properties = new Properties(); - properties.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver"); - properties.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/xacml"); - properties.setProperty("javax.persistence.jdbc.user", "policy_user"); - properties.setProperty("javax.persistence.jdbc.password", ""); - //properties.setProperty("ping_interval", "500000"); - BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , properties, new Handler()); - assertNull(bum); - } - - @Test - public void backUpMonitorTestFailNoUser() throws Exception{ - Properties properties = new Properties(); - properties.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver"); - properties.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/xacml"); - properties.setProperty("javax.persistence.jdbc.user", ""); - properties.setProperty("javax.persistence.jdbc.password", "password"); - //properties.setProperty("ping_interval", "500000"); - BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , properties, new Handler()); - assertNull(bum); - } - - @Test - public void backUpMonitorTestFailNoURL() throws Exception{ - Properties properties = new Properties(); - properties.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver"); - properties.setProperty("javax.persistence.jdbc.url", ""); - properties.setProperty("javax.persistence.jdbc.user", "test"); - properties.setProperty("javax.persistence.jdbc.password", "password"); - //properties.setProperty("ping_interval", "500000"); - BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , properties, new Handler()); - assertNull(bum); - } - - @Test - public void backUpMonitorTestFailNoDriver() throws Exception{ - Properties properties = new Properties(); - properties.setProperty("javax.persistence.jdbc.driver", ""); - properties.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/xacml"); - properties.setProperty("javax.persistence.jdbc.user", "test"); - properties.setProperty("javax.persistence.jdbc.password", "password"); - //properties.setProperty("ping_interval", "500000"); - BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , properties, new Handler()); - assertNull(bum); - } - - @Test - public void backUpMonitorTestFailNoNode() throws Exception{ - Properties properties = new Properties(); - properties.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver"); - properties.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/xacml"); - properties.setProperty("javax.persistence.jdbc.user", "test"); - properties.setProperty("javax.persistence.jdbc.password", "password"); - //properties.setProperty("ping_interval", "500000"); - BackUpMonitor bum = BackUpMonitor.getInstance(null, "brms_test" , properties, new Handler()); - assertNull(bum); - } - - @Test - public void backUpMonitorTestFailNoResource() throws Exception{ - Properties properties = new Properties(); - properties.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver"); - properties.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/xacml"); - properties.setProperty("javax.persistence.jdbc.user", "test"); - properties.setProperty("javax.persistence.jdbc.password", "password"); - //properties.setProperty("ping_interval", "500000"); - BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), null , properties, new Handler()); - assertNull(bum); - } - - @Test - public void backUpMonitorTestFailNoProperties() throws Exception{ - BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , null, new Handler()); - assertNull(bum); - } - - @Test - public void backUpMonitorTestFailNoHandler() throws Exception{ - Properties properties = new Properties(); - properties.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver"); - properties.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/xacml"); - properties.setProperty("javax.persistence.jdbc.user", "test"); - properties.setProperty("javax.persistence.jdbc.password", "password"); - //properties.setProperty("ping_interval", "500000"); - BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , properties, null); - assertNull(bum); - } -} diff --git a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/AAFClientTest.java b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/AAFClientTest.java new file mode 100644 index 000000000..2fa822a33 --- /dev/null +++ b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/AAFClientTest.java @@ -0,0 +1,90 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineUtils + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.utils.test; + +import static org.junit.Assert.assertFalse; + +import java.util.Properties; + +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.utils.AAFPolicyClient; +import org.onap.policy.utils.AAFPolicyClientImpl; +import org.onap.policy.utils.AAFPolicyException; + +public class AAFClientTest { + AAFPolicyClient afClient; + String pass = "test"; + + @Before + public void setUp() throws AAFPolicyException{ + Properties props = new Properties(); + props.setProperty("ENVIRONMENT", "TEST"); + props.setProperty("aafClient.impl.className", AAFPolicyClientImpl.class.getName()); + afClient = AAFPolicyClient.getInstance(props); + } + + @Test + public void invalidClientTest() throws AAFPolicyException{ + assertFalse(afClient.checkAuth("test", pass)); + assertFalse(afClient.checkPerm("test", pass, "policy-engine.config", "*", "*")); + Properties props = new Properties(); + props.setProperty("aafClient.impl.className", AAFPolicyClientImpl.class.getName()); + afClient = AAFPolicyClient.getInstance(props); + assertFalse(afClient.checkAuth("test", pass)); + props.setProperty("ENVIRONMENT", "PROD"); + props.setProperty("aafClient.impl.className", AAFPolicyClientImpl.class.getName()); + afClient.updateProperties(props); + assertFalse(afClient.checkAuth("test", pass)); + props.setProperty("aaf_url", "test"); + afClient.updateProperties(props); + assertFalse(afClient.checkAuth("test", pass)); + props = new Properties(); + props.setProperty("ENVIRONMENT", "123"); + afClient.updateProperties(props); + assertFalse(afClient.checkAuth("test", pass)); + assertFalse(afClient.checkAuthPerm("test", pass, "decision", "*", "read")); + } + + @Test(expected = AAFPolicyException.class) + public void invalidAAFInstance() throws AAFPolicyException{ + Properties props = new Properties(); + props.setProperty("aafClient.impl.className", "errorClass"); + afClient = AAFPolicyClient.getInstance(props); + } + + @Test(expected = AAFPolicyException.class) + public void testPropNullException() throws AAFPolicyException { + afClient.updateProperties(null); + } + + @Test(expected = AAFPolicyException.class) + public void testPropEmptyException() throws AAFPolicyException { + afClient.updateProperties(new Properties()); + } + + @Test(expected = AAFPolicyException.class) + public void testAAFException() throws AAFPolicyException{ + new AAFPolicyException(); + new AAFPolicyException("error", new Exception()); + throw new AAFPolicyException("error", new Exception(), false, false); + } +} diff --git a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/BusTest.java b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/BusTest.java new file mode 100644 index 000000000..37170f077 --- /dev/null +++ b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/BusTest.java @@ -0,0 +1,57 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineUtils + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.utils.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.net.MalformedURLException; +import java.util.Arrays; + +import org.junit.Test; +import org.onap.policy.utils.BusConsumer; +import org.onap.policy.utils.BusPublisher; + +import com.att.nsa.mr.client.MRClient.MRApiException; + +public class BusTest { + + @Test + public void busPublisherTest(){ + BusPublisher bus = new BusPublisher.DmaapPublisherWrapper(Arrays.asList("test"), "test", "test", "test"); + assertTrue(bus.send("test123", "Hello World!")); + assertEquals("DmaapPublisherWrapper [publisher.getAuthDate()=null, publisher.getAuthKey()=null, publisher.getHost()=test, publisher.getProtocolFlag()=HTTPAAF, publisher.getUsername()=test, publisher.getPendingMessageCount()=1]",bus.toString()); + bus.close(); + } + + @Test (expected = MRApiException.class) + public void busConsumerFailTest() throws MalformedURLException, MRApiException{ + new BusConsumer.DmaapConsumerWrapper(Arrays.asList("test"), "test", "test", "test", "test", "test", 1, 1).fetch(); + } + + @Test + public void busConsumerTest() throws MalformedURLException, MRApiException{ + BusConsumer bus = new BusConsumer.DmaapConsumerWrapper(Arrays.asList("test"), "test", "test", "test", "test", "test", 1, 1); + assertEquals(bus.toString(),"DmaapConsumerWrapper [consumer.getAuthDate()=null, consumer.getAuthKey()=null, consumer.getHost()=test:3904, consumer.getProtocolFlag()=HTTPAAF, consumer.getUsername()=test]"); + bus.close(); + } + +} diff --git a/PolicyEngineUtils/src/test/java/org/onap/policy/test/Handler.java b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/Handler.java index 0f71858a3..91f467b60 100644 --- a/PolicyEngineUtils/src/test/java/org/onap/policy/test/Handler.java +++ b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/Handler.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.policy.test; +package org.onap.policy.utils.test; import org.onap.policy.api.PDPNotification; import org.onap.policy.utils.BackUpHandler; diff --git a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/NotificationStoreTest.java b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/NotificationStoreTest.java new file mode 100644 index 000000000..8ec646a0f --- /dev/null +++ b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/NotificationStoreTest.java @@ -0,0 +1,99 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineUtils + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.utils.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Test; +import org.onap.policy.api.NotificationType; +import org.onap.policy.api.UpdateType; +import org.onap.policy.std.NotificationStore; +import org.onap.policy.std.StdLoadedPolicy; +import org.onap.policy.std.StdPDPNotification; +import org.onap.policy.std.StdRemovedPolicy; + +public class NotificationStoreTest { + + @Test + public void notificationTest(){ + StdPDPNotification notification = new StdPDPNotification(); + notification.setNotificationType(NotificationType.UPDATE); + List<StdLoadedPolicy> loadedPolicies = new ArrayList<>(); + StdLoadedPolicy loadedPolicy = new StdLoadedPolicy(); + loadedPolicy.setPolicyName("com.testing"); + loadedPolicy.setUpdateType(UpdateType.NEW); + loadedPolicy.setVersionNo("1"); + Map<String, String> matches = new HashMap<>(); + matches.put("test", "test"); + loadedPolicy.setMatches(matches); + loadedPolicies.add(loadedPolicy); + notification.setLoadedPolicies(loadedPolicies); + NotificationStore.recordNotification(notification); + assertEquals(notification, NotificationStore.getNotificationRecord()); + // Add new Notifications. + notification = new StdPDPNotification(); + notification.setNotificationType(NotificationType.BOTH); + loadedPolicies = new ArrayList<>(); + loadedPolicy = new StdLoadedPolicy(); + loadedPolicy.setPolicyName("com.testing"); + loadedPolicy.setUpdateType(UpdateType.UPDATE); + loadedPolicy.setVersionNo("2"); + matches = new HashMap<>(); + matches.put("test", "test"); + loadedPolicy.setMatches(matches); + loadedPolicies.add(loadedPolicy); + notification.setLoadedPolicies(loadedPolicies); + List<StdRemovedPolicy> removedPolicies = new ArrayList<>(); + StdRemovedPolicy removedPolicy = new StdRemovedPolicy(); + removedPolicy.setPolicyName("com.testing"); + removedPolicy.setVersionNo("1"); + notification.setRemovedPolicies(removedPolicies); + NotificationStore.recordNotification(notification); + assertNotNull(NotificationStore.getNotificationRecord()); + // Add new Notifications. + notification = new StdPDPNotification(); + notification.setNotificationType(NotificationType.BOTH); + loadedPolicies = new ArrayList<>(); + loadedPolicy = new StdLoadedPolicy(); + loadedPolicy.setPolicyName("com.test.xml"); + loadedPolicy.setUpdateType(UpdateType.NEW); + loadedPolicy.setVersionNo("2"); + matches = new HashMap<>(); + matches.put("test", "test"); + loadedPolicy.setMatches(matches); + loadedPolicies.add(loadedPolicy); + notification.setLoadedPolicies(loadedPolicies); + removedPolicies = new ArrayList<>(); + removedPolicy = new StdRemovedPolicy(); + removedPolicy.setPolicyName("com.testing.xml"); + removedPolicy.setVersionNo("2"); + notification.setRemovedPolicies(removedPolicies); + NotificationStore.recordNotification(notification); + assertNotNull(NotificationStore.getNotificationRecord()); + } + +} diff --git a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/PEDependencyTest.java b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/PEDependencyTest.java new file mode 100644 index 000000000..4cc6c90f2 --- /dev/null +++ b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/PEDependencyTest.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineUtils + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.utils.test; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.maven.model.Exclusion; +import org.junit.Test; +import org.onap.policy.api.PEDependency; + +public class PEDependencyTest { + + @Test + public void pojoTests(){ + PEDependency pe = new PEDependency(); + pe.setArtifactId("test"); + pe.setGroupId("test"); + pe.setVersion("1"); + pe.setType("jar"); + pe.setScope("test"); + pe.setClassifier("pom"); + List<Exclusion> exclusions = new ArrayList<>(); + Exclusion e = new Exclusion(); + e.setArtifactId("ex1"); + e.setGroupId("eG"); + exclusions.add(e); + pe.setExclusions(exclusions); + pe.getDependency(); + assertEquals(exclusions, pe.getExclusions()); + assertEquals("pom", pe.getClassifier()); + assertEquals("test", pe.getScope()); + assertEquals("jar", pe.getType()); + assertEquals("1", pe.getVersion()); + assertEquals("test", pe.getGroupId()); + assertEquals("test", pe.getArtifactId()); + } + +} diff --git a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/PolicyUtilsTest.java b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/PolicyUtilsTest.java new file mode 100644 index 000000000..586ab356d --- /dev/null +++ b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/PolicyUtilsTest.java @@ -0,0 +1,209 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineUtils + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.utils.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.Base64; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.onap.policy.api.NotificationType; +import org.onap.policy.api.PDPNotification; +import org.onap.policy.api.UpdateType; +import org.onap.policy.std.StdLoadedPolicy; +import org.onap.policy.std.StdPDPNotification; +import org.onap.policy.std.StdRemovedPolicy; +import org.onap.policy.utils.PolicyUtils; +import org.onap.policy.utils.XMLErrorHandler; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; + +public class PolicyUtilsTest { + + private static final String ERROR = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations"; + private static final String SUCCESS = "success"; + + @Test + public void testJsonConversions() throws Exception{ + StdPDPNotification notification = new StdPDPNotification(); + notification.setNotificationType(NotificationType.BOTH); + Collection<StdRemovedPolicy> removedPolicies = new ArrayList<>(); + Collection<StdLoadedPolicy> loadedPolicies = new ArrayList<>(); + StdRemovedPolicy removedPolicy = new StdRemovedPolicy(); + StdLoadedPolicy updatedPolicy = new StdLoadedPolicy(); + removedPolicy.setPolicyName("Test"); + removedPolicy.setVersionNo("1"); + removedPolicies.add(removedPolicy); + updatedPolicy.setPolicyName("Testing"); + updatedPolicy.setVersionNo("1"); + updatedPolicy.setUpdateType(UpdateType.NEW); + Map<String, String> matches = new HashMap<>(); + matches.put("key", "value"); + updatedPolicy.setMatches(matches); + loadedPolicies.add(updatedPolicy); + notification.setRemovedPolicies(removedPolicies); + notification.setLoadedPolicies(loadedPolicies); + + String json = PolicyUtils.objectToJsonString(notification); + PDPNotification getBackObject = PolicyUtils.jsonStringToObject(json, StdPDPNotification.class); + assertEquals(0,getBackObject.getNotificationType().compareTo(notification.getNotificationType())); + + } + + private String encodedValue(String input){ + return new String(Base64.getEncoder().encode(input.getBytes())); + } + + @Test + public void testDecode() throws Exception{ + String value = "test"; + assertEquals(value, PolicyUtils.decode(encodedValue(value))); + assertNull(PolicyUtils.decode(null)); + assertNull(PolicyUtils.decode("")); + } + + @Test + public void testBasicEncoding() throws Exception{ + String userName = "test"; + String key = "pass"; + String[] decodedValue = PolicyUtils.decodeBasicEncoding("Basic "+encodedValue(userName+":"+key)); + assertEquals(userName,decodedValue[0]); + assertEquals(key,decodedValue[1]); + assertEquals(0, PolicyUtils.decodeBasicEncoding(encodedValue(userName+":"+key)).length); + assertEquals(0, PolicyUtils.decodeBasicEncoding(null).length); + } + + @Test + public void testSpecialCharValidator(){ + assertEquals(ERROR, PolicyUtils.policySpecialCharValidator("$TEST_")); + assertEquals(ERROR, PolicyUtils.policySpecialCharValidator("$TEST _")); + assertEquals(ERROR, PolicyUtils.policySpecialCharValidator("")); + assertEquals(ERROR, PolicyUtils.policySpecialCharValidator("TæST")); + assertEquals(SUCCESS, PolicyUtils.policySpecialCharValidator("TEST")); + } + + @Test + public void testSpecialCharWithSpaceValidator(){ + assertEquals(ERROR, PolicyUtils.policySpecialCharWithSpaceValidator("")); + assertEquals(ERROR, PolicyUtils.policySpecialCharWithSpaceValidator("$TEST _")); + assertEquals(SUCCESS, PolicyUtils.policySpecialCharWithSpaceValidator("TE ST")); + } + + @Test + public void testDescription() { + assertEquals(SUCCESS, PolicyUtils.descriptionValidator("Test")); + assertNotEquals(SUCCESS, PolicyUtils.descriptionValidator("@ModifiedBy:TesterB")); + assertNotEquals(SUCCESS, PolicyUtils.descriptionValidator("@CreatedBy:TesterA")); + } + + @Test + public void testNonAscii(){ + assertTrue(PolicyUtils.containsNonAsciiEmptyChars(null)); + assertTrue(PolicyUtils.containsNonAsciiEmptyChars("")); + assertTrue(PolicyUtils.containsNonAsciiEmptyChars("T æST")); + assertTrue(PolicyUtils.containsNonAsciiEmptyChars("TæST")); + assertFalse(PolicyUtils.containsNonAsciiEmptyChars("TEST")); + } + + @Test + public void testInteger(){ + assertFalse(PolicyUtils.isInteger(null)); + assertTrue(PolicyUtils.isInteger("123")); + assertFalse(PolicyUtils.isInteger("1a23")); + } + + @Test + public void testEmailAddress(){ + assertEquals(SUCCESS, PolicyUtils.validateEmailAddress("test@onap.org")); + assertNotEquals(SUCCESS, PolicyUtils.validateEmailAddress("test@onap")); + } + + @Test + public void testBRMSValidate(){ + String rule = "package com.sample;\n" + + "import com.sample.DroolsTest.Message;\n" + + "declare Params\n" + + "samPoll : int\n" + + "value : String\n" + + "end\n" + + "///This Rule will be generated by the UI.\n" + + "rule \"Create parameters structure\"\n" + + "salience 1000 \n" + + "when\n" + + "then\n" + + "Params params = new Params();\n" + + "params.setSamPoll(76);\n" + + "params.setValue(\"test\");\n" + + "insertLogical(params);\n" + + "end\n" + + "rule \"Rule 1: Check parameter structure access from when/then\"\n" + + "when\n" + + "$param: Params()\n" + + "Params($param.samPoll > 50)\n" + + "then\n" + + "System.out.println(\"Firing rule 1\");\n" + + "System.out.println($param);\n" + + "end\n"; + assertEquals(PolicyUtils.brmsRawValidate(rule),""); + assertTrue(PolicyUtils.brmsRawValidate("error").contains("[ERR")); + assertFalse(PolicyUtils.brmsRawValidate("package com.att.ecomp.policy.controlloop.p_${unique};").contains("[ERR")); + } + + @Test + public void testiIsJsonValid(){ + assertTrue(PolicyUtils.isJSONValid("{\"test\":\"test\"}")); + String value = "{\"test\":\"test\", \"t1\": {\"test\": 12 , \"t2\":\"34\"},\"t2\":[{\"test\":\"val\"}]}"; + assertTrue(PolicyUtils.isJSONValid(value)); + assertFalse(PolicyUtils.isJSONValid("{\"test\":\"test")); + } + + @Test + public void testIsXMLValid() throws SAXException{ + XMLErrorHandler error = new XMLErrorHandler(); + error.error(new SAXParseException(null, null)); + error.warning(new SAXParseException(null, null)); + assertTrue(PolicyUtils.isXMLValid("<test>123</test>")); + assertFalse(PolicyUtils.isXMLValid("<test>123</test")); + } + + @Test + public void testIsPropValid(){ + assertTrue(PolicyUtils.isPropValid("test=123\n\tval=123")); + assertFalse(PolicyUtils.isPropValid("test")); + assertFalse(PolicyUtils.isPropValid("test=")); + assertTrue(PolicyUtils.isPropValid("#test\n\nval=123")); + } + + @Test + public void testVersionStringToArray(){ + assertTrue(PolicyUtils.versionStringToArray(null).length==0); + assertTrue(PolicyUtils.versionStringToArray("").length==0); + assertTrue(PolicyUtils.versionStringToArray("1.2.3").length==3); + } +}
\ No newline at end of file diff --git a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/testBackUpMonitor.java b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/testBackUpMonitor.java new file mode 100644 index 000000000..afc3d0dce --- /dev/null +++ b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/testBackUpMonitor.java @@ -0,0 +1,292 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineUtils + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.utils.test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.TimeUnit; + +import javax.persistence.EntityManager; +import javax.persistence.EntityTransaction; +import javax.persistence.Persistence; +import javax.persistence.PersistenceException; +import javax.persistence.Query; + +import org.eclipse.persistence.config.PersistenceUnitProperties; +import org.junit.After; +import org.junit.Test; +import org.onap.policy.api.NotificationType; +import org.onap.policy.api.UpdateType; +import org.onap.policy.jpa.BackUpMonitorEntity; +import org.onap.policy.std.NotificationStore; +import org.onap.policy.std.StdLoadedPolicy; +import org.onap.policy.std.StdPDPNotification; +import org.onap.policy.std.StdRemovedPolicy; +import org.onap.policy.utils.BackUpMonitor; +import org.onap.policy.utils.BackUpMonitor.ResourceNode; +import org.onap.policy.utils.BackUpMonitorException; +import org.onap.policy.utils.PolicyUtils; + +import com.fasterxml.jackson.core.JsonProcessingException; + + +public class testBackUpMonitor { + + @Test (expected = PersistenceException.class) + public void backUpMonitorTestFail() throws Exception{ + Properties properties = new Properties(); + properties.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver"); + properties.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/xacml"); + properties.setProperty("javax.persistence.jdbc.user", "policy_user"); + properties.setProperty("javax.persistence.jdbc.password", ""); + BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , properties, new Handler()); + } + + @Test + public void backUpMonitorTestFailNoUser() throws Exception{ + Properties properties = new Properties(); + properties.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver"); + properties.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/xacml"); + properties.setProperty("javax.persistence.jdbc.user", ""); + properties.setProperty("javax.persistence.jdbc.password", "password"); + BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , properties, new Handler()); + assertNull(bum); + } + + @Test + public void backUpMonitorTestFailNoURL() throws Exception{ + Properties properties = new Properties(); + properties.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver"); + properties.setProperty("javax.persistence.jdbc.url", ""); + properties.setProperty("javax.persistence.jdbc.user", "test"); + properties.setProperty("javax.persistence.jdbc.password", "password"); + properties.setProperty("ping_interval", "500"); + BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , properties, new Handler()); + assertNull(bum); + } + + @Test + public void backUpMonitorTestFailNoDriver() throws Exception{ + Properties properties = new Properties(); + properties.setProperty("javax.persistence.jdbc.driver", ""); + properties.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/xacml"); + properties.setProperty("javax.persistence.jdbc.user", "test"); + properties.setProperty("javax.persistence.jdbc.password", "password"); + properties.setProperty("ping_interval", "500"); + BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , properties, new Handler()); + assertNull(bum); + } + + @Test + public void backUpMonitorTestFailNoNode() throws Exception{ + Properties properties = new Properties(); + properties.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver"); + properties.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/xacml"); + properties.setProperty("javax.persistence.jdbc.user", "test"); + properties.setProperty("javax.persistence.jdbc.password", "password"); + properties.setProperty("ping_interval", ""); + BackUpMonitor bum = BackUpMonitor.getInstance(null, "brms_test" , properties, new Handler()); + assertNull(bum); + } + + @Test + public void backUpMonitorTestFailNoResource() throws Exception{ + Properties properties = new Properties(); + properties.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver"); + properties.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/xacml"); + properties.setProperty("javax.persistence.jdbc.user", "test"); + properties.setProperty("javax.persistence.jdbc.password", "password"); + BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), null , properties, new Handler()); + assertNull(bum); + } + + @Test + public void backUpMonitorTestFailNoProperties() throws Exception{ + BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , null, new Handler()); + assertNull(bum); + } + + @Test + public void backUpMonitorTestFailNoHandler() throws Exception{ + Properties properties = new Properties(); + properties.setProperty("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver"); + properties.setProperty("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/xacml"); + properties.setProperty("javax.persistence.jdbc.user", "test"); + properties.setProperty("javax.persistence.jdbc.password", "password"); + properties.setProperty("ping_interval", "500"); + BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , properties, null); + assertNull(bum); + } + + @Test + public void backUpMonitorPingError() throws BackUpMonitorException { + Properties properties = new Properties(); + properties.setProperty("javax.persistence.jdbc.driver", "org.h2.Driver"); + properties.setProperty("javax.persistence.jdbc.url", "jdbc:h2:file:./sql/xacmlTest"); + properties.setProperty("javax.persistence.jdbc.user", "sa"); + properties.setProperty("javax.persistence.jdbc.password", ""); + properties.setProperty("ping_interval", "123a"); + properties.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, "META-INF/persistencePUtest.xml"); + BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , properties, new Handler()); + assertTrue(bum.getFlag()); + } + + @Test + public void backUpMonitorMasterTest() throws BackUpMonitorException, InterruptedException, JsonProcessingException { + Properties properties = new Properties(); + // Master Check. Initial Run. + properties.setProperty("javax.persistence.jdbc.driver", "org.h2.Driver"); + properties.setProperty("javax.persistence.jdbc.url", "jdbc:h2:file:./sql/xacmlTest"); + properties.setProperty("javax.persistence.jdbc.user", "sa"); + properties.setProperty("javax.persistence.jdbc.password", ""); + properties.setProperty("ping_interval", "500"); + properties.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, "META-INF/persistencePUtest.xml"); + BackUpMonitor bum = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), "brms_test" , properties, new Handler()); + createPolicyNotification(); + assertTrue(bum.getFlag()); + // Start a slave check. + startSlave(properties); + updatePolicyNotification(); + TimeUnit.MILLISECONDS.sleep(1500); + assertFalse(bum.getFlag()); + // Get Back to Master test + TimeUnit.MILLISECONDS.sleep(2000); + assertTrue(bum.getFlag()); + // No Master check. + changeALL(properties, "SLAVE"); + TimeUnit.MILLISECONDS.sleep(2000); + assertTrue(bum.getFlag()); + // No Master check. + changeALL(properties, "MASTER"); + TimeUnit.MILLISECONDS.sleep(2000); + assertTrue(bum.getFlag()); + + } + + private void updatePolicyNotification() { + StdPDPNotification notification = new StdPDPNotification(); + notification.setNotificationType(NotificationType.BOTH); + List<StdLoadedPolicy> loadedPolicies = new ArrayList<>(); + StdLoadedPolicy loadedPolicy = new StdLoadedPolicy(); + loadedPolicy.setPolicyName("com.testing"); + loadedPolicy.setUpdateType(UpdateType.UPDATE); + loadedPolicy.setVersionNo("2"); + Map<String, String> matches = new HashMap<>(); + matches.put("test", "test"); + loadedPolicy.setMatches(matches); + loadedPolicies.add(loadedPolicy); + notification.setLoadedPolicies(loadedPolicies); + List<StdRemovedPolicy> removedPolicies = new ArrayList<>(); + StdRemovedPolicy removedPolicy = new StdRemovedPolicy(); + removedPolicy.setPolicyName("com.testing"); + removedPolicy.setVersionNo("1"); + notification.setRemovedPolicies(removedPolicies); + NotificationStore.recordNotification(notification); + } + + private void createPolicyNotification() { + StdPDPNotification notification = new StdPDPNotification(); + notification.setNotificationType(NotificationType.UPDATE); + List<StdLoadedPolicy> loadedPolicies = new ArrayList<>(); + StdLoadedPolicy loadedPolicy = new StdLoadedPolicy(); + loadedPolicy.setPolicyName("com.testing"); + loadedPolicy.setUpdateType(UpdateType.NEW); + loadedPolicy.setVersionNo("1"); + Map<String, String> matches = new HashMap<>(); + matches.put("test", "test"); + loadedPolicy.setMatches(matches); + loadedPolicies.add(loadedPolicy); + notification.setLoadedPolicies(loadedPolicies); + NotificationStore.recordNotification(notification); + } + + private void changeALL(Properties properties, String flag) { + EntityManager em = Persistence.createEntityManagerFactory("PolicyEngineUtils", properties).createEntityManager(); + EntityTransaction et = em.getTransaction(); + et.begin(); + Query query = em.createQuery("select b from BackUpMonitorEntity b where b.resourceNodeName = :nn"); + query.setParameter("nn", ResourceNode.BRMS.toString()); + for(Object bMValue: query.getResultList()){ + BackUpMonitorEntity bmEntity = (BackUpMonitorEntity) bMValue; + bmEntity.setFlag(flag); + bmEntity.setTimeStamp(new Date()); + } + em.flush(); + et.commit(); + } + + private void startSlave(Properties properties) throws JsonProcessingException { + EntityManager em = Persistence.createEntityManagerFactory("PolicyEngineUtils", properties).createEntityManager(); + EntityTransaction et = em.getTransaction(); + et.begin(); + Query query = em.createQuery("select b from BackUpMonitorEntity b where b.resourceNodeName = :nn"); + query.setParameter("nn", ResourceNode.BRMS.toString()); + List<?> bMList = query.getResultList(); + BackUpMonitorEntity origBM = (BackUpMonitorEntity) bMList.get(0); + origBM.setFlag("SLAVE"); + origBM.setTimeStamp(new Date()); + BackUpMonitorEntity bMEntity = new BackUpMonitorEntity(); + bMEntity.setResoruceNodeName(ResourceNode.BRMS.toString()); + bMEntity.setResourceName("brms_test2"); + bMEntity.setFlag("MASTER"); + bMEntity.setTimeStamp(new Date()); + StdPDPNotification notification = new StdPDPNotification(); + notification.setNotificationType(NotificationType.UPDATE); + List<StdLoadedPolicy> loadedPolicies = new ArrayList<>(); + StdLoadedPolicy loadedPolicy = new StdLoadedPolicy(); + loadedPolicy.setPolicyName("com.test"); + loadedPolicy.setUpdateType(UpdateType.NEW); + loadedPolicy.setVersionNo("1"); + Map<String, String> matches = new HashMap<>(); + matches.put("test", "test"); + loadedPolicy.setMatches(matches); + loadedPolicies.add(loadedPolicy); + notification.setLoadedPolicies(loadedPolicies); + bMEntity.setNotificationRecord(PolicyUtils.objectToJsonString(notification)); + em.persist(bMEntity); + em.persist(origBM); + em.flush(); + et.commit(); + } + + @Test(expected = BackUpMonitorException.class) + public void testException() throws InterruptedException, BackUpMonitorException{ + BackUpMonitor.stop(); + new BackUpMonitorException(); + new BackUpMonitorException(new Exception()); + new BackUpMonitorException("error"); + new BackUpMonitorException("error", new Exception()); + throw new BackUpMonitorException("error", new Exception(), false, false); + } + + @After + public void setup() throws InterruptedException{ + BackUpMonitor.stop(); + } +} diff --git a/PolicyEngineUtils/src/test/resources/META-INF/drop.ddl b/PolicyEngineUtils/src/test/resources/META-INF/drop.ddl new file mode 100644 index 000000000..345f258b0 --- /dev/null +++ b/PolicyEngineUtils/src/test/resources/META-INF/drop.ddl @@ -0,0 +1 @@ +DROP TABLE IF EXISTS BackUpMonitorEntity
\ No newline at end of file diff --git a/PolicyEngineUtils/src/test/resources/META-INF/persistencePUtest.xml b/PolicyEngineUtils/src/test/resources/META-INF/persistencePUtest.xml new file mode 100644 index 000000000..a73e6b3c5 --- /dev/null +++ b/PolicyEngineUtils/src/test/resources/META-INF/persistencePUtest.xml @@ -0,0 +1,35 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- ============LICENSE_START======================================================= + PolicyEngineUtils ================================================================================ + Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. ================================================================================ + Licensed under the Apache License, Version 2.0 (the "License"); you may not + use this file except in compliance with the License. You may obtain a copy + of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required + by applicable law or agreed to in writing, software distributed under the + License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS + OF ANY KIND, either express or implied. See the License for the specific + language governing permissions and limitations under the License. ============LICENSE_END========================================================= --> + +<persistence version="2.1" + xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> + <persistence-unit name="PolicyEngineUtils" + transaction-type="RESOURCE_LOCAL"> + <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> + <class>org.onap.policy.jpa.BackUpMonitorEntity</class> + <property name="javax.persistence.schema-generation.scripts.action" + value="drop-and-create" /> + <property name="javax.persistence.schema-generation.scripts.create-target" + value="./src/test/resources/META-INF/generatedCreate.ddl" /> + <property name="javax.persistence.schema-generation.scripts.drop-target" + value="./src/test/resources/META-INF/generatedDrop.ddl" /> + <property name="javax.persistence.schema-generation.database.action" + value="drop-and-create" /> + <property name="javax.persistence.schema-generation.create-source" + value="metadata-then-script" /> + <property name="javax.persistence.schema-generation.drop-source" + value="script" /> + <property name="javax.persistence.schema-generation.drop-script-source" + value="META-INF/drop.ddl" /> + </persistence-unit> +</persistence> |