summaryrefslogtreecommitdiffstats
path: root/PolicyEngineUtils/src/main
diff options
context:
space:
mode:
authorTej, Tarun <tt3868@att.com>2017-09-15 00:52:13 -0400
committerTej, Tarun <tt3868@att.com>2017-09-15 01:37:52 -0400
commite0385921034ae9ce860038ea65d2d13259f7cc4c (patch)
treefa9461d587584fca27fc9a4a81614c91dcac6231 /PolicyEngineUtils/src/main
parente9e7bef3c130f7525a5ad250f365ee910bebe85a (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/src/main')
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/std/StdLoadedPolicy.java2
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/std/StdRemovedPolicy.java2
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyClientImpl.java8
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpMonitor.java85
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusConsumer.java2
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusPublisher.java5
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/utils/PolicyUtils.java321
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/utils/XMLErrorHandler.java47
8 files changed, 336 insertions, 136 deletions
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);
+ }
+
+}