aboutsummaryrefslogtreecommitdiffstats
path: root/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils
diff options
context:
space:
mode:
authorGuo Ruijing <ruijing.guo@intel.com>2017-07-31 08:47:35 +0000
committerPamela Dragosh <pdragosh@research.att.com>2017-07-31 15:51:10 -0400
commit073cc188efe9abb4c010cf674e34e2cf46ef1c52 (patch)
tree155c23fbdf3a838ecb5f4183fc3bb6b09aac41eb /PolicyEngineUtils/src/main/java/org/openecomp/policy/utils
parent4ca818fdfb9b807562166800a086b413593d6894 (diff)
[POLICY-73] replace openecomp for policy-engine
Change-Id: I54072f6bcd388c0e05562614ee89b4ae7ad67004 Signed-off-by: Guo Ruijing <ruijing.guo@intel.com> Signed-off-by: Pamela Dragosh <pdragosh@research.att.com>
Diffstat (limited to 'PolicyEngineUtils/src/main/java/org/openecomp/policy/utils')
-rw-r--r--PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/AAFEnvironment.java29
-rw-r--r--PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/AAFPolicyClient.java40
-rw-r--r--PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/AAFPolicyClientImpl.java214
-rw-r--r--PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/AAFPolicyException.java48
-rw-r--r--PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/BackUpHandler.java41
-rw-r--r--PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/BackUpMonitor.java422
-rw-r--r--PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/BusConsumer.java99
-rw-r--r--PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/BusPublisher.java119
-rw-r--r--PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/PolicyAccess.java106
-rw-r--r--PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/PolicyUtils.java201
10 files changed, 0 insertions, 1319 deletions
diff --git a/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/AAFEnvironment.java b/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/AAFEnvironment.java
deleted file mode 100644
index dd599cb85..000000000
--- a/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/AAFEnvironment.java
+++ /dev/null
@@ -1,29 +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.openecomp.policy.utils;
-
-public enum AAFEnvironment {
- /*
- * Enumeration for the Resource Node Naming. Add here if required.
- */
- DEVL,
- TEST,
- PROD
-}
diff --git a/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/AAFPolicyClient.java b/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/AAFPolicyClient.java
deleted file mode 100644
index 3955e944a..000000000
--- a/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/AAFPolicyClient.java
+++ /dev/null
@@ -1,40 +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.openecomp.policy.utils;
-
-import java.lang.reflect.Method;
-import java.util.Properties;
-
-public interface AAFPolicyClient {
-
- public boolean checkAuth(String userName, String pass);
- public void updateProperties(Properties properties) throws AAFPolicyException;
- public boolean checkAuthPerm(String mechID, String pass, String type, String instance, String action);
- public boolean checkPerm(String userName, String pass, String type, String instance, String action);
- public static AAFPolicyClient getInstance(Properties properties) throws AAFPolicyException{
- try {
- Class<?> aafPolicyClient = Class.forName(properties.getProperty("aafClient.impl.className", AAFPolicyClientImpl.class.getName()));
- Method method = aafPolicyClient.getMethod("getInstance", Properties.class);
- return (AAFPolicyClient) method.invoke(null, properties);
- } catch (Exception e) {
- throw new AAFPolicyException(e);
- }
- }
-}
diff --git a/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/AAFPolicyClientImpl.java b/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/AAFPolicyClientImpl.java
deleted file mode 100644
index a1c489922..000000000
--- a/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/AAFPolicyClientImpl.java
+++ /dev/null
@@ -1,214 +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.openecomp.policy.utils;
-
-import java.util.Properties;
-
-import org.apache.log4j.Logger;
-
-import com.att.cadi.Access;
-import com.att.cadi.Access.Level;
-import com.att.cadi.CadiException;
-import com.att.cadi.aaf.AAFPermission;
-import com.att.cadi.aaf.v2_0.AAFAuthn;
-import com.att.cadi.aaf.v2_0.AAFCon;
-import com.att.cadi.aaf.v2_0.AAFConDME2;
-import com.att.cadi.aaf.v2_0.AAFLurPerm;
-import com.att.cadi.config.Config;
-
-
-/**
- * AAF Client: Generic AAF Client implementation to connect to AAF Resources to validate permissions and authorization.
- *
- */
-public class AAFPolicyClientImpl implements AAFPolicyClient{
- private static Logger logger = Logger.getLogger(AAFPolicyClientImpl.class.getName());
-
- private static final String ENVIRONMENT = "ENVIRONMENT";
-
- // Warning Please don't Change these Values. Confirm with AAF team.
- private static final String DEVL_AAF_URL = "";
- private static final String TEST_AAF_URL = "";
- private static final String PROD_AAF_URL = "";
- private static final String DEFAULT_AFT_LATITUDE = "32.780140";
- private static final String DEFAULT_AFT_LONGITUDE = "-96.800451";
- private static final String TEST_AFT_ENVIRONMENT = "AFTUAT";
- private static final String PROD_AFT_ENVIRONMENT = "AFTPRD";
- private static final String DEFAULT_AAF_USER_EXPIRES = Integer.toString(5*60000); // 5 minutes for found items to live in cache
- private static final String DEFAULT_AAF_HIGH_COUNT = Integer.toString(400); // Maximum number of items in Cache
-
- private static AAFPolicyClientImpl instance = null;
-
- private static Properties props = new Properties();
- private static AAFCon<?> aafCon = null;
- private static AAFLurPerm aafLurPerm = null;
- private static AAFAuthn<?> aafAuthn = null;
- private static Access access = null;
-
- private AAFPolicyClientImpl(Properties properties) throws AAFPolicyException{
- if(instance == null){
- instance = this;
- }
- setup(properties);
- }
-
- /**
- * Gets the instance of the AAFClient instance. Needs Proper properties with CLIENT_ID, CLIENT_KEY and ENVIRONMENT
- *
- * @param properties Properties with CLIENT_ID, CLIENT_KEY and ENVIRONMENT
- * @return AAFClient instance.
- * @throws AAFPolicyException Exceptions.
- */
- public static synchronized AAFPolicyClientImpl getInstance(Properties properties) throws AAFPolicyException{
- if(instance == null) {
- logger.info("Creating AAFClient Instance ");
- instance = new AAFPolicyClientImpl(properties);
- }
- return instance;
- }
-
- // To set Property values && Connections.
- private static void setup(Properties properties) throws AAFPolicyException {
- if(properties!=null && !properties.isEmpty()){
- props = System.getProperties();
- 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)){
- // if given a value in properties file.
- props.setProperty(Config.AAF_URL, properties.getProperty(Config.AAF_URL));
- }else{
- // Set Default values.
- if(properties.getProperty(ENVIRONMENT, "DEVL").equalsIgnoreCase(AAFEnvironment.TEST.toString())){
- props.setProperty(Config.AAF_URL, TEST_AAF_URL);
- }else if(properties.getProperty(ENVIRONMENT, "DEVL").equalsIgnoreCase(AAFEnvironment.PROD.toString())){
- props.setProperty(Config.AAF_URL, PROD_AAF_URL);
- aftEnv = PROD_AFT_ENVIRONMENT;
- }else{
- props.setProperty(Config.AAF_URL, DEVL_AAF_URL);
- }
- }
- props.setProperty("AFT_ENVIRONMENT", properties.getProperty("AFT_ENVIRONMENT", aftEnv));
- props.setProperty(Config.AAF_USER_EXPIRES, properties.getProperty(Config.AAF_USER_EXPIRES, DEFAULT_AAF_USER_EXPIRES));
- props.setProperty(Config.AAF_HIGH_COUNT, properties.getProperty(Config.AAF_HIGH_COUNT, DEFAULT_AAF_HIGH_COUNT));
- }else{
- logger.error("Required Property value is missing : " + ENVIRONMENT);
- throw new AAFPolicyException("Required Property value is missing : " + ENVIRONMENT);
- }
- access = new PolicyAccess(props, Level.valueOf(properties.getProperty("AAF_LOG_LEVEL", Level.ERROR.toString())));
- setUpAAF();
- }
-
- /**
- * Updates the Properties file in case if required.
- *
- * @param properties Properties with CLIENT_ID, CLIENT_KEY and ENVIRONMENT
- * @throws AAFPolicyException exceptions if any.
- */
- public void updateProperties(Properties properties) throws AAFPolicyException{
- setup(properties);
- }
-
- /**
- * Checks the Authentication and Permissions for the given values.
- *
- * @param mechID MechID or ATT ID must be registered under the Name space.
- * @param pass Password pertaining to the MechID or ATTID.
- * @param type Permissions Type.
- * @param instance Permissions Instance.
- * @param action Permissions Action.
- * @return
- */
- public boolean checkAuthPerm(String mechID, String pass, String type, String instance, String action){
- return checkAuth(mechID, pass) && checkPerm(mechID, pass, type, instance, action);
- }
-
- /**
- * Checks the Authentication of the UserName and Password Given.
- *
- * @param userName UserName or MechID
- * @param pass Password.
- * @return True or False.
- */
- public boolean checkAuth(String userName, String pass){
- if(aafAuthn!=null){
- try {
- int i=0;
- do{
- if(aafAuthn.validate(userName, pass)==null){
- return true;
- }
- i++;
- }while(i<2);
- } catch (Exception e) {
- logger.error(e.getMessage() + e);
- }
- }
- logger.info("Authentication failed for : " + userName + " in " + props.getProperty(Config.AAF_URL));
- return false;
- }
-
- /**
- * Checks Permissions for the given UserName, Password and Type, Instance Action.
- *
- * @param userName UserName or MechID
- * @param pass Password.
- * @param type Permissions Type.
- * @param instance Permissions Instance.
- * @param action Permissions Action.
- * @return True or False.
- */
- public boolean checkPerm(String userName, String pass, String type, String instance, String action){
- int i =0;
- Boolean result= false;
- do{
- if(aafCon!=null && aafLurPerm !=null){
- try {
- aafCon.basicAuth(userName, pass);
- AAFPermission perm = new AAFPermission(type, instance, action);
- result = aafLurPerm.fish(userName, perm);
- } catch (CadiException e) {
- logger.error(e.getMessage() + e);
- aafLurPerm.destroy();
- }
- }
- logger.info("Permissions for : " + userName + " in " + props.getProperty(Config.AAF_URL) + " for " + type + "," + instance + "," + action + "\n Result is: " + result);
- i++;
- }while(i<2 && !result); // Try once more to check if this can be passed. AAF has some issues.
- return result;
- }
-
- private static boolean setUpAAF(){
- try {
- aafCon = new AAFConDME2(access);
- aafLurPerm = aafCon.newLur();//new AAFLurPerm(aafCon);
- aafAuthn = aafCon.newAuthn(aafLurPerm);//new AAFAuthn(aafCon, aafLurPerm);
- return true;
- } catch (Exception e) {
- logger.error("Error while setting up AAF Connection " + e.getMessage() + e);
- return false;
- }
- }
-}
diff --git a/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/AAFPolicyException.java b/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/AAFPolicyException.java
deleted file mode 100644
index a798b6e53..000000000
--- a/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/AAFPolicyException.java
+++ /dev/null
@@ -1,48 +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.openecomp.policy.utils;
-
-/**
- * AAFPolicyException to show exception messages.
- *
- */
-public class AAFPolicyException extends Exception {
- private static final long serialVersionUID = 1910606668038621L;
-
- public AAFPolicyException() {
- }
-
- public AAFPolicyException(String message) {
- super(message);
- }
-
- public AAFPolicyException(Throwable cause){
- super(cause);
- }
-
- public AAFPolicyException(String message, Throwable cause) {
- super(message, cause);
- }
-
- public AAFPolicyException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
- super(message, cause, enableSuppression, writableStackTrace);
- }
-}
diff --git a/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/BackUpHandler.java b/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/BackUpHandler.java
deleted file mode 100644
index 227d0ceff..000000000
--- a/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/BackUpHandler.java
+++ /dev/null
@@ -1,41 +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.openecomp.policy.utils;
-
-import org.openecomp.policy.api.NotificationHandler;
-import org.openecomp.policy.api.PDPNotification;
-
-public interface BackUpHandler extends NotificationHandler{
-
- /**
- * <code>notificationReceived</code> method will be triggered automatically whenever a Notification is received by the PEP.
- *
- * @param notification <code>PDPNotification</code> of {@link org.openecomp.policy.api.PDPNotification} is the object that has information of the notification.
- */
- public void notificationReceived(PDPNotification notification);
-
- /**
- * <code>runOnNotification</code> method will be triggered automatically whenever a Notification is received by the PEP This needs to be the main implementation.
- *
- * @param notification <code>PDPNotification</code> of {@link org.openecomp.policy.api.PDPNotification} is the object that has information of the notification.
- */
- public void runOnNotification(PDPNotification notification);
-}
diff --git a/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/BackUpMonitor.java b/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/BackUpMonitor.java
deleted file mode 100644
index 6f9082bc9..000000000
--- a/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/BackUpMonitor.java
+++ /dev/null
@@ -1,422 +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.openecomp.policy.utils;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-import java.util.Properties;
-import java.util.concurrent.TimeUnit;
-
-import javax.persistence.EntityManager;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.EntityTransaction;
-import javax.persistence.Persistence;
-import javax.persistence.Query;
-
-import org.apache.log4j.Logger;
-import org.eclipse.persistence.config.PersistenceUnitProperties;
-import org.openecomp.policy.api.PDPNotification;
-import org.openecomp.policy.jpa.BackUpMonitorEntity;
-import org.openecomp.policy.std.NotificationStore;
-import org.openecomp.policy.std.StdPDPNotification;
-
-import com.fasterxml.jackson.databind.JsonNode;
-import com.github.fge.jackson.JsonLoader;
-import com.github.fge.jsonpatch.JsonPatch;
-import com.github.fge.jsonpatch.JsonPatchException;
-import com.github.fge.jsonpatch.diff.JsonDiff;
-
-/**
- * BackUp Monitor checks Backup Status with the Database and maintains Redundancy for Gateway Applications.
- *
- */
-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 BackUpMonitor instance = null;
- private static String resourceName = null;
- private static String resourceNodeName = null;
- private static String notificationRecord = null;
- private static String lastMasterNotification= null;
- private static int pingInterval = DEFAULT_PING;
- private static Boolean masterFlag = false;
- private static Object lock = new Object();
- private static Object notificationLock = new Object();
- private static BackUpHandler handler= null;
- private EntityManager em;
- private EntityManagerFactory emf;
-
- /*
- * Enumeration for the Resource Node Naming. Add here if required.
- */
- public enum ResourceNode{
- BRMS,
- ASTRA
- }
-
- private BackUpMonitor(String resourceNodeName, String resourceName, Properties properties, BackUpHandler handler) throws Exception{
- if(instance == null){
- instance = this;
- }
- BackUpMonitor.resourceNodeName = resourceNodeName;
- BackUpMonitor.resourceName = resourceName;
- BackUpMonitor.handler = handler;
- // Create Persistence Entity
- 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 ");
- throw new Exception("Unable to create Entity Manger Factory");
- }
- em = emf.createEntityManager();
-
- // Check Database if this is Master or Slave.
- checkDataBase();
-
- // Start thread.
- Thread t = new Thread(new BMonitor());
- t.start();
- }
-
- /**
- * Gets the BackUpMonitor Instance if given proper resourceName and properties. Else returns null.
- *
- * @param resourceNodeName String format of the Resource Node to which the resource Belongs to.
- * @param resourceName String format of the ResourceName. This needs to be Unique.
- * @param properties Properties format of the properties file.
- * @return BackUpMonitor instance.
- */
- public static synchronized BackUpMonitor getInstance(String resourceNodeName, String resourceName, Properties properties, BackUpHandler handler) throws Exception {
- if(resourceNodeName==null || resourceNodeName.trim().equals("") ||resourceName==null|| resourceName.trim().equals("") || properties == null || handler==null){
- LOGGER.error("Error while getting Instance. Please check resourceName and/or properties file");
- return null;
- }else if((resourceNodeName.equals(ResourceNode.ASTRA.toString()) || resourceNodeName.equals(ResourceNode.BRMS.toString())) && validate(properties) && instance==null){
- LOGGER.info("Creating Instance of BackUpMonitor");
- instance = new BackUpMonitor(resourceNodeName, resourceName, properties, handler);
- }
- return instance;
- }
-
- // This is to validate given Properties with required values.
- private static Boolean validate(Properties properties){
- if(properties.getProperty("javax.persistence.jdbc.driver")==null ||properties.getProperty("javax.persistence.jdbc.driver").trim().equals("")){
- LOGGER.error("javax.persistence.jdbc.driver property is empty");
- return false;
- }
- if(properties.getProperty("javax.persistence.jdbc.url")==null || properties.getProperty("javax.persistence.jdbc.url").trim().equals("")){
- LOGGER.error("javax.persistence.jdbc.url property is empty");
- return false;
- }
- if(properties.getProperty("javax.persistence.jdbc.user")==null || properties.getProperty("javax.persistence.jdbc.user").trim().equals("")){
- 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("")){
- LOGGER.info("ping_interval property not specified. Taking default value");
- }else{
- try{
- 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;
- }
- }
- return true;
- }
-
- // Sets the Flag for masterFlag to either True or False.
- private static void setFlag(Boolean flag){
- synchronized (lock) {
- masterFlag = flag;
- }
- }
-
- /**
- * Gets the Boolean value of Master(True) or Slave mode (False)
- *
- * @return Boolean flag which if True means that the operation needs to be performed(Master mode) or if false the operation is in slave mode.
- */
- public Boolean getFlag(){
- synchronized (lock) {
- return masterFlag;
- }
- }
-
- // BackUpMonitor Thread
- private class BMonitor implements Runnable{
- @Override
- public void run() {
- LOGGER.info("Starting BackUpMonitor Thread.. ");
- while(true){
- try {
- TimeUnit.MILLISECONDS.sleep(pingInterval);
- checkDataBase();
- } catch (Exception e) {
- LOGGER.error("Error during Thread execution " + e.getMessage());
- }
- }
- }
- }
-
- // Set Master
- private static BackUpMonitorEntity setMaster(BackUpMonitorEntity bMEntity){
- bMEntity.setFlag("MASTER");
- setFlag(true);
- return bMEntity;
- }
-
- // Set Slave
- private static BackUpMonitorEntity setSlave(BackUpMonitorEntity bMEntity){
- bMEntity.setFlag("SLAVE");
- setFlag(false);
- return bMEntity;
- }
-
- // Check Database and set the Flag.
- private void checkDataBase() throws Exception {
- EntityTransaction et = em.getTransaction();
- notificationRecord = PolicyUtils.objectToJsonString(NotificationStore.getNotificationRecord());
- // Clear Cache.
- LOGGER.info("Clearing Cache");
- em.getEntityManagerFactory().getCache().evictAll();
- try{
- LOGGER.info("Checking Datatbase for BackUpMonitor.. ");
- et.begin();
- Query query = em.createQuery("select b from BackUpMonitorEntity b where b.resourceNodeName = :nn");
- if(resourceNodeName.equals(ResourceNode.ASTRA.toString())){
- query.setParameter("nn", ResourceNode.ASTRA.toString());
- }else if(resourceNodeName.equals(ResourceNode.BRMS.toString())){
- query.setParameter("nn", ResourceNode.BRMS.toString());
- }
- List<?> bMList = query.getResultList();
- if(bMList.isEmpty()){
- // This is New. create an entry as Master.
- LOGGER.info("Adding resource " + resourceName + " to Database");
- BackUpMonitorEntity bMEntity = new BackUpMonitorEntity();
- bMEntity.setResoruceNodeName(resourceNodeName);
- bMEntity.setResourceName(resourceName);
- bMEntity = setMaster(bMEntity);
- bMEntity.setTimeStamp(new Date());
- em.persist(bMEntity);
- em.flush();
- }else{
- // Check for other Master(s)
- ArrayList<BackUpMonitorEntity> masterEntities = new ArrayList<>();
- // Check for self.
- BackUpMonitorEntity selfEntity = null;
- // Check backup monitor entities.
- for(int i=0; i< bMList.size(); i++){
- BackUpMonitorEntity bMEntity = (BackUpMonitorEntity) bMList.get(i);
- LOGGER.info("Refreshing Entity. ");
- em.refresh(bMEntity);
- if(bMEntity.getFlag().equalsIgnoreCase("MASTER")){
- masterEntities.add(bMEntity);
- }
- if(bMEntity.getResourceName().equals(resourceName)){
- selfEntity = bMEntity;
- }
- }
- if(selfEntity!=null){
- LOGGER.info("Resource Name already Exists: " + resourceName);
- if(selfEntity.getFlag().equalsIgnoreCase("MASTER")){
- // Already Master Mode.
- setFlag(true);
- LOGGER.info(resourceName + " is on Master Mode");
- selfEntity.setTimeStamp(new Date());
- selfEntity.setNotificationRecord(notificationRecord);
- em.persist(selfEntity);
- em.flush();
- setLastNotification(null);
- if(!masterEntities.contains(selfEntity)){
- masterEntities.add(selfEntity);
- }
- }else{
- // Already Slave Mode.
- setFlag(false);
- selfEntity.setTimeStamp(new Date());
- selfEntity.setNotificationRecord(notificationRecord);
- em.persist(selfEntity);
- em.flush();
- LOGGER.info(resourceName + " is on Slave Mode");
- }
- }else{
- // Resource name is null -> No resource with same name.
- selfEntity = new BackUpMonitorEntity();
- selfEntity.setResoruceNodeName(resourceNodeName);
- selfEntity.setResourceName(resourceName);
- selfEntity.setTimeStamp(new Date());
- selfEntity = setSlave(selfEntity);
- setLastNotification(null);
- LOGGER.info("Creating: " + resourceName + " on Slave Mode");
- em.persist(selfEntity);
- em.flush();
- }
- // Correct the database if any errors and perform monitor checks.
- if(masterEntities.size()!=1 || !getFlag()){
- // We are either not master or there are more masters or no masters.
- if(masterEntities.size()==0){
- // No Masters is a problem Convert ourselves to Master.
- selfEntity = setMaster(selfEntity);
- selfEntity.setTimeStamp(new Date());
- selfEntity.setNotificationRecord(notificationRecord);
- LOGGER.info(resourceName + " changed to Master Mode - No Masters available.");
- em.persist(selfEntity);
- em.flush();
- }else {
- if(masterEntities.size()>1){
- // More Masters is a problem, Fix the issue by looking for the latest one and make others Slave.
- BackUpMonitorEntity masterEntity = null;
- for(BackUpMonitorEntity currentEntity: masterEntities){
- 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.setTimeStamp(new Date());
- em.persist(masterEntity);
- em.flush();
- masterEntity = currentEntity;
- }else{
- currentEntity.setFlag("SLAVE");
- currentEntity.setTimeStamp(new Date());
- em.persist(currentEntity);
- em.flush();
- }
- }
- }
- masterEntities = new ArrayList<>();
- masterEntities.add(masterEntity);
- }
- if(masterEntities.size()==1){
- // Correct Size, Check if Master is Latest, if not Change Master to Slave and Slave to Master.
- BackUpMonitorEntity masterEntity = masterEntities.get(0);
- if(!masterEntity.getResourceName().equals(selfEntity.getResourceName())){
- Date currentTime = new Date();
- long timeDiff = 0;
- timeDiff = currentTime.getTime()-masterEntity.getTimeStamp().getTime();
- 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");
- String lastNotification = null;
- if(masterEntity.getNotificationRecord()!=null){
- lastNotification = calculatePatch(masterEntity.getNotificationRecord());
- }
- setLastNotification(lastNotification);
- em.persist(masterEntity);
- em.flush();
- // Lets Become Master.
- selfEntity = setMaster(selfEntity);
- LOGGER.info("Changing "+ resourceName + " from slave to Master Mode");
- selfEntity.setTimeStamp(new Date());
- selfEntity.setNotificationRecord(notificationRecord);
- em.persist(selfEntity);
- em.flush();
- }
- }
- }else{
- LOGGER.error("Backup Monitor Issue, Masters out of sync, This will be fixed in next interval.");
- }
- }
- }
- }
- et.commit();
- }catch(Exception e){
- LOGGER.error("failed Database Operation " + e.getMessage());
- if(et.isActive()){
- et.rollback();
- }
- throw new Exception(e);
- }
- }
-
- // Calculate Patch and return String JsonPatch of the notification Delta.
- private synchronized String calculatePatch(String oldNotificationRecord) {
- try{
- JsonNode notification = JsonLoader.fromString(notificationRecord);
- JsonNode oldNotification = JsonLoader.fromString(oldNotificationRecord);
- JsonNode patchNode = JsonDiff.asJson(oldNotification, notification);
- LOGGER.info("Generated JSON Patch is " + patchNode.toString());
- JsonPatch patch = JsonPatch.fromJson(patchNode);
- try {
- JsonNode patched = patch.apply(oldNotification);
- LOGGER.info("Generated New Notification is : " + patched.toString());
- return patched.toString();
- } catch (JsonPatchException e) {
- LOGGER.error("Error generating Patched " +e.getMessage());
- return null;
- }
- }catch(IOException e){
- LOGGER.error("Error generating Patched " +e.getMessage());
- return null;
- }
- }
-
- /**
- * Updates Notification in the Database while Performing the health check.
- *
- * @param notification String format of notification record to store in the Database.
- * @throws Exception
- */
- public synchronized void updateNotification() throws Exception{
- checkDataBase();
- }
-
- // Take in string notification and send the record delta to Handler.
- private static void callHandler(String notification){
- if(handler!=null){
- try {
- PDPNotification notificationObject = PolicyUtils.jsonStringToObject(notification, StdPDPNotification.class);
- if(notificationObject.getNotificationType()!=null){
- LOGGER.info("Performing Patched notification ");
- try{
- handler.runOnNotification(notificationObject);
- notificationRecord = lastMasterNotification;
- }catch (Exception e){
- LOGGER.error("Error in Clients Handler Object : " + e.getMessage());
- }
- }
- } catch (IOException e) {
- LOGGER.info("Error while notification Conversion " + e.getMessage());
- }
- }
- }
-
- // Used to set LastMasterNotification Record.
- private static void setLastNotification(String notification){
- synchronized(notificationLock){
- lastMasterNotification = notification;
- if(lastMasterNotification!=null && !lastMasterNotification.equals("\"notificationType\":null")){
- if(lastMasterNotification.equals(notificationRecord)){
- return;
- }
- callHandler(notification);
- }
- }
- }
-}
diff --git a/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/BusConsumer.java b/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/BusConsumer.java
deleted file mode 100644
index 9fcae39d7..000000000
--- a/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/BusConsumer.java
+++ /dev/null
@@ -1,99 +0,0 @@
-package org.openecomp.policy.utils;
-
-import java.util.List;
-import java.util.Properties;
-
-import com.att.nsa.mr.client.impl.MRConsumerImpl;
-import com.att.nsa.mr.test.clients.ProtocolTypeConstants;
-
-public interface BusConsumer {
-
- /**
- * fetch messages
- *
- * @return list of messages
- * @throws Exception when error encountered by underlying libraries
- */
- public Iterable<String> fetch() throws Exception;
-
- /**
- * close underlying library consumer
- */
- public void close();
-
- /**
- * MR based consumer
- */
- public static class DmaapConsumerWrapper implements BusConsumer {
-
- /**
- * MR Consumer
- */
- protected MRConsumerImpl consumer;
-
- /**
- * MR Consumer Wrapper
- *
- * @param servers messaging bus hosts
- * @param topic topic
- * @param apiKey API Key
- * @param apiSecret API Secret
- * @param aafLogin AAF Login
- * @param aafPassword AAF Password
- * @param consumerGroup Consumer Group
- * @param consumerInstance Consumer Instance
- * @param fetchTimeout Fetch Timeout
- * @param fetchLimit Fetch Limit
- */
- public DmaapConsumerWrapper(List<String> servers, String topic,
- String aafLogin, String aafPassword,
- String consumerGroup, String consumerInstance,
- int fetchTimeout, int fetchLimit)
- throws Exception {
-
- this.consumer = new MRConsumerImpl(servers, topic,
- consumerGroup, consumerInstance,
- fetchTimeout, fetchLimit,
- null, aafLogin, aafPassword);
-
- this.consumer.setUsername(aafLogin);
- this.consumer.setPassword(aafPassword);
-
- this.consumer.setProtocolFlag(ProtocolTypeConstants.AAF_AUTH.getValue());
-
- Properties props = new Properties();
- props.setProperty("Protocol", "http");
- this.consumer.setProps(props);
- this.consumer.setHost(servers.get(0) + ":3904");
- }
-
- /**
- * {@inheritDoc}
- */
- public Iterable<String> fetch() throws Exception {
- return this.consumer.fetch();
- }
-
- /**
- * {@inheritDoc}
- */
- public void close() {
- this.consumer.close();
- }
-
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.
- append("DmaapConsumerWrapper [").
- append("consumer.getAuthDate()=").append(consumer.getAuthDate()).
- append(", consumer.getAuthKey()=").append(consumer.getAuthKey()).
- append(", consumer.getHost()=").append(consumer.getHost()).
- append(", consumer.getProtocolFlag()=").append(consumer.getProtocolFlag()).
- append(", consumer.getUsername()=").append(consumer.getUsername()).
- append("]");
- return builder.toString();
- }
- }
-
-}
diff --git a/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/BusPublisher.java b/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/BusPublisher.java
deleted file mode 100644
index fe3e4f6eb..000000000
--- a/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/BusPublisher.java
+++ /dev/null
@@ -1,119 +0,0 @@
-package org.openecomp.policy.utils;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Properties;
-import java.util.concurrent.TimeUnit;
-
-import org.openecomp.policy.common.logging.eelf.PolicyLogger;
-
-import com.att.nsa.mr.client.impl.MRSimplerBatchPublisher;
-import com.att.nsa.mr.test.clients.ProtocolTypeConstants;
-
-public interface BusPublisher {
-
- /**
- * sends a message
- *
- * @param partition id
- * @param message the message
- * @return true if success, false otherwise
- * @throws IllegalArgumentException if no message provided
- */
- public boolean send(String partitionId, String message) throws IllegalArgumentException;
-
- /**
- * closes the publisher
- */
- public void close();
-
- /**
- * DmaapClient library wrapper
- */
- public static class DmaapPublisherWrapper implements BusPublisher {
- /**
- * MR based Publisher
- */
- protected MRSimplerBatchPublisher publisher;
-
- public DmaapPublisherWrapper(List<String> servers, String topic,
- String aafLogin,
- String aafPassword) {
-
- ArrayList<String> dmaapServers = new ArrayList<>();
- for (String server: servers) {
- dmaapServers.add(server + ":3904");
- }
-
- this.publisher =
- new MRSimplerBatchPublisher.Builder().
- againstUrls(dmaapServers).
- onTopic(topic).
- build();
-
- this.publisher.setProtocolFlag(ProtocolTypeConstants.AAF_AUTH.getValue());
-
- this.publisher.setUsername(aafLogin);
- this.publisher.setPassword(aafPassword);
-
- Properties props = new Properties();
- props.setProperty("Protocol", "http");
- props.setProperty("contenttype", "application/json");
-
- this.publisher.setProps(props);
-
- this.publisher.setHost(servers.get(0));
-
- if (PolicyLogger.isInfoEnabled())
- PolicyLogger.info(DmaapPublisherWrapper.class.getName(),
- "CREATION: " + this);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void close() {
- if (PolicyLogger.isInfoEnabled())
- PolicyLogger.info(DmaapPublisherWrapper.class.getName(),
- "CREATION: " + this);
-
- try {
- this.publisher.close(1, TimeUnit.SECONDS);
- } catch (Exception e) {
- PolicyLogger.warn(DmaapPublisherWrapper.class.getName(),
- "CLOSE: " + this + " because of " +
- e.getMessage());
- }
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean send(String partitionId, String message)
- throws IllegalArgumentException {
- if (message == null)
- throw new IllegalArgumentException("No message provided");
-
- this.publisher.send(partitionId, message);
- return true;
-
- }
-
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.append("DmaapPublisherWrapper [").
- append("publisher.getAuthDate()=").append(publisher.getAuthDate()).
- append(", publisher.getAuthKey()=").append(publisher.getAuthKey()).
- append(", publisher.getHost()=").append(publisher.getHost()).
- append(", publisher.getProtocolFlag()=").append(publisher.getProtocolFlag()).
- append(", publisher.getUsername()=").append(publisher.getUsername()).
- append(", publisher.getPendingMessageCount()=").append(publisher.getPendingMessageCount()).
- append("]");
- return builder.toString();
- }
- }
-
-}
diff --git a/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/PolicyAccess.java b/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/PolicyAccess.java
deleted file mode 100644
index bbbffec0a..000000000
--- a/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/PolicyAccess.java
+++ /dev/null
@@ -1,106 +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.openecomp.policy.utils;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Date;
-import java.util.Properties;
-
-import org.apache.log4j.Logger;
-
-import com.att.cadi.Access;
-
-/**
- * PolicyAccess used by AAF for logging purposes.
- *
- */
-public class PolicyAccess implements Access {
- private static final Logger logger = Logger.getLogger(PolicyAccess.class.getName());
-
- private Properties properties = new Properties();
- private Access.Level logLevel = Access.Level.INFO;
-
- public PolicyAccess(Properties properties, Level level) {
- this.properties = properties;
- if(level!=null){
- logLevel = level;
- }
- }
-
- @Override
- public ClassLoader classLoader() {
- return getClass().getClassLoader();
- }
-
- @Override
- public String decrypt(String enc, boolean arg1) throws IOException {
- return enc;
- }
-
- @Override
- public String getProperty(String prop, String def) {
- return properties.getProperty(prop, def);
- }
-
- @Override
- public void load(InputStream in) throws IOException {
- properties.load(in);
- }
-
- @Override
- public void log(Level level, Object... args) {
- if (logLevel.compareTo(level) > 0) {
- return;
- }
- StringBuffer sb = new StringBuffer();
- sb.append(new Date()).append(' ').append(level);
- logtail(sb, args);
- }
-
- @Override
- public void log(Exception e, Object... args) {
- StringBuffer sb = new StringBuffer();
- sb.append(new Date()).append(" EXCEPTION ").append(e.getMessage());
- logtail(sb, args);
- logger.error(e.getMessage() + e);
- }
-
- @Override
- public void setLogLevel(Level level) {
- logLevel = level;
- }
-
- private void logtail(StringBuffer sb, Object[] args) {
- for (Object o: args) {
- String s = o.toString();
- if (s.length() > 0) {
- sb.append(' ').append(s);
- }
- }
- logger.info(sb.toString());
- }
-
- @Override
- public boolean willLog(Level arg0) {
- return false;
- }
-}
diff --git a/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/PolicyUtils.java b/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/PolicyUtils.java
deleted file mode 100644
index e7639356a..000000000
--- a/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/PolicyUtils.java
+++ /dev/null
@@ -1,201 +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.openecomp.policy.utils;
-
-import java.io.IOException;
-import java.io.StringReader;
-import java.io.UnsupportedEncodingException;
-import java.util.Arrays;
-import java.util.Base64;
-import java.util.List;
-import java.util.StringTokenizer;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-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 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 =
- "^[_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 Exception{
- 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){
- 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;
- }
-
- public static String emptyPolicyValidatorWithSpaceAllowed(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;
- }
- public static String descriptionValidator(String field) {
- String error;
- if (field.contains("@CreatedBy:") || field.contains("@ModifiedBy:")) {
- error = "The value in the description shouldn't contain @CreatedBy: or @ModifiedBy:";
- return error;
- } else {
- error = SUCCESS;
- }
- return error;
- }
-
- public static Boolean isInteger(String number){
- try{
- Integer.parseInt(number);
- }catch(NumberFormatException e){
- return false;
- }
- return true;
- }
-
- public static String validateEmailAddress(String emailAddressValue) {
- String error = SUCCESS;
- List<String> emailList = Arrays.asList(emailAddressValue.split(","));
- for(int i =0 ; i < emailList.size() ; i++){
- Pattern pattern = Pattern.compile(EMAIL_PATTERN);
- Matcher matcher = pattern.matcher(emailList.get(i).trim());
- if(!matcher.matches()){
- error = "Please check the Following Email Address is not Valid .... " +emailList.get(i);
- return error;
- }else{
- error = SUCCESS;
- }
- }
- return error;
- }
-
- /*
- * Check for "[ERR" to see if there are any errors.
- */
- public static String brmsRawValidate(String rule){
- VerifierBuilder vBuilder = VerifierBuilderFactory.newVerifierBuilder();
- Verifier verifier = vBuilder.newVerifier();
- verifier.addResourcesToVerify(new ReaderResource(new StringReader(rule)), ResourceType.DRL);
- // Check if there are any Errors in Verification.
- if(!verifier.getErrors().isEmpty()){
- 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;
- message.append("\n" + error.getMessage());
- }
- }
- // 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]");
- }
- return message.toString();
- }
- return "";
- }
-
- /**
- * 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;
- }
-}