diff options
81 files changed, 4491 insertions, 4339 deletions
diff --git a/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSGateway.java b/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSGateway.java index 0b4058d59..c4fcf5454 100644 --- a/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSGateway.java +++ b/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSGateway.java @@ -22,67 +22,60 @@ package org.onap.policy.brmsInterface; import org.onap.policy.api.NotificationScheme; import org.onap.policy.api.PolicyEngine; - -//import org.apache.log4j.Logger; - -//import org.apache.commons.logging.Log; -//import org.apache.commons.logging.LogFactory; - +import org.onap.policy.api.PolicyException; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; - import org.onap.policy.xacml.api.XACMLErrorConstants; - /** - * BRMSGateway: This application acts as the Gateway interface between the PDP XACML and PDP Drools. - * The listens for BRMS based policies and pushes them to the specified Policy Repository, from where the PDP Drools reads the Rule Jar. + * BRMSGateway: This application acts as the Gateway interface between the PDP XACML and PDP Drools. The listens for + * BRMS based policies and pushes them to the specified Policy Repository, from where the PDP Drools reads the Rule Jar. * * @version 0.1 */ public class BRMSGateway { - - private static final Logger logger = FlexLogger.getLogger(BRMSGateway.class); - private static final String configFile = "config.properties"; - - private static PolicyEngine policyEngine = null; - - public static void main(String[] args) throws Exception{ - // Initialize Handler. - logger.info("Initializing BRMS Handler"); - BRMSHandler bRMSHandler = null; - try{ - bRMSHandler = new BRMSHandler(configFile); - }catch(NullPointerException e){ - logger.error("Check your property file: " + e.getMessage()); - System.exit(1); - } - - // Set Handler with Auto Notification and initialize policyEngine - try{ - logger.info("Initializing policyEngine with Auto Notifications"); - policyEngine= new PolicyEngine(configFile,NotificationScheme.AUTO_ALL_NOTIFICATIONS, bRMSHandler); - }catch(Exception e){ - logger.error(XACMLErrorConstants.ERROR_UNKNOWN+"Error while Initializing Policy Engine " + e.getMessage()); - } - - //Keep Running.... - Runnable runnable = new Runnable(){ - public void run(){ - while (true){ - try { - Thread.sleep(30000); - } catch (InterruptedException e) { - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Thread Exception " + e.getMessage()); - } - } - } - }; - Thread thread = new Thread(runnable); - thread.start(); - } - - public static PolicyEngine getPolicyEngine(){ - return policyEngine; - } + + private static final Logger logger = FlexLogger.getLogger(BRMSGateway.class); + private static final String CONFIGFILE = "config.properties"; + + private static PolicyEngine policyEngine = null; + + public static void main(String[] args) throws Exception { + // Initialize Handler. + logger.info("Initializing BRMS Handler"); + BRMSHandler bRMSHandler = null; + try { + bRMSHandler = new BRMSHandler(CONFIGFILE); + } catch (PolicyException e) { + logger.error("Check your property file: " + e.getMessage(), e); + System.exit(1); + } + + // Set Handler with Auto Notification and initialize policyEngine + try { + logger.info("Initializing policyEngine with Auto Notifications"); + policyEngine = new PolicyEngine(CONFIGFILE, NotificationScheme.AUTO_ALL_NOTIFICATIONS, bRMSHandler); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_UNKNOWN + "Error while Initializing Policy Engine " + e.getMessage(), + e); + } + + // Keep Running.... + Runnable runnable = () -> { + while (true) { + try { + Thread.sleep(30000); + } catch (InterruptedException e) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Thread Exception " + e.getMessage()); + Thread.currentThread().interrupt(); + } + } + }; + Thread thread = new Thread(runnable); + thread.start(); + } + + public static PolicyEngine getPolicyEngine() { + return policyEngine; + } } diff --git a/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSHandler.java b/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSHandler.java index 305f64de1..43031861b 100644 --- a/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSHandler.java +++ b/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSHandler.java @@ -91,7 +91,7 @@ public class BRMSHandler implements BackUpHandler{ bRMSPush.removeRule(removedPolicy.getPolicyName()); removed = true; }catch(Exception e){ - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Rertriving policy failed " + e.getMessage()); + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Rertriving policy failed " + e.getMessage(), e); } } } @@ -106,6 +106,7 @@ public class BRMSHandler implements BackUpHandler{ //Upon Notification failure failureFlag = true; bRMSPush.rotateURLs(); + logger.error("Failure during Push Operation " , e); } } i++; @@ -138,6 +139,7 @@ public class BRMSHandler implements BackUpHandler{ //Upon Notification failure successFlag = false; bRMSPush.rotateURLs(); + logger.error("Failure during Push Operation " , e); } } } @@ -171,7 +173,7 @@ public class BRMSHandler implements BackUpHandler{ } } }catch(Exception e){ - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Rertriving policy failed " + e.getMessage()); + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Rertriving policy failed " + e.getMessage(), e); } } } diff --git a/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSPush.java b/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSPush.java index c24493882..f6f7c1214 100644 --- a/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSPush.java +++ b/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSPush.java @@ -96,670 +96,708 @@ import com.att.nsa.cambria.client.CambriaClientBuilders.PublisherBuilder; import com.fasterxml.jackson.core.JsonProcessingException; /** - * BRMSPush: Application responsible to push policies to the BRMS PDP Policy Repository (PR). - * Mavenize and push policy to PR + * BRMSPush: Application responsible to push policies to the BRMS PDP Policy Repository (PR). Mavenize and push policy + * to PR * - * @version 1.0 + * @version 1.0 */ @SuppressWarnings("deprecation") public class BRMSPush { - private static final Logger LOGGER = FlexLogger.getLogger(BRMSPush.class.getName()); - private static final String PROJECTSLOCATION = "RuleProjects"; - private static final String GOALS[] = {"clean", "deploy"}; - private static final String DEFAULT_VERSION = "1.1.0-SNAPSHOT"; - private static final String DEPENDENCY_FILE = "dependency.json"; - - private static Map<String, String> modifiedGroups = new HashMap<>(); - private static IntegrityMonitor im; - private static BackUpMonitor bm; - private static String resourceName = null; - private String defaultName = null; - private String repID = null; - private String repName = null; - private ArrayList<String> repURLs= null; - private String repUserName = null; - private String repPassword = null; - private String policyKeyID = null; - private boolean createFlag = false; - private String uebList = null; - private List<String> dmaapList = null; - private String pubTopic = null; - private PublisherBuilder pubBuilder = null; - protected BusPublisher publisher = null; - private Long uebDelay = Long.parseLong("20"); - private Long dmaapDelay = Long.parseLong("5000"); - private String notificationType = null; - private ArrayList<ControllerPOJO> controllers; - private HashMap<String, ArrayList<Object>> groupMap = new HashMap<>(); - private Map<String, String> policyMap = new HashMap<>(); - private String brmsdependencyversion; - private EntityManager em; - private boolean syncFlag = false; - - public BRMSPush(String propertiesFile, BackUpHandler handler) throws PolicyException{ - Properties config = new Properties(); - Path file = Paths.get(propertiesFile); - if(Files.notExists(file)){ - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Config File doesn't Exist in the specified Path " + file.toString()); - throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE+"Config File doesn't Exist in the specified Path " + file.toString()); - }else{ - if(file.toString().endsWith(".properties")){ - // Grab the Properties. - setProperty(file, config, handler); - } - } - } - - private void setProperty(Path file, Properties config, BackUpHandler handler) throws PolicyException{ - InputStream in; - try { - in = new FileInputStream(file.toFile()); - config.load(in); - } catch (IOException e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Data/File Read Error while reading from the property file."); - throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Data/File Read Error while reading from the property file."); - } - LOGGER.info("Trying to set up IntegrityMonitor"); - try { - LOGGER.info("Trying to set up IntegrityMonitor"); - resourceName = config.getProperty("RESOURCE_NAME"); - if(resourceName==null){ - LOGGER.warn("RESOURCE_NAME is missing setting default value. "); - resourceName = "brmsgw_pdp01"; - } - resourceName = resourceName.trim(); - im = IntegrityMonitor.getInstance(resourceName, config); - } catch (Exception e) { - LOGGER.error("Error starting Integerity Monitor: " + e); - } - LOGGER.info("Trying to set up BackUpMonitor"); - try { - bm = BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), resourceName, config, handler); - } catch (Exception e) { - LOGGER.error("Error starting BackUpMonitor: " + e); - } - config.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, "META-INF/persistenceBRMS.xml"); - EntityManagerFactory emf = Persistence.createEntityManagerFactory("BRMSGW", config); - em = emf.createEntityManager(); - defaultName = config.getProperty("defaultName"); - if(defaultName==null){ - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "defaultName property is missing from the property file "); - throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + "defaultName property is missing from the property file"); - } - defaultName = defaultName.trim(); - repID = config.getProperty("repositoryID"); - if(repID==null){ - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryID property is missing from the property file "); - throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryID property is missing from the property file "); - } - repID = repID.trim(); - repName = config.getProperty("repositoryName"); - if(repName==null){ - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryName property is missing from the property file "); - throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryName property is missing from the property file "); - } - repName = repName.trim(); - String repURL = config.getProperty("repositoryURL"); - if(repURL==null){ - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryURL property is missing from the property file "); - throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryURL property is missing from the property file "); - } - if(repURL.contains(",")){ - repURLs = new ArrayList<>(Arrays.asList(repURL.trim().split(","))); - }else{ - repURLs = new ArrayList<>(); - repURLs.add(repURL); - } - repUserName = config.getProperty("repositoryUsername"); - repPassword = config.getProperty("repositoryPassword"); - if(repUserName==null || repPassword==null){ - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "repostoryUserName and respositoryPassword properties are required."); - throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + "repostoryUserName and respositoryPassword properties are required."); - } - repUserName = repUserName.trim(); - repPassword = repPassword.trim(); - policyKeyID = config.getProperty("policyKeyID"); - if(policyKeyID==null){ - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "policyKeyID property is missing from the property file "); - throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + "policyKeyID property is missing from the property file "); - } - policyKeyID = policyKeyID.trim(); - String syncF = config.getProperty("sync", "false").trim(); - syncFlag = Boolean.parseBoolean(syncF); - if(syncFlag){ - PolicyLogger.info("SYNC Flag is turned ON. DB will be given Priority."); - } - brmsdependencyversion = config.getProperty("brms.dependency.version"); - if(brmsdependencyversion==null){ - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "brmsdependencyversion property is missing from the property file, Using default Version."); - brmsdependencyversion = DEFAULT_VERSION; - } - brmsdependencyversion = brmsdependencyversion.trim(); - readGroups(config); - - // Setup Publisher - notificationType = config.getProperty("NOTIFICATION_TYPE"); - if("dmaap".equalsIgnoreCase(notificationType)){ - - LOGGER.info("Notification Type being used is DMaaP... creating instance of BusPublisher."); - // Setting up the Publisher for DMaaP MR - String dmaapServers = config.getProperty("NOTIFICATION_SERVERS"); - pubTopic = config.getProperty("NOTIFICATION_TOPIC"); - String aafLogin = config.getProperty("CLIENT_ID").trim(); - String aafPassword = config.getProperty("CLIENT_KEY").trim(); - - if(dmaapServers==null || pubTopic==null){ - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file "); - throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file "); - } - - dmaapServers = dmaapServers.trim(); - pubTopic = pubTopic.trim(); - - if(dmaapServers.contains(",")) { - dmaapList = new ArrayList<>(Arrays.asList(dmaapServers.split("\\s*,\\s*"))); - } else { - dmaapList = new ArrayList<>(); - dmaapList.add(dmaapServers); - } - - this.publisher = - new BusPublisher.DmaapPublisherWrapper(this.dmaapList, - this.pubTopic, - aafLogin, - aafPassword); - - - String dDelay = config.getProperty("NOTIFICATION_DELAY"); - if(dDelay!=null && !dDelay.isEmpty()){ - dDelay = dDelay.trim(); - try{ - dmaapDelay = Long.parseLong(dDelay); - }catch (NumberFormatException e){ - LOGGER.error("DMAAP_DELAY not a long format number" + e); - } - } - LOGGER.info("DMAAP BusPublisher is created."); - - } else { - LOGGER.info("Notification Type being used is UEB... creating instance of PublisherBuilder."); - // Setting up the Publisher for UEB - uebList = config.getProperty("NOTIFICATION_SERVERS"); - pubTopic = config.getProperty("NOTIFICATION_TOPIC"); - String apiKey = config.getProperty("UEB_API_KEY"); - String apiSecret = config.getProperty("UEB_API_SECRET"); - if(uebList==null || pubTopic==null){ - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file "); - throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file "); - } - uebList = uebList.trim(); - pubTopic = pubTopic.trim(); - pubBuilder = new CambriaClientBuilders.PublisherBuilder(); - pubBuilder.usingHosts(uebList).onTopic(pubTopic); - if(apiKey!=null && !apiKey.isEmpty() && - apiSecret!=null && !apiSecret.isEmpty()) { - apiKey= apiKey.trim(); - apiSecret = apiSecret.trim(); - pubBuilder.authenticatedBy(apiKey, apiSecret); - } - String uDelay = config.getProperty("NOTIFICATION_DELAY"); - if(uDelay!=null && !uDelay.isEmpty()){ - uDelay = uDelay.trim(); - try{ - uebDelay = Long.parseLong(uDelay); - }catch (NumberFormatException e){ - LOGGER.error("UEB_DELAY not a long format number" + e); - } - } - LOGGER.info("UEB PublisherBuilder is created."); - - } - - } - - /** - * Will Initialize the variables required for BRMSPush. - */ - public void initiate(boolean flag) { - modifiedGroups = new HashMap<>(); - controllers = new ArrayList<>(); - try { - bm.updateNotification(); - } catch (Exception e) { - LOGGER.error("Error while updating Notification: " + e.getMessage()); - } - if(flag) syncGroupInfo(); - } - - /** - * Will Add rules to projects. Creates necessary folders if required. - */ - public void addRule(String name, String rule, Map<String, String> responseAttributes) { - // 1 check the response Attributes and determine if this belongs to any projects. - // 2 if not create folder - // 3 create pom. - // 4 copy the rule. - // 5 store the groups that have been updated. - String kSessionName=null; - String selectedName = null; - if(!responseAttributes.isEmpty()){ - // Pick selected Value - String userControllerName = null; - ArrayList<PEDependency> userDependencies = new ArrayList<>(); - for(String key: responseAttributes.keySet()){ - if(key.equals(policyKeyID)){ - selectedName = responseAttributes.get(key); - } - //kmodule configurations - else if (key.equals("kSessionName")){ - kSessionName=responseAttributes.get(key); - } - // Check User Specific values. + private static final Logger LOGGER = FlexLogger.getLogger(BRMSPush.class.getName()); + private static final String PROJECTSLOCATION = "RuleProjects"; + private static final String[] GOALS = { "clean", "deploy" }; + private static final String DEFAULT_VERSION = "1.1.0-SNAPSHOT"; + private static final String DEPENDENCY_FILE = "dependency.json"; + + private static Map<String, String> modifiedGroups = new HashMap<>(); + private static IntegrityMonitor im; + private static BackUpMonitor bm; + private String defaultName = null; + private String repID = null; + private String repName = null; + private ArrayList<String> repURLs = null; + private String repUserName = null; + private String repPassword = null; + private String policyKeyID = null; + private boolean createFlag = false; + private String uebList = null; + private List<String> dmaapList = null; + private String pubTopic = null; + private PublisherBuilder pubBuilder = null; + protected BusPublisher publisher = null; + private Long uebDelay = Long.parseLong("20"); + private Long dmaapDelay = Long.parseLong("5000"); + private String notificationType = null; + private ArrayList<ControllerPOJO> controllers; + private HashMap<String, ArrayList<Object>> groupMap = new HashMap<>(); + private Map<String, String> policyMap = new HashMap<>(); + private String brmsdependencyversion; + private EntityManager em; + private boolean syncFlag = false; + + public BRMSPush(String propertiesFile, BackUpHandler handler) throws PolicyException { + Properties config = new Properties(); + Path file = Paths.get(propertiesFile); + if (Files.notExists(file)) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Config File doesn't Exist in the specified Path " + + file.toString()); + throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + + "Config File doesn't Exist in the specified Path " + file.toString()); + } else { + if (file.toString().endsWith(".properties")) { + // Grab the Properties. + setProperty(file, config, handler); + } + } + } + + private void setProperty(Path file, Properties config, BackUpHandler handler) throws PolicyException { + InputStream in; + try { + in = new FileInputStream(file.toFile()); + config.load(in); + } catch (IOException e) { + LOGGER.error( + XACMLErrorConstants.ERROR_DATA_ISSUE + "Data/File Read Error while reading from the property file.", + e); + throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + + "Data/File Read Error while reading from the property file."); + } + LOGGER.info("Trying to set up IntegrityMonitor"); + String resourceName = null; + try { + LOGGER.info("Trying to set up IntegrityMonitor"); + resourceName = config.getProperty("RESOURCE_NAME"); + if (resourceName == null) { + LOGGER.warn("RESOURCE_NAME is missing setting default value. "); + resourceName = "brmsgw_pdp01"; + } + resourceName = resourceName.trim(); + setIntegrityMonitor(IntegrityMonitor.getInstance(resourceName, config)); + } catch (Exception e) { + LOGGER.error("Error starting Integerity Monitor: " + e); + } + LOGGER.info("Trying to set up BackUpMonitor"); + try { + setBackupMonitor(BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), resourceName, config, + handler)); + } catch (Exception e) { + LOGGER.error("Error starting BackUpMonitor: " + e); + } + config.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, "META-INF/persistenceBRMS.xml"); + EntityManagerFactory emf = Persistence.createEntityManagerFactory("BRMSGW", config); + em = emf.createEntityManager(); + defaultName = config.getProperty("defaultName"); + if (defaultName == null) { + LOGGER.error( + XACMLErrorConstants.ERROR_DATA_ISSUE + "defaultName property is missing from the property file "); + throw new PolicyException( + XACMLErrorConstants.ERROR_DATA_ISSUE + "defaultName property is missing from the property file"); + } + defaultName = defaultName.trim(); + repID = config.getProperty("repositoryID"); + if (repID == null) { + LOGGER.error( + XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryID property is missing from the property file "); + throw new PolicyException( + XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryID property is missing from the property file "); + } + repID = repID.trim(); + repName = config.getProperty("repositoryName"); + if (repName == null) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + + "repositoryName property is missing from the property file "); + throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + + "repositoryName property is missing from the property file "); + } + repName = repName.trim(); + String repURL = config.getProperty("repositoryURL"); + if (repURL == null) { + LOGGER.error( + XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryURL property is missing from the property file "); + throw new PolicyException( + XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryURL property is missing from the property file "); + } + if (repURL.contains(",")) { + repURLs = new ArrayList<>(Arrays.asList(repURL.trim().split(","))); + } else { + repURLs = new ArrayList<>(); + repURLs.add(repURL); + } + repUserName = config.getProperty("repositoryUsername"); + repPassword = config.getProperty("repositoryPassword"); + if (repUserName == null || repPassword == null) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + + "repostoryUserName and respositoryPassword properties are required."); + throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + + "repostoryUserName and respositoryPassword properties are required."); + } + repUserName = repUserName.trim(); + repPassword = repPassword.trim(); + policyKeyID = config.getProperty("policyKeyID"); + if (policyKeyID == null) { + LOGGER.error( + XACMLErrorConstants.ERROR_DATA_ISSUE + "policyKeyID property is missing from the property file "); + throw new PolicyException( + XACMLErrorConstants.ERROR_DATA_ISSUE + "policyKeyID property is missing from the property file "); + } + policyKeyID = policyKeyID.trim(); + String syncF = config.getProperty("sync", "false").trim(); + syncFlag = Boolean.parseBoolean(syncF); + if (syncFlag) { + PolicyLogger.info("SYNC Flag is turned ON. DB will be given Priority."); + } + brmsdependencyversion = config.getProperty("brms.dependency.version"); + if (brmsdependencyversion == null) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + + "brmsdependencyversion property is missing from the property file, Using default Version."); + brmsdependencyversion = DEFAULT_VERSION; + } + brmsdependencyversion = brmsdependencyversion.trim(); + readGroups(config); + + // Setup Publisher + notificationType = config.getProperty("NOTIFICATION_TYPE"); + if ("dmaap".equalsIgnoreCase(notificationType)) { + + LOGGER.info("Notification Type being used is DMaaP... creating instance of BusPublisher."); + // Setting up the Publisher for DMaaP MR + String dmaapServers = config.getProperty("NOTIFICATION_SERVERS"); + pubTopic = config.getProperty("NOTIFICATION_TOPIC"); + String aafLogin = config.getProperty("CLIENT_ID").trim(); + String aafPassword = config.getProperty("CLIENT_KEY").trim(); + + if (dmaapServers == null || pubTopic == null) { + LOGGER.error( + XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file "); + throw new PolicyException( + XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file "); + } + + dmaapServers = dmaapServers.trim(); + pubTopic = pubTopic.trim(); + + if (dmaapServers.contains(",")) { + dmaapList = new ArrayList<>(Arrays.asList(dmaapServers.split("\\s*,\\s*"))); + } else { + dmaapList = new ArrayList<>(); + dmaapList.add(dmaapServers); + } + + this.publisher = new BusPublisher.DmaapPublisherWrapper(this.dmaapList, this.pubTopic, aafLogin, + aafPassword); + + String dDelay = config.getProperty("NOTIFICATION_DELAY"); + if (dDelay != null && !dDelay.isEmpty()) { + dDelay = dDelay.trim(); + try { + dmaapDelay = Long.parseLong(dDelay); + } catch (NumberFormatException e) { + LOGGER.error("DMAAP_DELAY not a long format number" + e); + } + } + LOGGER.info("DMAAP BusPublisher is created."); + + } else { + LOGGER.info("Notification Type being used is UEB... creating instance of PublisherBuilder."); + // Setting up the Publisher for UEB + uebList = config.getProperty("NOTIFICATION_SERVERS"); + pubTopic = config.getProperty("NOTIFICATION_TOPIC"); + String apiKey = config.getProperty("UEB_API_KEY"); + String apiSecret = config.getProperty("UEB_API_SECRET"); + if (uebList == null || pubTopic == null) { + LOGGER.error( + XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file "); + throw new PolicyException( + XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file "); + } + uebList = uebList.trim(); + pubTopic = pubTopic.trim(); + pubBuilder = new CambriaClientBuilders.PublisherBuilder(); + pubBuilder.usingHosts(uebList).onTopic(pubTopic); + if (apiKey != null && !apiKey.isEmpty() && apiSecret != null && !apiSecret.isEmpty()) { + apiKey = apiKey.trim(); + apiSecret = apiSecret.trim(); + pubBuilder.authenticatedBy(apiKey, apiSecret); + } + String uDelay = config.getProperty("NOTIFICATION_DELAY"); + if (uDelay != null && !uDelay.isEmpty()) { + uDelay = uDelay.trim(); + try { + uebDelay = Long.parseLong(uDelay); + } catch (NumberFormatException e) { + LOGGER.error("UEB_DELAY not a long format number" + e); + } + } + LOGGER.info("UEB PublisherBuilder is created."); + + } + + } + + private static void setBackupMonitor(BackUpMonitor instance) { + bm = instance; + } + + private static void setIntegrityMonitor(IntegrityMonitor instance) { + im = instance; + } + + /** + * Will Initialize the variables required for BRMSPush. + */ + public void initiate(boolean flag) { + resetModifiedGroups(); + controllers = new ArrayList<>(); + try { + bm.updateNotification(); + } catch (Exception e) { + LOGGER.error("Error while updating Notification: " + e.getMessage(), e); + } + if (flag) + syncGroupInfo(); + } + + private static void resetModifiedGroups() { + modifiedGroups = new HashMap<>(); + } + + /** + * Will Add rules to projects. Creates necessary folders if required. + */ + public void addRule(String name, String rule, Map<String, String> responseAttributes) { + // 1 check the response Attributes and determine if this belongs to any projects. + // 2 if not create folder + // 3 create pom. + // 4 copy the rule. + // 5 store the groups that have been updated. + String kSessionName = null; + String selectedName = null; + if (!responseAttributes.isEmpty()) { + // Pick selected Value + String userControllerName = null; + ArrayList<PEDependency> userDependencies = new ArrayList<>(); + for (String key : responseAttributes.keySet()) { + if (key.equals(policyKeyID)) { + selectedName = responseAttributes.get(key); + } + // kmodule configurations + else if (key.equals("kSessionName")) { + kSessionName = responseAttributes.get(key); + } + // Check User Specific values. if (key.equals("$controller:")) { try { - PEDependency dependency = PolicyUtils.jsonStringToObject(responseAttributes.get(key), PEDependency.class); - userControllerName = key.replaceFirst("$controller:",""); + PEDependency dependency = PolicyUtils.jsonStringToObject(responseAttributes.get(key), + PEDependency.class); + userControllerName = key.replaceFirst("$controller:", ""); addToGroup(userControllerName, dependency); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Error while resolving Controller: " + e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while resolving Controller: " + e); } - } - else if(key.equals("$dependency$")){ + } else if (key.equals("$dependency$")) { String value = responseAttributes.get(key); - if(value.startsWith("[") && value.endsWith("]")){ - value = value.substring(1, value.length()-1).trim(); + if (value.startsWith("[") && value.endsWith("]")) { + value = value.substring(1, value.length() - 1).trim(); List<String> dependencyStrings = Arrays.asList(value.split("},{")); - for(String dependencyString: dependencyStrings){ + for (String dependencyString : dependencyStrings) { try { - userDependencies.add(PolicyUtils.jsonStringToObject(dependencyString, PEDependency.class)); + userDependencies + .add(PolicyUtils.jsonStringToObject(dependencyString, PEDependency.class)); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Error while resolving Dependencies: " + e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error while resolving Dependencies: " + e); } } } } - } - if(userControllerName!=null){ - // Adding custom dependencies here. + } + if (userControllerName != null) { + // Adding custom dependencies here. ArrayList<Object> values = groupMap.get(userControllerName); values.add(userDependencies); groupMap.put(userControllerName, values); selectedName = userControllerName; } - } - // If no Match then pick Default. - if(selectedName==null){ - selectedName = defaultName; - } - if (groupMap.containsKey(selectedName)) { - //If the key is not got as parameters set by the user, setting the default value for kSessionName as closedLoop - if(kSessionName==null){ - if(selectedName==defaultName){ - kSessionName="closedloop"; - }else{ - kSessionName= "closedloop-" + selectedName; - } - } - // create directories if missing. - manageProject(selectedName, kSessionName, name, rule); + } + // If no Match then pick Default. + if (selectedName == null) { + selectedName = defaultName; + } + if (groupMap.containsKey(selectedName)) { + // If the key is not got as parameters set by the user, setting the default value for kSessionName as + // closedLoop + if (kSessionName == null) { + if (selectedName == defaultName) { + kSessionName = "closedloop"; + } else { + kSessionName = "closedloop-" + selectedName; + } + } + // create directories if missing. + manageProject(selectedName, kSessionName, name, rule); addModifiedGroup(selectedName, "update"); // Will check for Create Later after generating the Pom. - } - } - - private void syncGroupInfo() { - // Sync DB to JMemory. - EntityTransaction et = em.getTransaction(); - et.begin(); - Query query = em.createQuery("select b from BRMSGroupInfo AS b"); - List<?> bList = query.getResultList(); - if(bList.size()!=groupMap.size()){ - for(Object value : bList){ - BRMSGroupInfo brmsGroupInfo = (BRMSGroupInfo) value; - PEDependency dependency = new PEDependency(); - dependency.setArtifactId(brmsGroupInfo.getArtifactId()); - dependency.setGroupId(brmsGroupInfo.getGroupId()); - dependency.setVersion(brmsGroupInfo.getVersion()); - ArrayList<Object> values = new ArrayList<>(); - values.add(dependency); - groupMap.put(brmsGroupInfo.getControllerName(), values); - } - } - query = em.createQuery("select g from BRMSPolicyInfo AS g"); - bList = query.getResultList(); - if(bList.size()!=policyMap.size()){ - for(Object value: bList){ - BRMSPolicyInfo brmsPolicyInfo = (BRMSPolicyInfo) value; - policyMap.put(brmsPolicyInfo.getPolicyName(), brmsPolicyInfo.getControllerName().getControllerName()); - } - } - et.commit(); - LOGGER.info("Updated Local Memory values with values from database."); - } - - private void manageProject(String selectedName, String kSessionName, String name, String rule) { - // Check if the Project is in Sync. If not get the latest Version. - syncProject(selectedName); - createProject(PROJECTSLOCATION + File.separator - + getArtifactID(selectedName) + File.separator + "src" - + File.separator + "main" + File.separator + "resources", - kSessionName); - copyDataToFile( - PROJECTSLOCATION + File.separator - + getArtifactID(selectedName) + File.separator - + "src" + File.separator + "main" + File.separator - + "resources" + File.separator + "rules" - + File.separator + name + ".drl", rule); - addToPolicy(name,selectedName); - } - - /* - * Add Policy to JMemory and DataBase. - */ - private void addToPolicy(String policyName, String controllerName) { - policyMap.put(policyName, controllerName); - EntityTransaction et = em.getTransaction(); - et.begin(); - Query query = em.createQuery("select b from BRMSPolicyInfo as b where b.policyName = :pn"); - query.setParameter("pn", policyName); - List<?> pList = query.getResultList(); - boolean createFlag = false; - BRMSPolicyInfo brmsPolicyInfo = new BRMSPolicyInfo(); - if(pList.size()>0){ - // Already exists. - brmsPolicyInfo = (BRMSPolicyInfo) pList.get(0); - if(!brmsPolicyInfo.getControllerName().getControllerName().equals(controllerName)){ - createFlag = true; - } - }else{ - createFlag = true; - } - if(createFlag){ - query = em.createQuery("select b from BRMSGroupInfo as b where b.controllerName = :cn"); - query.setParameter("cn", controllerName); - List<?> bList = query.getResultList(); - BRMSGroupInfo brmsGroupInfo = new BRMSGroupInfo(); - if(bList.size()>0){ - brmsGroupInfo = (BRMSGroupInfo) bList.get(0); - } - brmsPolicyInfo.setPolicyName(policyName); - brmsPolicyInfo.setControllerName(brmsGroupInfo); - em.persist(brmsPolicyInfo); - em.flush(); - } - et.commit(); - } - - private void syncProject(String selectedName) { - boolean projectExists = checkProject(selectedName); - if(projectExists){ - String version = null; - version = getVersion(selectedName); - if(version==null){ - LOGGER.error("Error getting local version for the given Controller Name:"+ selectedName+" going with Default value"); - version = "0.1.0"; - } - String nextVersion = incrementVersion(version); - boolean outOfSync = checkRemoteSync(selectedName, nextVersion); - if(!outOfSync){ - return; - } - } - // We are out of Sync or Project is not Present. - downloadProject(selectedName); - } - - private void downloadProject(String selectedName) { - NexusArtifact artifact = getLatestArtifactFromNexus(selectedName); - if(artifact==null) return; - String dirName = getDirectoryName(selectedName); - URL website; - String fileName = "rule.jar"; - try { - website = new URL(artifact.getResourceURI()); - ReadableByteChannel rbc = Channels.newChannel(website.openStream()); - FileOutputStream fos = new FileOutputStream(fileName); - fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); - fos.close(); - extractJar(fileName, dirName); - new File(fileName).delete(); - } catch (IOException e) { - LOGGER.error("Error while downloading the project to File System. " + e.getMessage()); - } - } - - private void extractJar(String jarFileName, String artifactId) throws IOException{ - JarFile jar = new JarFile(jarFileName); - Enumeration<?> enumEntries = jar.entries(); - while (enumEntries.hasMoreElements()) { - JarEntry file = (JarEntry) enumEntries.nextElement(); - File f = null; - String fileName = file.getName().substring(file.getName().lastIndexOf("/")+1); - if(file.getName().endsWith(".drl")){ - String path = PROJECTSLOCATION+ File.separator + artifactId + File.separator + "src"+ - File.separator+ "main" + File.separator + "resources" + File.separator+ "rules"; - new File(path).mkdirs(); - if(syncFlag && policyMap.containsKey(fileName.replace(".drl", ""))){ - f = new File(path + File.separator + fileName); - }else{ - f = new File(path + File.separator + fileName); - } - }else if(file.getName().endsWith("pom.xml")){ - String path = PROJECTSLOCATION+ File.separator + artifactId; - new File(path).mkdirs(); - f = new File(path + File.separator + fileName); - }else if(file.getName().endsWith("kmodule.xml")){ - String path = PROJECTSLOCATION+ File.separator + artifactId + File.separator + "src"+ - File.separator+ "main" + File.separator + "resources" + File.separator+ "META-INF"; - new File(path).mkdirs(); - f = new File(path + File.separator + fileName); - } - if(f!=null){ - InputStream is = jar.getInputStream(file); - FileOutputStream fos = new FileOutputStream(f); - while (is.available() > 0) { - fos.write(is.read()); - } - fos.close(); - is.close(); - f=null; - LOGGER.info(fileName + " Created.."); - } - } - jar.close(); - } - - private NexusArtifact getLatestArtifactFromNexus(String selectedName) { - List<NexusArtifact> artifacts = getArtifactFromNexus(selectedName, null); - int bigNum = 0; + } + } + + private void syncGroupInfo() { + // Sync DB to JMemory. + EntityTransaction et = em.getTransaction(); + et.begin(); + Query query = em.createQuery("select b from BRMSGroupInfo AS b"); + List<?> bList = query.getResultList(); + if (bList.size() != groupMap.size()) { + for (Object value : bList) { + BRMSGroupInfo brmsGroupInfo = (BRMSGroupInfo) value; + PEDependency dependency = new PEDependency(); + dependency.setArtifactId(brmsGroupInfo.getArtifactId()); + dependency.setGroupId(brmsGroupInfo.getGroupId()); + dependency.setVersion(brmsGroupInfo.getVersion()); + ArrayList<Object> values = new ArrayList<>(); + values.add(dependency); + groupMap.put(brmsGroupInfo.getControllerName(), values); + } + } + query = em.createQuery("select g from BRMSPolicyInfo AS g"); + bList = query.getResultList(); + if (bList.size() != policyMap.size()) { + for (Object value : bList) { + BRMSPolicyInfo brmsPolicyInfo = (BRMSPolicyInfo) value; + policyMap.put(brmsPolicyInfo.getPolicyName(), brmsPolicyInfo.getControllerName().getControllerName()); + } + } + et.commit(); + LOGGER.info("Updated Local Memory values with values from database."); + } + + private void manageProject(String selectedName, String kSessionName, String name, String rule) { + // Check if the Project is in Sync. If not get the latest Version. + syncProject(selectedName); + createProject(PROJECTSLOCATION + File.separator + getArtifactID(selectedName) + File.separator + "src" + + File.separator + "main" + File.separator + "resources", kSessionName); + copyDataToFile(PROJECTSLOCATION + File.separator + getArtifactID(selectedName) + File.separator + "src" + + File.separator + "main" + File.separator + "resources" + File.separator + "rules" + File.separator + + name + ".drl", rule); + addToPolicy(name, selectedName); + } + + /* + * Add Policy to JMemory and DataBase. + */ + private void addToPolicy(String policyName, String controllerName) { + policyMap.put(policyName, controllerName); + EntityTransaction et = em.getTransaction(); + et.begin(); + Query query = em.createQuery("select b from BRMSPolicyInfo as b where b.policyName = :pn"); + query.setParameter("pn", policyName); + List<?> pList = query.getResultList(); + boolean createFlag = false; + BRMSPolicyInfo brmsPolicyInfo = new BRMSPolicyInfo(); + if (pList.size() > 0) { + // Already exists. + brmsPolicyInfo = (BRMSPolicyInfo) pList.get(0); + if (!brmsPolicyInfo.getControllerName().getControllerName().equals(controllerName)) { + createFlag = true; + } + } else { + createFlag = true; + } + if (createFlag) { + query = em.createQuery("select b from BRMSGroupInfo as b where b.controllerName = :cn"); + query.setParameter("cn", controllerName); + List<?> bList = query.getResultList(); + BRMSGroupInfo brmsGroupInfo = new BRMSGroupInfo(); + if (bList.size() > 0) { + brmsGroupInfo = (BRMSGroupInfo) bList.get(0); + } + brmsPolicyInfo.setPolicyName(policyName); + brmsPolicyInfo.setControllerName(brmsGroupInfo); + em.persist(brmsPolicyInfo); + em.flush(); + } + et.commit(); + } + + private void syncProject(String selectedName) { + boolean projectExists = checkProject(selectedName); + if (projectExists) { + String version = null; + version = getVersion(selectedName); + if (version == null) { + LOGGER.error("Error getting local version for the given Controller Name:" + selectedName + + " going with Default value"); + version = "0.1.0"; + } + String nextVersion = incrementVersion(version); + boolean outOfSync = checkRemoteSync(selectedName, nextVersion); + if (!outOfSync) { + return; + } + } + // We are out of Sync or Project is not Present. + downloadProject(selectedName); + } + + private void downloadProject(String selectedName) { + NexusArtifact artifact = getLatestArtifactFromNexus(selectedName); + if (artifact == null) + return; + String dirName = getDirectoryName(selectedName); + URL website; + String fileName = "rule.jar"; + try { + website = new URL(artifact.getResourceURI()); + ReadableByteChannel rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(fileName); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + extractJar(fileName, dirName); + new File(fileName).delete(); + } catch (IOException e) { + LOGGER.error("Error while downloading the project to File System. " + e.getMessage(), e); + } + } + + private void extractJar(String jarFileName, String artifactId) throws IOException { + JarFile jar = new JarFile(jarFileName); + Enumeration<?> enumEntries = jar.entries(); + while (enumEntries.hasMoreElements()) { + JarEntry file = (JarEntry) enumEntries.nextElement(); + File f = null; + String fileName = file.getName().substring(file.getName().lastIndexOf("/") + 1); + if (file.getName().endsWith(".drl")) { + String path = PROJECTSLOCATION + File.separator + artifactId + File.separator + "src" + File.separator + + "main" + File.separator + "resources" + File.separator + "rules"; + new File(path).mkdirs(); + if (syncFlag && policyMap.containsKey(fileName.replace(".drl", ""))) { + f = new File(path + File.separator + fileName); + } else { + f = new File(path + File.separator + fileName); + } + } else if (file.getName().endsWith("pom.xml")) { + String path = PROJECTSLOCATION + File.separator + artifactId; + new File(path).mkdirs(); + f = new File(path + File.separator + fileName); + } else if (file.getName().endsWith("kmodule.xml")) { + String path = PROJECTSLOCATION + File.separator + artifactId + File.separator + "src" + File.separator + + "main" + File.separator + "resources" + File.separator + "META-INF"; + new File(path).mkdirs(); + f = new File(path + File.separator + fileName); + } + if (f != null) { + InputStream is = jar.getInputStream(file); + FileOutputStream fos = new FileOutputStream(f); + while (is.available() > 0) { + fos.write(is.read()); + } + fos.close(); + is.close(); + f = null; + LOGGER.info(fileName + " Created.."); + } + } + jar.close(); + } + + private NexusArtifact getLatestArtifactFromNexus(String selectedName) { + List<NexusArtifact> artifacts = getArtifactFromNexus(selectedName, null); + int bigNum = 0; int smallNum = 0; NexusArtifact result = null; for (NexusArtifact artifact : artifacts) { int majorVal = Integer.parseInt(artifact.getVersion().substring(0, artifact.getVersion().indexOf("."))); - int minorVal = Integer.parseInt(artifact.getVersion().substring(artifact.getVersion().indexOf(".")+1,artifact.getVersion().lastIndexOf("."))); - if(majorVal>bigNum){ + int minorVal = Integer.parseInt(artifact.getVersion().substring(artifact.getVersion().indexOf(".") + 1, + artifact.getVersion().lastIndexOf("."))); + if (majorVal > bigNum) { bigNum = majorVal; smallNum = minorVal; } - if((bigNum==majorVal)&&(minorVal>smallNum)){ + if ((bigNum == majorVal) && (minorVal > smallNum)) { smallNum = minorVal; } - if(bigNum==majorVal && minorVal==smallNum){ + if (bigNum == majorVal && minorVal == smallNum) { result = artifact; } } return additionalNexusLatestCheck(selectedName, result); - } - - // Additional Check due to Limitations from Nexus API to check if the artifact is the latest. - private NexusArtifact additionalNexusLatestCheck(String selectedName, NexusArtifact result) { - String nextVersion = incrementVersion(result.getVersion()); + } + + // Additional Check due to Limitations from Nexus API to check if the artifact is the latest. + private NexusArtifact additionalNexusLatestCheck(String selectedName, NexusArtifact result) { + String nextVersion = incrementVersion(result.getVersion()); List<NexusArtifact> artifact = getArtifactFromNexus(selectedName, nextVersion); - return artifact.isEmpty()? result: additionalNexusLatestCheck(selectedName, artifact.get(0)); - } - - private boolean checkRemoteSync(String selectedName, String version) { - List<NexusArtifact> artifacts = getArtifactFromNexus(selectedName, version); - return (artifacts.size()==0) ? false: true; - } - - private List<NexusArtifact> getArtifactFromNexus(String selectedName, String version) { - final NexusClient client = new NexusRestClient(); - int i = 0 ; - boolean flag = false; - while(i<repURLs.size()){ - try { - String repURL = repURLs.get(0); - client.connect(repURL.substring(0, repURL.indexOf(repURL.split(":[0-9]+\\/nexus")[1])), repUserName, repPassword); - final NexusArtifact template = new NexusArtifact(); - template.setGroupId(getGroupID(selectedName)); - template.setArtifactId(getArtifactID(selectedName)); - if(version!=null){ - template.setVersion(version); - } - List<NexusArtifact> resultList = client.searchByGAV(template); - if(resultList!=null){ - flag = true; - return resultList; - } - } catch (NexusClientException | NexusConnectionException | NullPointerException e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Connection to remote Nexus has failed. " +e.getMessage()); - } finally { - try { - client.disconnect(); - } catch (NexusClientException | NexusConnectionException e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "failed to disconnect Connection from Nexus." +e.getMessage()); - } - if(!flag){ - Collections.rotate(repURLs, -1); - i++; - } - } - } - return new ArrayList<>(); - } - - private void setVersion(String selectedName) { - String newVersion = "0.1.0"; - createFlag = false; - NexusArtifact artifact = getLatestArtifactFromNexus(selectedName); - if(artifact!=null){ - newVersion = incrementVersion(artifact.getVersion()); - } - if(newVersion.equals("0.1.0")){ - createFlag = true; - } - setVersion(newVersion, selectedName); + return artifact.isEmpty() ? result : additionalNexusLatestCheck(selectedName, artifact.get(0)); + } + + private boolean checkRemoteSync(String selectedName, String version) { + List<NexusArtifact> artifacts = getArtifactFromNexus(selectedName, version); + return (artifacts.size() == 0) ? false : true; + } + + private List<NexusArtifact> getArtifactFromNexus(String selectedName, String version) { + final NexusClient client = new NexusRestClient(); + int i = 0; + boolean flag = false; + while (i < repURLs.size()) { + try { + String repURL = repURLs.get(0); + client.connect(repURL.substring(0, repURL.indexOf(repURL.split(":[0-9]+\\/nexus")[1])), repUserName, + repPassword); + final NexusArtifact template = new NexusArtifact(); + template.setGroupId(getGroupID(selectedName)); + template.setArtifactId(getArtifactID(selectedName)); + if (version != null) { + template.setVersion(version); + } + List<NexusArtifact> resultList = client.searchByGAV(template); + if (resultList != null) { + flag = true; + return resultList; + } + } catch (NexusClientException | NexusConnectionException | NullPointerException e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Connection to remote Nexus has failed. " + + e.getMessage(), e); + } finally { + try { + client.disconnect(); + } catch (NexusClientException | NexusConnectionException e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "failed to disconnect Connection from Nexus." + + e.getMessage(), e); + } + if (!flag) { + Collections.rotate(repURLs, -1); + i++; + } + } + } + return new ArrayList<>(); + } + + private void setVersion(String selectedName) { + String newVersion = "0.1.0"; + createFlag = false; + NexusArtifact artifact = getLatestArtifactFromNexus(selectedName); + if (artifact != null) { + newVersion = incrementVersion(artifact.getVersion()); + } + if (newVersion.equals("0.1.0")) { + createFlag = true; + } + setVersion(newVersion, selectedName); LOGGER.info("Controller: " + selectedName + "is on version: " + newVersion); - } + } - private String incrementVersion(String version) { - int majorVal = Integer.parseInt(version.substring(0, version.indexOf("."))); - int minorVal = Integer.parseInt(version.substring(version.indexOf(".")+1,version.lastIndexOf("."))); - if (minorVal >= 9) { + private String incrementVersion(String version) { + int majorVal = Integer.parseInt(version.substring(0, version.indexOf("."))); + int minorVal = Integer.parseInt(version.substring(version.indexOf(".") + 1, version.lastIndexOf("."))); + if (minorVal >= 9) { majorVal += 1; minorVal = 0; } else { minorVal += 1; } - return majorVal + "." + minorVal + version.substring(version.lastIndexOf(".")); - } - - private boolean checkProject(String selectedName) { - return new File(PROJECTSLOCATION + File.separator + getDirectoryName(selectedName)).exists(); - } - - private String getDirectoryName(String selectedName) { - return getArtifactID(selectedName); - } - - /** - * Will Push policies to the PolicyRepo. - * - * @param notificationType <String> type of notification Type. - * @throws PolicyException - */ - public void pushRules() throws PolicyException{ - // Check how many groups have been updated. - // Invoke their Maven process. - try { - im.startTransaction(); - } catch (AdministrativeStateException e) { - LOGGER.error("Error while starting Transaction " + e); - } catch (Exception e) { - LOGGER.error("Error while starting Transaction " + e); - } - if(!modifiedGroups.isEmpty()){ - Boolean flag = false; - for(String group: modifiedGroups.keySet()){ - InvocationResult result = null; - try{ - InvocationRequest request = new DefaultInvocationRequest(); - setVersion(group); - createPom(group); - request.setPomFile(new File(PROJECTSLOCATION+File.separator+getArtifactID(group)+File.separator+"pom.xml")); - request.setGoals(Arrays.asList(GOALS)); - Invoker invoker = new DefaultInvoker(); - result = invoker.execute(request); - if(result.getExecutionException()!=null){ - LOGGER.error(result.getExecutionException()); - }else if(result.getExitCode()!=0){ - LOGGER.error("Maven Invocation failure..!"); - } - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Maven Invocation issue for "+getArtifactID(group) + e.getMessage()); - } - if(result!=null && result.getExitCode()==0){ - LOGGER.info("Build Completed..!"); - if (createFlag) { - addNotification(group, "create"); - }else{ - addNotification(group, modifiedGroups.get(group)); - } - flag = true; - }else{ - throw new PolicyException(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation failure!"); - } - } - if(flag){ - sendNotification(controllers); - } - } - if(im!=null){ - im.endTransaction(); - } - } - - /** - * Removes a Rule from Rule Projects. - */ - public void removeRule(String name){ - String controllerName = getGroupName(name); - if(controllerName==null){ - LOGGER.info("Error finding the controllerName for the given Policy: " + name); - return; - } - syncProject(controllerName); - getNameAndSetRemove(controllerName, name); - } - - private String getGroupName(String name) { - if(policyMap.containsKey(name)){ - return policyMap.get(name); - }else{ - syncGroupInfo(); - return (policyMap.containsKey(name)) ? policyMap.get(name):null; - } - } - - private void addModifiedGroup(String controllerName, String operation) { - if(controllerName!=null){ + return majorVal + "." + minorVal + version.substring(version.lastIndexOf(".")); + } + + private boolean checkProject(String selectedName) { + return new File(PROJECTSLOCATION + File.separator + getDirectoryName(selectedName)).exists(); + } + + private String getDirectoryName(String selectedName) { + return getArtifactID(selectedName); + } + + /** + * Will Push policies to the PolicyRepo. + * + * @param notificationType + * <String> type of notification Type. + * @throws PolicyException + */ + public void pushRules() throws PolicyException { + // Check how many groups have been updated. + // Invoke their Maven process. + try { + im.startTransaction(); + } catch (AdministrativeStateException e) { + LOGGER.error("Error while starting Transaction " + e); + } catch (Exception e) { + LOGGER.error("Error while starting Transaction " + e); + } + if (!modifiedGroups.isEmpty()) { + Boolean flag = false; + for (String group : modifiedGroups.keySet()) { + InvocationResult result = null; + try { + InvocationRequest request = new DefaultInvocationRequest(); + setVersion(group); + createPom(group); + request.setPomFile(new File( + PROJECTSLOCATION + File.separator + getArtifactID(group) + File.separator + "pom.xml")); + request.setGoals(Arrays.asList(GOALS)); + Invoker invoker = new DefaultInvoker(); + result = invoker.execute(request); + if (result.getExecutionException() != null) { + LOGGER.error(result.getExecutionException()); + } else if (result.getExitCode() != 0) { + LOGGER.error("Maven Invocation failure..!"); + } + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation issue for " + + getArtifactID(group) + e.getMessage(), e); + } + if (result != null && result.getExitCode() == 0) { + LOGGER.info("Build Completed..!"); + if (createFlag) { + addNotification(group, "create"); + } else { + addNotification(group, modifiedGroups.get(group)); + } + flag = true; + } else { + throw new PolicyException(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation failure!"); + } + } + if (flag) { + sendNotification(controllers); + } + } + if (im != null) { + im.endTransaction(); + } + } + + /** + * Removes a Rule from Rule Projects. + */ + public void removeRule(String name) { + String controllerName = getGroupName(name); + if (controllerName == null) { + LOGGER.info("Error finding the controllerName for the given Policy: " + name); + return; + } + syncProject(controllerName); + getNameAndSetRemove(controllerName, name); + } + + private String getGroupName(String name) { + if (policyMap.containsKey(name)) { + return policyMap.get(name); + } else { + syncGroupInfo(); + return (policyMap.containsKey(name)) ? policyMap.get(name) : null; + } + } + + private void addModifiedGroup(String controllerName, String operation) { + if (controllerName != null) { modifiedGroups.put(controllerName, operation); } } - private void addNotification(String controllerName, String operation) { + private void addNotification(String controllerName, String operation) { ControllerPOJO controllerPOJO = new ControllerPOJO(); controllerPOJO.setName(controllerName); controllerPOJO.setOperation(operation); @@ -770,338 +808,341 @@ public class BRMSPush { controllerPOJO.setDrools(drools); controllers.add(controllerPOJO); try { - LOGGER.debug("Notification added: " - + PolicyUtils.objectToJsonString(controllerPOJO)); + LOGGER.debug("Notification added: " + PolicyUtils.objectToJsonString(controllerPOJO)); } catch (JsonProcessingException e) { - LOGGER.error(MessageCodes.ERROR_SCHEMA_INVALID - + "Json Processing Error " + e); + LOGGER.error(MessageCodes.ERROR_SCHEMA_INVALID + "Json Processing Error " + e); } } - private void removedRuleModifiedGroup(String controllerName){ - // This will be sending Notification to PDPD directly to Lock - ControllerPOJO controllerPOJO = new ControllerPOJO(); - controllerPOJO.setName(controllerName); - controllerPOJO.setOperation("lock"); - List<ControllerPOJO> controllers = new ArrayList<>(); - controllers.add(controllerPOJO); - sendNotification(controllers); - } - - private void sendNotification(List<ControllerPOJO> controllers){ - NotificationPOJO notification = new NotificationPOJO(); - String requestId = UUID.randomUUID().toString(); - LOGGER.info("Generating notification RequestID : " + requestId); - notification.setRequestID(requestId); - notification.setEntity("controller"); - notification.setControllers(controllers); - try { - String notificationJson = PolicyUtils.objectToJsonString(notification); - LOGGER.info("Sending Notification :\n" + notificationJson); - sendMessage(notificationJson); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while sending notification to PDP-D " + e.getMessage()); - } - } - - private void sendMessage(String message) throws IOException, GeneralSecurityException, InterruptedException { - - if("dmaap".equalsIgnoreCase(notificationType)) { - // Sending Message through DMaaP Message Router - LOGGER.debug("DMAAP Publishing Message"); - - publisher.send( "MyPartitionKey", message); - - LOGGER.debug("Message Published on DMaaP :" + dmaapList.get(0) + "for Topic: " + pubTopic); - - Thread.sleep(dmaapDelay); - publisher.close(); - } else { - // Sending Message through UEB interface. - LOGGER.debug("UEB Publishing Message"); - - CambriaBatchingPublisher pub = pubBuilder.build(); - pub.send( "MyPartitionKey", message); - - final List<?> stuck = pub.close ( uebDelay, TimeUnit.SECONDS ); - if ( stuck.size () > 0 ) { - LOGGER.error ( stuck.size() + " messages unsent" ); - }else { - LOGGER.debug ( "Clean exit; Message Published on UEB : " + uebList + "for Topic: " + pubTopic ); - } - } - - } - - private void createPom(String name) { + private void removedRuleModifiedGroup(String controllerName) { + // This will be sending Notification to PDPD directly to Lock + ControllerPOJO controllerPOJO = new ControllerPOJO(); + controllerPOJO.setName(controllerName); + controllerPOJO.setOperation("lock"); + List<ControllerPOJO> controllers = new ArrayList<>(); + controllers.add(controllerPOJO); + sendNotification(controllers); + } + + private void sendNotification(List<ControllerPOJO> controllers) { + NotificationPOJO notification = new NotificationPOJO(); + String requestId = UUID.randomUUID().toString(); + LOGGER.info("Generating notification RequestID : " + requestId); + notification.setRequestID(requestId); + notification.setEntity("controller"); + notification.setControllers(controllers); + try { + String notificationJson = PolicyUtils.objectToJsonString(notification); + LOGGER.info("Sending Notification :\n" + notificationJson); + sendMessage(notificationJson); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while sending notification to PDP-D " + + e.getMessage(), e); + } + } + + private void sendMessage(String message) throws IOException, GeneralSecurityException, InterruptedException { + + if ("dmaap".equalsIgnoreCase(notificationType)) { + // Sending Message through DMaaP Message Router + LOGGER.debug("DMAAP Publishing Message"); + + publisher.send("MyPartitionKey", message); + + LOGGER.debug("Message Published on DMaaP :" + dmaapList.get(0) + "for Topic: " + pubTopic); + + Thread.sleep(dmaapDelay); + publisher.close(); + } else { + // Sending Message through UEB interface. + LOGGER.debug("UEB Publishing Message"); + + CambriaBatchingPublisher pub = pubBuilder.build(); + pub.send("MyPartitionKey", message); + + final List<?> stuck = pub.close(uebDelay, TimeUnit.SECONDS); + if (stuck.size() > 0) { + LOGGER.error(stuck.size() + " messages unsent"); + } else { + LOGGER.debug("Clean exit; Message Published on UEB : " + uebList + "for Topic: " + pubTopic); + } + } + + } + + private void createPom(String name) { Model model = new Model(); model.setModelVersion("4.0.0"); model.setGroupId(getGroupID(name)); model.setArtifactId(getArtifactID(name)); model.setVersion(getVersion(name)); model.setName(name); - DistributionManagement distributionManagement = new DistributionManagement(); - DeploymentRepository repository = new DeploymentRepository(); - repository.setId(repID); - repository.setName(repName); - repository.setUrl(repURLs.get(0)); - distributionManagement.setRepository(repository); - model.setDistributionManagement(distributionManagement); - // Dependency Management goes here. - List<Dependency> dependencyList= new ArrayList<>(); - if(groupMap.get(name).size()>1){ - @SuppressWarnings("unchecked") + DistributionManagement distributionManagement = new DistributionManagement(); + DeploymentRepository repository = new DeploymentRepository(); + repository.setId(repID); + repository.setName(repName); + repository.setUrl(repURLs.get(0)); + distributionManagement.setRepository(repository); + model.setDistributionManagement(distributionManagement); + // Dependency Management goes here. + List<Dependency> dependencyList = new ArrayList<>(); + if (groupMap.get(name).size() > 1) { + @SuppressWarnings("unchecked") ArrayList<PEDependency> dependencies = (ArrayList<PEDependency>) groupMap.get(name).get(1); - for(PEDependency dependency: dependencies){ + for (PEDependency dependency : dependencies) { dependencyList.add(dependency.getDependency()); } - }else{ - // Add Default dependencies. - dependencyList = getDependencies(name); + } else { + // Add Default dependencies. + dependencyList = getDependencies(name); + } + model.setDependencies(dependencyList); + Writer writer = null; + try { + writer = WriterFactory.newXmlWriter( + new File(PROJECTSLOCATION + File.separator + getArtifactID(name) + File.separator + "pom.xml")); + MavenXpp3Writer pomWriter = new MavenXpp3Writer(); + pomWriter.write(writer, model); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while creating POM for " + getArtifactID(name) + + e.getMessage(), e); + } finally { + IOUtil.close(writer); + } + } + + private List<Dependency> getDependencies(String controllerName) { + // Read the Dependency Information from property file. + Path file = Paths.get(DEPENDENCY_FILE); + if (!Files.notExists(file)) { + try { + String dependencyJSON = new String(Files.readAllBytes(file), StandardCharsets.UTF_8); + DependencyInfo dependencyInfo = PolicyUtils.jsonStringToObject(dependencyJSON, DependencyInfo.class); + String controller = "default"; + if (dependencyInfo.getDependencies().containsKey(controllerName)) { + controller = controllerName; + } + List<Dependency> dependencyList = new ArrayList<>(); + for (PEDependency dependency : dependencyInfo.getDependencies().get(controller)) { + dependencyList.add(dependency.getDependency()); + } + return dependencyList; + } catch (IOException | NullPointerException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error while getting dependecy Information for controller: " + controllerName + + e.getMessage(), e); + } } - model.setDependencies(dependencyList); - Writer writer = null; - try{ - writer = WriterFactory.newXmlWriter(new File(PROJECTSLOCATION - + File.separator + getArtifactID(name) + File.separator - + "pom.xml")); - MavenXpp3Writer pomWriter = new MavenXpp3Writer(); - pomWriter.write(writer, model); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error while creating POM for " + getArtifactID(name) - + e.getMessage()); - }finally{ - IOUtil.close(writer); - } - } - - private List<Dependency> getDependencies(String controllerName) { - // Read the Dependency Information from property file. - Path file = Paths.get(DEPENDENCY_FILE); - if(!Files.notExists(file)){ - try { - String dependencyJSON = new String(Files.readAllBytes(file), StandardCharsets.UTF_8); - DependencyInfo dependencyInfo = PolicyUtils.jsonStringToObject(dependencyJSON, DependencyInfo.class); - String controller = "default"; - if(dependencyInfo.getDependencies().containsKey(controllerName)){ - controller = controllerName; - } - List<Dependency> dependencyList = new ArrayList<>(); - for(PEDependency dependency: dependencyInfo.getDependencies().get(controller)){ - dependencyList.add(dependency.getDependency()); - } - return dependencyList; - } catch (IOException| NullPointerException e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error while getting dependecy Information for controller: " + controllerName - + e.getMessage()); - } - } - return defaultDependencies(controllerName); - } - - // Default Dependency Section. Can be changed as required. - public List<Dependency> defaultDependencies(String controllerName) { - - List<Dependency> dependencyList = new ArrayList<>(); - String version= StringEscapeUtils.escapeJava(brmsdependencyversion); - - Dependency demoDependency = new Dependency(); - demoDependency.setGroupId("org.onap.policy.drools-applications"); - demoDependency.setArtifactId("demo"); - demoDependency.setVersion(version); - dependencyList.add(demoDependency); - - Dependency controlloopDependency = new Dependency(); - controlloopDependency.setGroupId("org.onap.policy.drools-applications"); - controlloopDependency.setArtifactId("events"); - controlloopDependency.setVersion(version); - dependencyList.add(controlloopDependency); - - Dependency restDependency = new Dependency(); - restDependency.setGroupId("org.onap.policy.drools-applications"); - restDependency.setArtifactId("rest"); - restDependency.setVersion(version); - dependencyList.add(restDependency); - - Dependency appcDependency = new Dependency(); - appcDependency.setGroupId("org.onap.policy.drools-applications"); - appcDependency.setArtifactId("appc"); - appcDependency.setVersion(version); - dependencyList.add(appcDependency); - - Dependency aaiDependency = new Dependency(); - aaiDependency.setGroupId("org.onap.policy.drools-applications"); - aaiDependency.setArtifactId("aai"); - aaiDependency.setVersion(version); - dependencyList.add(aaiDependency); - - Dependency msoDependency = new Dependency(); - msoDependency.setGroupId("org.onap.policy.drools-applications"); - msoDependency.setArtifactId("mso"); - msoDependency.setVersion(version); - dependencyList.add(msoDependency); - - Dependency trafficgeneratorDependency = new Dependency(); - trafficgeneratorDependency.setGroupId("org.onap.policy.drools-applications"); - trafficgeneratorDependency.setArtifactId("trafficgenerator"); - trafficgeneratorDependency.setVersion(version); - dependencyList.add(trafficgeneratorDependency); - return dependencyList; - } - - private void createProject(String path,String ksessionName){ - new File(path+File.separator+"rules").mkdirs(); - new File(path+File.separator+"META-INF").mkdirs(); - if(!Files.exists(Paths.get(path+File.separator+"META-INF"+File.separator+"kmodule.xml"))){ - // Hard coding XML for PDP Drools to accept our Rules. - String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "\n"+ - "<kmodule xmlns=\"http://jboss.org/kie/6.0.0/kmodule\">" +"\n"+ - "<kbase name=\"rules\" packages=\"rules\">" + "\n" + - "<ksession name=\""+ ksessionName +"\"/>"+ "\n" + - "</kbase></kmodule>"; - copyDataToFile(path+File.separator+"META-INF"+File.separator+"kmodule.xml", xml); - } - } - - private void copyDataToFile(String file, String rule) { - try{ - FileUtils.writeStringToFile(new File(file), rule); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Error while creating Rule for " + file + e.getMessage()); - } - } - - private void readGroups(Properties config) throws PolicyException{ - String[] groupNames = null; - if(config.getProperty("groupNames").contains(",")){ - groupNames = config.getProperty("groupNames").replaceAll(" ", "").split(","); - }else{ - groupNames = new String[]{config.getProperty("groupNames").replaceAll(" ", "")}; - } - if(groupNames==null || groupNames.length==0){ - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "groupNames property is missing or empty from the property file "); - throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + "groupNames property is missing or empty from the property file "); - } - groupMap = new HashMap<>(); - for(int counter=0; counter < groupNames.length ;counter++){ - String name = groupNames[counter]; - String groupID = config.getProperty(name+".groupID"); - if(groupID==null){ - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + name+".groupID property is missing from the property file "); - throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + name+".groupID property is missing from the property file "); - } - String artifactID = config.getProperty(name+".artifactID"); - if(artifactID==null){ - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + name+".artifactID property is missing from the property file "); - throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + name+".artifactID property is missing from the property file "); - } - PEDependency dependency = new PEDependency(); - dependency.setArtifactId(artifactID); - dependency.setGroupId(groupID); - // Add to list if we got all - addToGroup(name,dependency); - } - } - - private void addToGroup(String name, PEDependency dependency) { - ArrayList<Object> values = new ArrayList<>(); + return defaultDependencies(controllerName); + } + + // Default Dependency Section. Can be changed as required. + public List<Dependency> defaultDependencies(String controllerName) { + + List<Dependency> dependencyList = new ArrayList<>(); + String version = StringEscapeUtils.escapeJava(brmsdependencyversion); + + Dependency demoDependency = new Dependency(); + demoDependency.setGroupId("org.onap.policy.drools-applications"); + demoDependency.setArtifactId("demo"); + demoDependency.setVersion(version); + dependencyList.add(demoDependency); + + Dependency controlloopDependency = new Dependency(); + controlloopDependency.setGroupId("org.onap.policy.drools-applications"); + controlloopDependency.setArtifactId("events"); + controlloopDependency.setVersion(version); + dependencyList.add(controlloopDependency); + + Dependency restDependency = new Dependency(); + restDependency.setGroupId("org.onap.policy.drools-applications"); + restDependency.setArtifactId("rest"); + restDependency.setVersion(version); + dependencyList.add(restDependency); + + Dependency appcDependency = new Dependency(); + appcDependency.setGroupId("org.onap.policy.drools-applications"); + appcDependency.setArtifactId("appc"); + appcDependency.setVersion(version); + dependencyList.add(appcDependency); + + Dependency aaiDependency = new Dependency(); + aaiDependency.setGroupId("org.onap.policy.drools-applications"); + aaiDependency.setArtifactId("aai"); + aaiDependency.setVersion(version); + dependencyList.add(aaiDependency); + + Dependency msoDependency = new Dependency(); + msoDependency.setGroupId("org.onap.policy.drools-applications"); + msoDependency.setArtifactId("mso"); + msoDependency.setVersion(version); + dependencyList.add(msoDependency); + + Dependency trafficgeneratorDependency = new Dependency(); + trafficgeneratorDependency.setGroupId("org.onap.policy.drools-applications"); + trafficgeneratorDependency.setArtifactId("trafficgenerator"); + trafficgeneratorDependency.setVersion(version); + dependencyList.add(trafficgeneratorDependency); + return dependencyList; + } + + private void createProject(String path, String ksessionName) { + new File(path + File.separator + "rules").mkdirs(); + new File(path + File.separator + "META-INF").mkdirs(); + if (!Files.exists(Paths.get(path + File.separator + "META-INF" + File.separator + "kmodule.xml"))) { + // Hard coding XML for PDP Drools to accept our Rules. + String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "\n" + + "<kmodule xmlns=\"http://jboss.org/kie/6.0.0/kmodule\">" + "\n" + + "<kbase name=\"rules\" packages=\"rules\">" + "\n" + "<ksession name=\"" + ksessionName + "\"/>" + + "\n" + "</kbase></kmodule>"; + copyDataToFile(path + File.separator + "META-INF" + File.separator + "kmodule.xml", xml); + } + } + + private void copyDataToFile(String file, String rule) { + try { + FileUtils.writeStringToFile(new File(file), rule); + } catch (Exception e) { + LOGGER.error( + XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while creating Rule for " + file + e.getMessage(), + e); + } + } + + private void readGroups(Properties config) throws PolicyException { + String[] groupNames = null; + if (config.getProperty("groupNames").contains(",")) { + groupNames = config.getProperty("groupNames").replaceAll(" ", "").split(","); + } else { + groupNames = new String[] { config.getProperty("groupNames").replaceAll(" ", "") }; + } + if (groupNames == null || groupNames.length == 0) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + + "groupNames property is missing or empty from the property file "); + throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + + "groupNames property is missing or empty from the property file "); + } + groupMap = new HashMap<>(); + for (int counter = 0; counter < groupNames.length; counter++) { + String name = groupNames[counter]; + String groupID = config.getProperty(name + ".groupID"); + if (groupID == null) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + name + + ".groupID property is missing from the property file "); + throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + name + + ".groupID property is missing from the property file "); + } + String artifactID = config.getProperty(name + ".artifactID"); + if (artifactID == null) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + name + + ".artifactID property is missing from the property file "); + throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + name + + ".artifactID property is missing from the property file "); + } + PEDependency dependency = new PEDependency(); + dependency.setArtifactId(artifactID); + dependency.setGroupId(groupID); + // Add to list if we got all + addToGroup(name, dependency); + } + } + + private void addToGroup(String name, PEDependency dependency) { + ArrayList<Object> values = new ArrayList<>(); values.add(dependency); - groupMap.put(name, values); - EntityTransaction et = em.getTransaction(); - et.begin(); - Query query = em.createQuery("select b from BRMSGroupInfo as b where b.controllerName = :cn"); - query.setParameter("cn", name); - List<?> groupList = query.getResultList(); - BRMSGroupInfo brmsGroupInfo = null; - if(groupList.size()>0){ - LOGGER.info("Controller name already Existing in DB. Will be updating the DB Values" + name); - brmsGroupInfo = (BRMSGroupInfo) groupList.get(0); - } - if(brmsGroupInfo==null){ - brmsGroupInfo = new BRMSGroupInfo(); - } - brmsGroupInfo.setControllerName(name); - brmsGroupInfo.setGroupId(dependency.getGroupId()); - brmsGroupInfo.setArtifactId(dependency.getArtifactId()); - brmsGroupInfo.setVersion(dependency.getVersion()); - em.persist(brmsGroupInfo); - em.flush(); - et.commit(); - } - - private String getArtifactID(String name){ + groupMap.put(name, values); + EntityTransaction et = em.getTransaction(); + et.begin(); + Query query = em.createQuery("select b from BRMSGroupInfo as b where b.controllerName = :cn"); + query.setParameter("cn", name); + List<?> groupList = query.getResultList(); + BRMSGroupInfo brmsGroupInfo = null; + if (groupList.size() > 0) { + LOGGER.info("Controller name already Existing in DB. Will be updating the DB Values" + name); + brmsGroupInfo = (BRMSGroupInfo) groupList.get(0); + } + if (brmsGroupInfo == null) { + brmsGroupInfo = new BRMSGroupInfo(); + } + brmsGroupInfo.setControllerName(name); + brmsGroupInfo.setGroupId(dependency.getGroupId()); + brmsGroupInfo.setArtifactId(dependency.getArtifactId()); + brmsGroupInfo.setVersion(dependency.getVersion()); + em.persist(brmsGroupInfo); + em.flush(); + et.commit(); + } + + private String getArtifactID(String name) { return ((PEDependency) groupMap.get(name).get(0)).getArtifactId(); } - - private String getGroupID(String name){ + + private String getGroupID(String name) { return ((PEDependency) groupMap.get(name).get(0)).getGroupId(); } - - private String getVersion(String name){ + + private String getVersion(String name) { return ((PEDependency) groupMap.get(name).get(0)).getVersion(); } private void getNameAndSetRemove(String controllerName, String policyName) { String artifactName = getArtifactID(controllerName); - String ruleFolder= PROJECTSLOCATION + File.separator - + artifactName + File.separator + "src" - + File.separator + "main" + File.separator - + "resources" + File.separator + "rules"; - File file = new File(ruleFolder+File.separator+ policyName +".drl"); - if(file.delete()){ - LOGGER.info("Deleted File.. " + file.getAbsolutePath()); - removePolicyFromGroup(policyName, controllerName); + String ruleFolder = PROJECTSLOCATION + File.separator + artifactName + File.separator + "src" + File.separator + + "main" + File.separator + "resources" + File.separator + "rules"; + File file = new File(ruleFolder + File.separator + policyName + ".drl"); + if (file.delete()) { + LOGGER.info("Deleted File.. " + file.getAbsolutePath()); + removePolicyFromGroup(policyName, controllerName); } - if(new File(ruleFolder).listFiles().length == 0) { + if (new File(ruleFolder).listFiles().length == 0) { removedRuleModifiedGroup(controllerName); } else { // This is an update in terms of PDPD. addModifiedGroup(controllerName, "update"); } } - - // Removes Policy from Memory and Database. - private void removePolicyFromGroup(String policyName, String controllerName) { - policyMap.remove(policyName); - EntityTransaction et = em.getTransaction(); - et.begin(); - Query query = em.createQuery("select b from BRMSPolicyInfo as b where b.policyName = :pn"); - query.setParameter("pn", policyName); - List<?> pList = query.getResultList(); - BRMSPolicyInfo brmsPolicyInfo = new BRMSPolicyInfo(); - if(pList.size()>0){ - // Already exists. - brmsPolicyInfo = (BRMSPolicyInfo) pList.get(0); - if(brmsPolicyInfo.getControllerName().getControllerName().equals(controllerName)){ - em.remove(brmsPolicyInfo); - em.flush(); - } - } - et.commit(); - } - - private void setVersion(String newVersion, String controllerName) { + + // Removes Policy from Memory and Database. + private void removePolicyFromGroup(String policyName, String controllerName) { + policyMap.remove(policyName); + EntityTransaction et = em.getTransaction(); + et.begin(); + Query query = em.createQuery("select b from BRMSPolicyInfo as b where b.policyName = :pn"); + query.setParameter("pn", policyName); + List<?> pList = query.getResultList(); + BRMSPolicyInfo brmsPolicyInfo = new BRMSPolicyInfo(); + if (pList.size() > 0) { + // Already exists. + brmsPolicyInfo = (BRMSPolicyInfo) pList.get(0); + if (brmsPolicyInfo.getControllerName().getControllerName().equals(controllerName)) { + em.remove(brmsPolicyInfo); + em.flush(); + } + } + et.commit(); + } + + private void setVersion(String newVersion, String controllerName) { PEDependency userController = (PEDependency) groupMap.get(controllerName).get(0); userController.setVersion(newVersion); groupMap.get(controllerName).set(0, userController); } - // Return BackUpMonitor - public static BackUpMonitor getBackUpMonitor(){ - return bm; - } - - public void rotateURLs() { - if(repURLs!=null){ - Collections.rotate(repURLs, -1); - } - } - - public int URLListSize() { - if(repURLs!=null){ - return repURLs.size(); - }else return 0; - } + // Return BackUpMonitor + public static BackUpMonitor getBackUpMonitor() { + return bm; + } + + public void rotateURLs() { + if (repURLs != null) { + Collections.rotate(repURLs, -1); + } + } + + public int URLListSize() { + if (repURLs != null) { + return repURLs.size(); + } else + return 0; + } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java index 53d801b5b..e11538c4e 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java @@ -128,10 +128,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList * The CopyOnWriteArrayList *should* protect from concurrency errors. * This list is seldom changed but often read, so the costs of this approach make sense. */ - private static final CopyOnWriteArrayList<String> adminConsoleURLStringList = new CopyOnWriteArrayList<String>(); + private static final CopyOnWriteArrayList<String> adminConsoleURLStringList = new CopyOnWriteArrayList<>(); - private static String CONFIG_HOME; - private static String ACTION_HOME; + private static String configHome; + private static String actionHome; /* * This PAP instance's own URL. * Need this when creating URLs to send to the PDPs so they can GET the Policy files from this process. @@ -155,26 +155,13 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList private static String papDbUrl = null; private static String papDbUser = null; private static String papDbPassword = null; - private static Integer papTransWait = null; - private static Integer papTransTimeout = null; - private static Integer papAuditTimeout = null; - private static Boolean papAuditFlag = null; - private static Boolean papFileSystemAudit = null; private static String papResourceName = null; - private static Integer fpMonitorInterval = null; - private static Integer failedCounterThreshold = null; - private static Integer testTransInterval = null; - private static Integer writeFpcInterval = null; - private static String papSiteName=null; - private static String papNodeType=null; - private static String papDependencyGroups = null; private static String[] papDependencyGroupsFlatArray = null; private static String environment = null; private static String pdpFile = null; - private String storedRequestId = null; - private IntegrityMonitor im; - private IntegrityAudit ia; + private transient IntegrityMonitor im; + private transient IntegrityAudit ia; //MicroService Model Properties private static String msOnapName; @@ -183,8 +170,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList * This thread may be invoked upon startup to initiate sending PDP policy/pip configuration when * this servlet starts. Its configurable by the admin. */ - private Thread initiateThread = null; - private ONAPLoggingContext baseLoggingContext = null; + private transient static Thread initiateThread = null; + private transient ONAPLoggingContext baseLoggingContext = null; /** * @see HttpServlet#HttpServlet() @@ -205,7 +192,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList String hostname = InetAddress.getLocalHost().getCanonicalHostName(); baseLoggingContext.setServer(hostname); } catch (UnknownHostException e) { - LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get hostname for logging"); + LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get hostname for logging", e); } // Initialize XACMLRest.xacmlInit(config); @@ -214,87 +201,36 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList /* * Retrieve the property values */ - CONFIG_HOME = getConfigHome(); - ACTION_HOME = getActionHome(); - papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER); - if(papDbDriver == null){ - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbDriver property entry"); - throw new PAPException("papDbDriver is null"); - } - setPapDbDriver(papDbDriver); - papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL); - if(papDbUrl == null){ - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUrl property entry"); - throw new PAPException("papDbUrl is null"); - } - setPapDbUrl(papDbUrl); - papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER); - if(papDbUser == null){ - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUser property entry"); - throw new PAPException("papDbUser is null"); - } - setPapDbUser(papDbUser); - papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD); - if(papDbPassword == null){ - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbPassword property entry"); - throw new PAPException("papDbPassword is null"); - } - setPapDbPassword(papDbPassword); - papResourceName = XACMLProperties.getProperty(XACMLRestProperties.PAP_RESOURCE_NAME); - if(papResourceName == null){ - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papResourceName property entry"); - throw new PAPException("papResourceName is null"); - } - papSiteName = XACMLProperties.getProperty(XACMLRestProperties.PAP_SITE_NAME); + setCommonProperties(); + String papSiteName = XACMLProperties.getProperty(XACMLRestProperties.PAP_SITE_NAME); if(papSiteName == null){ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papSiteName property entry"); throw new PAPException("papSiteName is null"); } - papNodeType = XACMLProperties.getProperty(XACMLRestProperties.PAP_NODE_TYPE); + String papNodeType = XACMLProperties.getProperty(XACMLRestProperties.PAP_NODE_TYPE); if(papNodeType == null){ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papNodeType property entry"); throw new PAPException("papNodeType is null"); } - environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL"); //Integer will throw an exception of anything is missing or unrecognized - papTransWait = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT)); - papTransTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)); - papAuditTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT)); + int papTransWait = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT)); + int papTransTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)); + int papAuditTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT)); //Boolean will default to false if anything is missing or unrecognized - papAuditFlag = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG)); - papFileSystemAudit = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_FLAG)); - papDependencyGroups = XACMLProperties.getProperty(XACMLRestProperties.PAP_DEPENDENCY_GROUPS); + boolean papAuditFlag = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG)); + boolean papFileSystemAudit = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_FLAG)); + String papDependencyGroups = XACMLProperties.getProperty(XACMLRestProperties.PAP_DEPENDENCY_GROUPS); if(papDependencyGroups == null){ throw new PAPException("papDependencyGroups is null"); } - try{ - //Now we have flattened the array into a simple comma-separated list - papDependencyGroupsFlatArray = papDependencyGroups.split("[;,]"); - //clean up the entries - for (int i = 0 ; i < papDependencyGroupsFlatArray.length ; i ++){ - papDependencyGroupsFlatArray[i] = papDependencyGroupsFlatArray[i].trim(); - } - try{ - if(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS) != null){ - papIntegrityAuditPeriodSeconds = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS).trim()); - } - }catch(Exception e){ - String msg = "integrity_audit_period_seconds "; - LOGGER.error("\n\nERROR: " + msg + "Bad property entry: " + e.getMessage() + "\n"); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: " + msg +"Bad property entry"); - throw e; - } - }catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry"); - throw e; - } + setPAPDependencyGroups(papDependencyGroups); //Integer will throw an exception of anything is missing or unrecognized - fpMonitorInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FP_MONITOR_INTERVAL)); - failedCounterThreshold = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD)); - testTransInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.TEST_TRANS_INTERVAL)); - writeFpcInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.WRITE_FPC_INTERVAL)); + int fpMonitorInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FP_MONITOR_INTERVAL)); + int failedCounterThreshold = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD)); + int testTransInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.TEST_TRANS_INTERVAL)); + int writeFpcInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.WRITE_FPC_INTERVAL)); LOGGER.debug("\n\n\n**************************************" - + "\n**************************************" + + "\n*************************************" + "\n" + "\n papDbDriver = " + papDbDriver + "\n papDbUrl = " + papDbUrl @@ -314,7 +250,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList + "\n papNodeType = " + papNodeType + "\n papDependencyGroupsList = " + papDependencyGroups + "\n papIntegrityAuditPeriodSeconds = " + papIntegrityAuditPeriodSeconds - + "\n\n**************************************" + + "\n\n*************************************" + "\n**************************************"); // Pull custom persistence settings Properties properties; @@ -330,39 +266,22 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList + "XACMLProperties.getProperties()"); throw new ServletException(e.getMessage(), e.getCause()); } - //Micro Service Properties - msOnapName=properties.getProperty("xacml.policy.msOnapName"); - setMsOnapName(msOnapName); - msPolicyName=properties.getProperty("xacml.policy.msPolicyName"); - setMsPolicyName(msPolicyName); - // PDPId File location - XACMLPapServlet.pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE); - if (XACMLPapServlet.pdpFile == null) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " The PDP Id Authentication File Property is not valid: " - + XACMLRestProperties.PROP_PDP_IDFILE); - throw new PAPException("The PDP Id Authentication File Property :"+ XACMLRestProperties.PROP_PDP_IDFILE+ " is not Valid. "); - } // Create an IntegrityMonitor im = IntegrityMonitor.getInstance(papResourceName,properties); // Create an IntegrityAudit ia = new IntegrityAudit(papResourceName, AUDIT_PAP_PERSISTENCE_UNIT, properties); ia.startAuditThread(); // Create the entity manager factory - emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, properties); - if (emf == null) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager factory with persistence unit: " - + PERSISTENCE_UNIT); - throw new ServletException("Unable to create Entity Manager Factory"); - } + setEMF(properties); // we are about to call the PDPs and give them their configuration. // To do that we need to have the URL of this PAP so we can construct the Policy file URLs - XACMLPapServlet.papURL = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); + setPAPURL(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL)); //Create the policyDBDao - policyDBDao = PolicyDBDao.getPolicyDBDaoInstance(getEmf()); + setPolicyDBDao(); // Load our PAP engine, first create a factory ONAPPapEngineFactory factory = ONAPPapEngineFactory.newInstance(XACMLProperties.getProperty(XACMLProperties.PROP_PAP_PAPENGINEFACTORY)); // The factory knows how to go about creating a PAP Engine - XACMLPapServlet.papEngine = (PAPPolicyEngine) factory.newEngine(); + setPAPEngine((PAPPolicyEngine) factory.newEngine()); PolicyDBDaoTransaction addNewGroup = null; try{ if(((org.onap.policy.xacml.std.pap.StdEngine)papEngine).wasDefaultGroupJustAdded){ @@ -381,7 +300,6 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } } policyDBDao.setPapEngine((PAPPolicyEngine) XACMLPapServlet.papEngine); - //boolean performFileToDatabaseAudit = false; if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG))){ //get an AuditTransaction to lock out all other transactions PolicyDBDaoTransaction auditTrans = policyDBDao.getNewAuditTransaction(); @@ -397,13 +315,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // Configurable - have the PAP servlet initiate sending the latest PDP policy/pip configuration // to all its known PDP nodes. if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_INITIATE_PDP_CONFIG))) { - this.initiateThread = new Thread(this); - this.initiateThread.start(); + startInitiateThreadService(new Thread(this)); } // After startup, the PAP does Heartbeat's to each of the PDPs periodically - XACMLPapServlet.heartbeat = new Heartbeat((PAPPolicyEngine) XACMLPapServlet.papEngine); - XACMLPapServlet.heartbeatThread = new Thread(XACMLPapServlet.heartbeat); - XACMLPapServlet.heartbeatThread.start(); + startHeartBeatService(new Heartbeat((PAPPolicyEngine) XACMLPapServlet.papEngine)); } catch (FactoryException | PAPException e) { PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine"); @@ -414,7 +329,114 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } } - /** + private static void startInitiateThreadService(Thread thread) { + initiateThread = thread; + initiateThread.start(); + } + + private static void startHeartBeatService(Heartbeat heartbeat) { + XACMLPapServlet.heartbeat = heartbeat; + XACMLPapServlet.heartbeatThread = new Thread(XACMLPapServlet.heartbeat); + XACMLPapServlet.heartbeatThread.start(); + } + + private static void setPolicyDBDao() throws ServletException { + try { + policyDBDao = PolicyDBDao.getPolicyDBDaoInstance(getEmf()); + } catch (Exception e) { + throw new ServletException("Unable to Create Policy DBDao Instance",e); + } + } + + private static void setEMF(Properties properties) throws ServletException { + emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, properties); + if (emf == null) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager factory with persistence unit: " + + PERSISTENCE_UNIT); + throw new ServletException("Unable to create Entity Manager Factory"); + } + } + + private static void setPAPURL(String papURL) { + XACMLPapServlet.papURL = papURL; + } + + private static void setPAPEngine(PAPPolicyEngine newEngine) { + XACMLPapServlet.papEngine = newEngine; + } + + private static void setPAPDependencyGroups(String papDependencyGroups) throws PAPException { + try{ + //Now we have flattened the array into a simple comma-separated list + papDependencyGroupsFlatArray = papDependencyGroups.split("[;,]"); + //clean up the entries + for (int i = 0 ; i < papDependencyGroupsFlatArray.length ; i ++){ + papDependencyGroupsFlatArray[i] = papDependencyGroupsFlatArray[i].trim(); + } + try{ + if(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS) != null){ + papIntegrityAuditPeriodSeconds = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS).trim()); + } + }catch(Exception e){ + String msg = "integrity_audit_period_seconds "; + LOGGER.error("\n\nERROR: " + msg + "Bad property entry: " + e.getMessage() + "\n"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: " + msg +"Bad property entry"); + throw e; + } + }catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry"); + throw new PAPException(e); + } + } + + private static void setCommonProperties() throws PAPException { + setConfigHome(); + setActionHome(); + papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER); + if(papDbDriver == null){ + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbDriver property entry"); + throw new PAPException("papDbDriver is null"); + } + setPapDbDriver(papDbDriver); + papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL); + if(papDbUrl == null){ + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUrl property entry"); + throw new PAPException("papDbUrl is null"); + } + setPapDbUrl(papDbUrl); + papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER); + if(papDbUser == null){ + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUser property entry"); + throw new PAPException("papDbUser is null"); + } + setPapDbUser(papDbUser); + papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD); + if(papDbPassword == null){ + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbPassword property entry"); + throw new PAPException("papDbPassword is null"); + } + setPapDbPassword(papDbPassword); + papResourceName = XACMLProperties.getProperty(XACMLRestProperties.PAP_RESOURCE_NAME); + if(papResourceName == null){ + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papResourceName property entry"); + throw new PAPException("papResourceName is null"); + } + environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL"); + //Micro Service Properties + msOnapName=XACMLProperties.getProperty("xacml.policy.msOnapName"); + setMsOnapName(msOnapName); + msPolicyName=XACMLProperties.getProperty("xacml.policy.msPolicyName"); + setMsPolicyName(msPolicyName); + // PDPId File location + XACMLPapServlet.pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE); + if (XACMLPapServlet.pdpFile == null) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " The PDP Id Authentication File Property is not valid: " + + XACMLRestProperties.PROP_PDP_IDFILE); + throw new PAPException("The PDP Id Authentication File Property :"+ XACMLRestProperties.PROP_PDP_IDFILE+ " is not Valid. "); + } + } + + /** * Thread used only during PAP startup to initiate change messages to all known PDPs. * This must be on a separate thread so that any GET requests from the PDPs during this update can be serviced. */ @@ -430,6 +452,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList * Depending on how this servlet is run, we may or may not care about cleaning up the resources. * For now we assume that we do care. */ + @Override public void destroy() { // Make sure our threads are destroyed if (XACMLPapServlet.heartbeatThread != null) { @@ -441,14 +464,16 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList XACMLPapServlet.heartbeatThread.interrupt(); XACMLPapServlet.heartbeatThread.join(); } catch (InterruptedException e) { + XACMLPapServlet.heartbeatThread.interrupt(); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping heartbeat"); } } - if (this.initiateThread != null) { + if (initiateThread != null) { try { - this.initiateThread.interrupt(); - this.initiateThread.join(); + initiateThread.interrupt(); + initiateThread.join(); } catch (InterruptedException e) { + initiateThread.interrupt(); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping thread"); } } @@ -479,21 +504,19 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList String message = "POST interface called for PAP " + papResourceName + " but it has an Administrative" + " state of " + im.getStateManager().getAdminState() + "\n Exception Message: " + ae.getMessage(); - LOGGER.info(message); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); + LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, ae); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); return; }catch (StandbyStatusException se) { String message = "POST interface called for PAP " + papResourceName + " but it has a Standby Status" + " of " + im.getStateManager().getStandbyStatus() + "\n Exception Message: " + se.getMessage(); - LOGGER.info(message); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); + LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, se); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + setResponseError(response,HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); return; } try { @@ -649,7 +672,16 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList im.endTransaction(); } - /** + private void setResponseError(HttpServletResponse response,int responseCode, String message) { + try { + response.sendError(responseCode, message); + } catch (IOException e) { + LOGGER.error("Error setting Error response Header ", e); + } + return; + } + + /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { @@ -827,7 +859,6 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList */ protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); - storedRequestId = loggingContext.getRequestID(); loggingContext.transactionStarted(); loggingContext.setServiceName("PAP.put"); if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){ @@ -1269,7 +1300,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList if (policy != null && ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) { PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance(); - if (pushPolicyHandler.preSafetyCheck(policy, CONFIG_HOME)) { + if (pushPolicyHandler.preSafetyCheck(policy, configHome)) { LOGGER.debug("Precheck Successful."); } } @@ -1813,7 +1844,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance(); OnapPDPGroup updatedGroup = (StdPDPGroup)objectFromJSON; - if (pushPolicyHandler.preSafetyCheck(updatedGroup, CONFIG_HOME)) { + if (pushPolicyHandler.preSafetyCheck(updatedGroup, configHome)) { LOGGER.debug("Precheck Successful."); } @@ -2196,7 +2227,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // kick off a thread to do an event notification for each PDP. // This needs to be on a separate thread so that PDPs that do not respond (down, non-existent, etc) // do not block the PSP response to the AC, which would freeze the GUI until all PDPs sequentially respond or time-out. - Thread t = new Thread(new UpdatePDPThread(pdp, storedRequestId)); + Thread t = new Thread(new UpdatePDPThread(pdp)); if(CheckPDP.validateID(pdp.getId())){ t.start(); } @@ -2206,9 +2237,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList private OnapPDP pdp; private String requestId; - public UpdatePDPThread(OnapPDP pdp, String storedRequestId) { + public UpdatePDPThread(OnapPDP pdp) { this.pdp = pdp; - requestId = storedRequestId; } public void run() { @@ -2246,7 +2276,6 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } connection.setRequestProperty("Content-Type", "text/x-java-properties"); connection.setRequestProperty("X-ECOMP-RequestID", loggingContext.getRequestID()); - storedRequestId = null; connection.setInstanceFollowRedirects(true); connection.setDoOutput(true); try (OutputStream os = connection.getOutputStream()) { @@ -2474,7 +2503,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } private static void loadWebapps() throws PAPException{ - if(ACTION_HOME == null || CONFIG_HOME == null){ + if(actionHome == null || configHome == null){ Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS)); //Sanity Check if (webappsPath == null) { @@ -2499,8 +2528,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList + webappsPathAction.toAbsolutePath().toString(), e); } } - ACTION_HOME = webappsPathAction.toString(); - CONFIG_HOME = webappsPathConfig.toString(); + actionHome = webappsPathAction.toString(); + configHome = webappsPathConfig.toString(); } } @@ -2510,7 +2539,11 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } catch (PAPException e) { return null; } - return CONFIG_HOME; + return configHome; + } + + private static void setConfigHome(){ + configHome = getConfigHome(); } public static String getActionHome(){ @@ -2519,7 +2552,11 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } catch (PAPException e) { return null; } - return ACTION_HOME; + return actionHome; + } + + private static void setActionHome(){ + actionHome = getActionHome(); } public static EntityManagerFactory getEmf() { diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/PapUrlResolver.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/PapUrlResolver.java index cee07fd9f..7ac322ec9 100644 --- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/PapUrlResolver.java +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/PapUrlResolver.java @@ -26,6 +26,7 @@ import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.NoSuchElementException; +import java.util.Objects; import java.util.Properties; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -35,343 +36,371 @@ import org.onap.policy.rest.XACMLRestProperties; import com.att.research.xacml.util.XACMLProperties; public class PapUrlResolver { - private static final Logger LOGGER = FlexLogger.getLogger(PapUrlResolver.class); - //how long to keep a pap failed before making it un-failed, in milli-seconds - private static final long FAIL_TIMEOUT = 18000000; - - //thread locks - public static final Object propertyLock = new Object(); - - //keeping this here for backward compatibility - public static String extractIdFromUrl(String url){ - return extractQuery(url); - } - public static String extractQuery(String url){ - try{ - return URI.create(url).getQuery(); - } catch(Exception e){ - LOGGER.error("Exception occured while extracting query. So, empty string is returned"+e); - return ""; - } - } - public static String modifyUrl(String idUrl, String serverUrl){ - URI one = URI.create(idUrl); - String host = one.getPath()+one.getQuery(); - URI two = URI.create(serverUrl); - two.resolve(host); - return two.toString(); - } - - //get an instance of a new PapUrlResolver, using XACMLProperties to get the url lists - public static PapUrlResolver getInstance(){ - return new PapUrlResolver(null,null,null,true); - } - - //get an instance of a new PapUrlResolver, using the provides strings for the url lists - public static PapUrlResolver getInstance(String urlList, String failedList, String succeededList){ - return new PapUrlResolver(urlList, failedList, succeededList,false); - } - - //keeps track of our current location in the list of urls, allows for iterating - private int pointer; - - //should the XACML property lists be updated after anything changes or should we wait for the update - //method to be called. - private boolean autoUpdateProperties; - - //this list keeps the sorted, priority of PAP URLs - private PapUrlNode[] sortedUrlNodes; - //this list keeps the original list of nodes so that they can be entered into the property list correctly - private PapUrlNode[] originalUrlNodes; - - //private constructor to make an instance of a PapUrlResolver, called by static method getInstance. - //If the list property strings are not defined, we get the values from XACMLProperties. - //The instance acts as an iterator, with hasNext and next methods, but does not implement Iterable, - //because it is used for a difference purpose. - private PapUrlResolver(String urlList, String failedList, String succeededList, boolean autoUpdateProperties){ - this.autoUpdateProperties = autoUpdateProperties; - String papUrlLists = urlList; - String papUrlFailedList = failedList; - String papUrlSuccessList = succeededList; - if(papUrlLists == null){ - papUrlLists = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URLS); - if(papUrlLists == null){ - papUrlLists = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); - } - papUrlFailedList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS); - papUrlSuccessList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS); - } - - String[] urls = papUrlLists.split(","); - if(urls.length == 0){ - //log error - } - String[] failed = emptyOrSplit(papUrlFailedList,urls.length); - String[] succeeded = emptyOrSplit(papUrlSuccessList,urls.length); - - sortedUrlNodes = new PapUrlNode[urls.length]; - for(int i=0;i<urls.length;i++){ - - String userId = null; - String pass = null; - userId = XACMLProperties.getProperty(urls[i]+"."+XACMLRestProperties.PROP_PAP_USERID); - pass = XACMLProperties.getProperty(urls[i]+"."+XACMLRestProperties.PROP_PAP_PASS); - if(userId == null || pass == null){ - userId = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); - pass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS); - } - if(userId == null || pass == null){ - userId = ""; - pass = ""; - } - PapUrlNode newNode = new PapUrlNode(urls[i],userId,pass); - newNode.setFailedTime(failed[i]); - newNode.setSucceededTime(succeeded[i]); - if(sortedUrlNodes[i] == null){ - sortedUrlNodes[i] = newNode; - } - } - originalUrlNodes = sortedUrlNodes.clone(); - sort(sortedUrlNodes); - pointer = 0; - } - - - //either split a list by commas, or fill an array to the expected length, if the property list is not long enough - private String[] emptyOrSplit(String list,int expectedLength){ - String[] ret; - if(list == null){ - ret = new String[expectedLength]; - for(int i=0;i<expectedLength;i++){ - ret[i] = "-1"; - } - } else { - ret = list.split(","); - if(ret.length != expectedLength){ - ret = emptyOrSplit(null,expectedLength); - } - } - return ret; - } - - private void sort(PapUrlNode[] array){ - - //O(n^2) double-loop most likely the best in this case, since number of records will be VERY small - for(int i=0;i<array.length;i++){ - for(int j=i;j<array.length;j++){ - if(array[j].compareTo(array[i])<0){ - PapUrlNode temp = array[i]; - array[i] = array[j]; - array[j] = temp; - } - } - } - } - - //returns whether this PapUrlResolver object has more PAP urls that can be tried - public boolean hasMoreUrls(){ - return pointer < sortedUrlNodes.length; - } - - //sets the current PAP url as being failed - //this will set the failed time to now and remove any succeeded time - public void failed(){ - LOGGER.error("PAP Server FAILED: "+sortedUrlNodes[pointer].getUrl()); - - sortedUrlNodes[pointer].setFailedTime(new Date()); - sortedUrlNodes[pointer].setSucceededTime(null); - propertiesUpdated(); - } - - //sets the current PAP url as being working - //this will set the succeeded time to now and remove any failed time - //Also, this will cause hasMoreUrls to return false, since a working one has been found - - public void succeeded(){ - registered(); - pointer = sortedUrlNodes.length; - } - public void registered(){ - sortedUrlNodes[pointer].setFailedTime(null); - sortedUrlNodes[pointer].setSucceededTime(new Date()); - LOGGER.info("PAP server SUCCEEDED "+sortedUrlNodes[pointer].getUrl()); - propertiesUpdated(); - } - - //returns a properties object with the properties that pertain to PAP urls - public Properties getProperties(){ - String failedPropertyString = ""; - String succeededPropertyString = ""; - String urlPropertyString = ""; - for(int i=0;i<originalUrlNodes.length;i++){ - failedPropertyString = failedPropertyString.concat(",").concat(originalUrlNodes[i].getFailedTime()); - succeededPropertyString = succeededPropertyString.concat(",").concat(originalUrlNodes[i].getSucceededTime()); - urlPropertyString = urlPropertyString.concat(",").concat(originalUrlNodes[i].getUrl()); - } - Properties prop = new Properties(); - failedPropertyString = failedPropertyString.substring(1); - succeededPropertyString = succeededPropertyString.substring(1); - urlPropertyString = urlPropertyString.substring(1); - prop.setProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS,failedPropertyString); - prop.setProperty(XACMLRestProperties.PROP_PAP_URLS,urlPropertyString); - prop.setProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS,succeededPropertyString); - return prop; - } - - //saves the updates urls to the correct properties - private void propertiesUpdated(){ - if(!autoUpdateProperties){ - return; - } - Properties prop = getProperties(); - - LOGGER.debug("Failed PAP Url List: "+prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS)); - LOGGER.debug("Succeeded PAP Url List: "+prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS)); - XACMLProperties.setProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS,prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS)); - XACMLProperties.setProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS,prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS)); - } - - //iterates to the next available PAP url, according to the priority order - public void getNext(){ - pointer++; - } - - //returns the url of the current PAP server that we are iterating over - //will append the provided policy id to the url - public String getUrl(String query){ - if(sortedUrlNodes[pointer]== null){ - throw new NoSuchElementException(); - } else { - return sortedUrlNodes[pointer].getUrl().concat("?").concat(query); - } - } - - //returns the url of the current PAP server that we are iterating over - //Just returns the url, with no id appended to it - public String getUrl(){ - if(sortedUrlNodes[pointer]== null){ - throw new NoSuchElementException(); - } else { - - return sortedUrlNodes[pointer].getUrl(); - } - } - public String getUserId(){ - if(sortedUrlNodes[pointer]== null){ - throw new NoSuchElementException(); - } else { - - return sortedUrlNodes[pointer].getUserId(); - } - } - public String getPass(){ - if(sortedUrlNodes[pointer]== null){ - throw new NoSuchElementException(); - } else { - - return sortedUrlNodes[pointer].getPass(); - } - } - - - //This is the class to hold the details of a single PAP URL - //including: the url itself, the last time it failed, and the last time it succeeded - //It also includes the custom comparer which can compare based on failed and succeeded times, and takes into account - //the timeout on failures. - private class PapUrlNode implements Comparable<PapUrlNode> { - private String papUrl; - private Date failedTime; - private Date succeededTime; - private String userId; - private String pass; - - public PapUrlNode(String url,String userId,String pass){ - this.papUrl = url; - failedTime = null; - this.succeededTime = null; - this.userId = userId; - this.pass = pass; - - } - public String getUserId(){ - return this.userId; - } - public String getPass(){ - return this.pass; - } - - public void setFailedTime(Object time){ - Date failedTimeAsDate = setHandler(time); - if(failedTimeAsDate == null){ - this.failedTime = null; - } else { - long timeDifference = new Date().getTime() - failedTimeAsDate.getTime(); - if(timeDifference < FAIL_TIMEOUT){ - this.failedTime = failedTimeAsDate; - } else { - this.failedTime = null; - } - } - } - - //set the time that this url succeeded at - public void setSucceededTime(Object time){ - this.succeededTime = setHandler(time); - } - - //parses string into a date or a null date, if the url never failed/succeeded (since -1 will be in the property) - private Date setHandler(Object time){ - if(time instanceof String){ - if("-1".equals((String)time)){ - return null; - } - try { - DateFormat df = new SimpleDateFormat(); - return df.parse((String)time); - } catch (ParseException e) { - return null; - } - } - if(time instanceof Date){ - return (Date)time; - } - return null; - } - - - public String getFailedTime(){ - return formatTime(this.failedTime); - } - - public String getSucceededTime(){ - return formatTime(this.succeededTime); - } - - //formats a Date into a string or a -1 if there is not date (-1 is used in properties for no date) - private String formatTime(Date d){ - if(d == null){ - return "-1"; - } - DateFormat df = new SimpleDateFormat(); - return df.format(d); - } - - public String getUrl(){ - return papUrl; - } - - @Override - public int compareTo(PapUrlNode other){ - if(this.failedTime == null && other.failedTime != null){ - return -1; - } - if(this.failedTime != null && other.failedTime == null){ - return 1; - } - if(this.failedTime != null){ - return this.failedTime.compareTo(other.failedTime); - } - return 0; - } - } + private static final Logger LOGGER = FlexLogger.getLogger(PapUrlResolver.class); + // how long to keep a pap failed before making it un-failed, in milli-seconds + private static final long FAIL_TIMEOUT = 18000000; + + // thread locks + public static final Object propertyLock = new Object(); + + // keeping this here for backward compatibility + public static String extractIdFromUrl(String url) { + return extractQuery(url); + } + + public static String extractQuery(String url) { + try { + return URI.create(url).getQuery(); + } catch (Exception e) { + LOGGER.error("Exception occured while extracting query. So, empty string is returned" + e); + return ""; + } + } + + public static String modifyUrl(String idUrl, String serverUrl) { + URI one = URI.create(idUrl); + String host = one.getPath() + one.getQuery(); + URI two = URI.create(serverUrl); + two.resolve(host); + return two.toString(); + } + + // get an instance of a new PapUrlResolver, using XACMLProperties to get the url lists + public static PapUrlResolver getInstance() { + return new PapUrlResolver(null, null, null, true); + } + + // get an instance of a new PapUrlResolver, using the provides strings for the url lists + public static PapUrlResolver getInstance(String urlList, String failedList, String succeededList) { + return new PapUrlResolver(urlList, failedList, succeededList, false); + } + + // keeps track of our current location in the list of urls, allows for iterating + private int pointer; + + // should the XACML property lists be updated after anything changes or should we wait for the update + // method to be called. + private boolean autoUpdateProperties; + + // this list keeps the sorted, priority of PAP URLs + private PapUrlNode[] sortedUrlNodes; + // this list keeps the original list of nodes so that they can be entered into the property list correctly + private PapUrlNode[] originalUrlNodes; + + // private constructor to make an instance of a PapUrlResolver, called by static method getInstance. + // If the list property strings are not defined, we get the values from XACMLProperties. + // The instance acts as an iterator, with hasNext and next methods, but does not implement Iterable, + // because it is used for a difference purpose. + private PapUrlResolver(String urlList, String failedList, String succeededList, boolean autoUpdateProperties) { + this.autoUpdateProperties = autoUpdateProperties; + String papUrlLists = urlList; + String papUrlFailedList = failedList; + String papUrlSuccessList = succeededList; + if (papUrlLists == null) { + papUrlLists = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URLS); + if (papUrlLists == null) { + papUrlLists = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); + } + papUrlFailedList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS); + papUrlSuccessList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS); + } + + String[] urls = papUrlLists.split(","); + if (urls.length == 0) { + // log error + } + String[] failed = emptyOrSplit(papUrlFailedList, urls.length); + String[] succeeded = emptyOrSplit(papUrlSuccessList, urls.length); + + sortedUrlNodes = new PapUrlNode[urls.length]; + for (int i = 0; i < urls.length; i++) { + + String userId = null; + String pass = null; + userId = XACMLProperties.getProperty(urls[i] + "." + XACMLRestProperties.PROP_PAP_USERID); + pass = XACMLProperties.getProperty(urls[i] + "." + XACMLRestProperties.PROP_PAP_PASS); + if (userId == null || pass == null) { + userId = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); + pass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS); + } + if (userId == null || pass == null) { + userId = ""; + pass = ""; + } + PapUrlNode newNode = new PapUrlNode(urls[i], userId, pass); + newNode.setFailedTime(failed[i]); + newNode.setSucceededTime(succeeded[i]); + if (sortedUrlNodes[i] == null) { + sortedUrlNodes[i] = newNode; + } + } + originalUrlNodes = sortedUrlNodes.clone(); + sort(sortedUrlNodes); + pointer = 0; + } + + // either split a list by commas, or fill an array to the expected length, if the property list is not long enough + private String[] emptyOrSplit(String list, int expectedLength) { + String[] ret; + if (list == null) { + ret = new String[expectedLength]; + for (int i = 0; i < expectedLength; i++) { + ret[i] = "-1"; + } + } else { + ret = list.split(","); + if (ret.length != expectedLength) { + ret = emptyOrSplit(null, expectedLength); + } + } + return ret; + } + + private void sort(PapUrlNode[] array) { + + // O(n^2) double-loop most likely the best in this case, since number of records will be VERY small + for (int i = 0; i < array.length; i++) { + for (int j = i; j < array.length; j++) { + if (array[j].compareTo(array[i]) < 0) { + PapUrlNode temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + } + } + } + + // returns whether this PapUrlResolver object has more PAP urls that can be tried + public boolean hasMoreUrls() { + return pointer < sortedUrlNodes.length; + } + + // sets the current PAP url as being failed + // this will set the failed time to now and remove any succeeded time + public void failed() { + LOGGER.error("PAP Server FAILED: " + sortedUrlNodes[pointer].getUrl()); + + sortedUrlNodes[pointer].setFailedTime(new Date()); + sortedUrlNodes[pointer].setSucceededTime(null); + propertiesUpdated(); + } + + // sets the current PAP url as being working + // this will set the succeeded time to now and remove any failed time + // Also, this will cause hasMoreUrls to return false, since a working one has been found + + public void succeeded() { + registered(); + pointer = sortedUrlNodes.length; + } + + public void registered() { + sortedUrlNodes[pointer].setFailedTime(null); + sortedUrlNodes[pointer].setSucceededTime(new Date()); + LOGGER.info("PAP server SUCCEEDED " + sortedUrlNodes[pointer].getUrl()); + propertiesUpdated(); + } + + // returns a properties object with the properties that pertain to PAP urls + public Properties getProperties() { + String failedPropertyString = ""; + String succeededPropertyString = ""; + String urlPropertyString = ""; + for (int i = 0; i < originalUrlNodes.length; i++) { + failedPropertyString = failedPropertyString.concat(",").concat(originalUrlNodes[i].getFailedTime()); + succeededPropertyString = succeededPropertyString.concat(",") + .concat(originalUrlNodes[i].getSucceededTime()); + urlPropertyString = urlPropertyString.concat(",").concat(originalUrlNodes[i].getUrl()); + } + Properties prop = new Properties(); + failedPropertyString = failedPropertyString.substring(1); + succeededPropertyString = succeededPropertyString.substring(1); + urlPropertyString = urlPropertyString.substring(1); + prop.setProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS, failedPropertyString); + prop.setProperty(XACMLRestProperties.PROP_PAP_URLS, urlPropertyString); + prop.setProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS, succeededPropertyString); + return prop; + } + + // saves the updates urls to the correct properties + private void propertiesUpdated() { + if (!autoUpdateProperties) { + return; + } + Properties prop = getProperties(); + + LOGGER.debug("Failed PAP Url List: " + prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS)); + LOGGER.debug("Succeeded PAP Url List: " + prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS)); + XACMLProperties.setProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS, + prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS)); + XACMLProperties.setProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS, + prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS)); + } + + // iterates to the next available PAP url, according to the priority order + public void getNext() { + pointer++; + } + + // returns the url of the current PAP server that we are iterating over + // will append the provided policy id to the url + public String getUrl(String query) { + if (sortedUrlNodes[pointer] == null) { + throw new NoSuchElementException(); + } else { + return sortedUrlNodes[pointer].getUrl().concat("?").concat(query); + } + } + + // returns the url of the current PAP server that we are iterating over + // Just returns the url, with no id appended to it + public String getUrl() { + if (sortedUrlNodes[pointer] == null) { + throw new NoSuchElementException(); + } else { + + return sortedUrlNodes[pointer].getUrl(); + } + } + + public String getUserId() { + if (sortedUrlNodes[pointer] == null) { + throw new NoSuchElementException(); + } else { + + return sortedUrlNodes[pointer].getUserId(); + } + } + + public String getPass() { + if (sortedUrlNodes[pointer] == null) { + throw new NoSuchElementException(); + } else { + + return sortedUrlNodes[pointer].getPass(); + } + } + + // This is the class to hold the details of a single PAP URL + // including: the url itself, the last time it failed, and the last time it succeeded + // It also includes the custom comparer which can compare based on failed and succeeded times, and takes into + // account + // the timeout on failures. + private class PapUrlNode implements Comparable<PapUrlNode> { + private String papUrl; + private Date failedTime; + private Date succeededTime; + private String userId; + private String pass; + + public PapUrlNode(String url, String userId, String pass) { + this.papUrl = url; + failedTime = null; + this.succeededTime = null; + this.userId = userId; + this.pass = pass; + + } + + public String getUserId() { + return this.userId; + } + + public String getPass() { + return this.pass; + } + + public void setFailedTime(Object time) { + Date failedTimeAsDate = setHandler(time); + if (failedTimeAsDate == null) { + this.failedTime = null; + } else { + long timeDifference = new Date().getTime() - failedTimeAsDate.getTime(); + if (timeDifference < FAIL_TIMEOUT) { + this.failedTime = failedTimeAsDate; + } else { + this.failedTime = null; + } + } + } + + // set the time that this url succeeded at + public void setSucceededTime(Object time) { + this.succeededTime = setHandler(time); + } + + // parses string into a date or a null date, if the url never failed/succeeded (since -1 will be in the + // property) + private Date setHandler(Object time) { + if (time instanceof String) { + if ("-1".equals((String) time)) { + return null; + } + try { + DateFormat df = new SimpleDateFormat(); + return df.parse((String) time); + } catch (ParseException e) { + return null; + } + } + if (time instanceof Date) { + return (Date) time; + } + return null; + } + + public String getFailedTime() { + return formatTime(this.failedTime); + } + + public String getSucceededTime() { + return formatTime(this.succeededTime); + } + + // formats a Date into a string or a -1 if there is not date (-1 is used in properties for no date) + private String formatTime(Date d) { + if (d == null) { + return "-1"; + } + DateFormat df = new SimpleDateFormat(); + return df.format(d); + } + + public String getUrl() { + return papUrl; + } + + @Override + public int compareTo(PapUrlNode other) { + if (this.failedTime == null && other.failedTime != null) { + return -1; + } + if (this.failedTime != null && other.failedTime == null) { + return 1; + } + if (this.failedTime != null) { + return this.failedTime.compareTo(other.failedTime); + } + return 0; + } + + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof PapUrlNode)) { + return false; + } + PapUrlNode papUrlNode = (PapUrlNode) obj; + return Objects.equals(papUrlNode.papUrl, papUrl) && Objects.equals(papUrlNode.failedTime, failedTime) + && Objects.equals(papUrlNode.succeededTime, succeededTime) + && Objects.equals(papUrlNode.userId, userId) && Objects.equals(papUrlNode.pass, pass); + } + + @Override + public int hashCode() { + return Objects.hash(papUrl, failedTime, succeededTime, userId, pass); + } + } } diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpServlet.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpServlet.java index d57e88498..18c201737 100644 --- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpServlet.java +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpServlet.java @@ -130,8 +130,8 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { // This thread may getting invoked on startup, to let the PAP know // that we are up and running. // - private Thread registerThread = null; - private XACMLPdpRegisterThread registerRunnable = null; + private static transient Thread registerThread = null; + private static transient XACMLPdpRegisterThread registerRunnable = null; // // This is our PDP engine pointer. There is a synchronized lock used // for access to the pointer. In case we are servicing PEP requests while @@ -176,10 +176,10 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { // This is our configuration thread that attempts to load // a new configuration request. // - private Thread configThread = null; - private volatile boolean configThreadTerminate = false; - private ONAPLoggingContext baseLoggingContext = null; - private IntegrityMonitor im; + private static transient Thread configThread = null; + private static volatile boolean configThreadTerminate = false; + private transient ONAPLoggingContext baseLoggingContext = null; + private transient IntegrityMonitor im; /** * Default constructor. */ @@ -198,16 +198,12 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { // Initialize // XACMLRest.xacmlInit(config); - // Load the Notification Delay. - try{ - XACMLPdpServlet.notificationDelay = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_DELAY)); - }catch(Exception e){ - logger.info("Notification Delay Not set. Keeping it 0 as default."+e); - } + // Load the Notification Delay. + setNotificationDelay(); // Load Queue size. int queueSize = 5; // Set default Queue Size here. queueSize = Integer.parseInt(XACMLProperties.getProperty("REQUEST_BUFFER_SIZE",String.valueOf(queueSize))); - queue = new LinkedBlockingQueue<PutRequest>(queueSize); + initQueue(queueSize); // Load our engine - this will use the latest configuration // that was saved to disk and set our initial status object. // @@ -250,25 +246,14 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { } PolicyLogger.info("\n Properties Given : \n" + properties.toString()); } - pdpResourceName = properties.getProperty(XACMLRestProperties.PDP_RESOURCE_NAME); - if(pdpResourceName == null){ - PolicyLogger.error(MessageCodes.MISS_PROPERTY_ERROR, XACMLRestProperties.PDP_RESOURCE_NAME, "xacml.pdp"); - throw new ServletException("pdpResourceName is null"); - } - + setPDPResourceName(properties); dependencyGroups = properties.getProperty(IntegrityMonitorProperties.DEPENDENCY_GROUPS); if(dependencyGroups == null){ PolicyLogger.error(MessageCodes.MISS_PROPERTY_ERROR, IntegrityMonitorProperties.DEPENDENCY_GROUPS, "xacml.pdp"); throw new ServletException("dependency_groups is null"); } - // dependency_groups is a semicolon-delimited list of groups, and - // each group is a comma-separated list of nodes. For our purposes - // we just need a list of dependencies without regard to grouping, - // so split the list into nodes separated by either comma or semicolon. - dependencyNodes = dependencyGroups.split("[;,]"); - for (int i = 0 ; i < dependencyNodes.length ; i++){ - dependencyNodes[i] = dependencyNodes[i].trim(); - } + setDependencyNodes(dependencyGroups); + // CreateUpdatePolicy ResourceName createUpdateResourceName = properties.getProperty("createUpdatePolicy.impl.className", CREATE_UPDATE_POLICY_SERVICE); @@ -282,25 +267,59 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "Failed to create IntegrityMonitor" +e); throw new ServletException(e); } - - environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL"); - // - // Kick off our thread to register with the PAP servlet. - // - if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER))) { - this.registerRunnable = new XACMLPdpRegisterThread(baseLoggingContext); - this.registerThread = new Thread(this.registerRunnable); - this.registerThread.start(); - } - // - // This is our thread that manages incoming configuration - // changes. - // - this.configThread = new Thread(this); - this.configThread.start(); + startThreads(baseLoggingContext, new Thread(this)); } - /** + private static void startThreads(ONAPLoggingContext baseLoggingContext, Thread thread) { + environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL"); + // + // Kick off our thread to register with the PAP servlet. + // + if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER))) { + XACMLPdpServlet.registerRunnable = new XACMLPdpRegisterThread(baseLoggingContext); + XACMLPdpServlet.registerThread = new Thread(XACMLPdpServlet.registerRunnable); + XACMLPdpServlet.registerThread.start(); + } + // + // This is our thread that manages incoming configuration + // changes. + // + XACMLPdpServlet.configThread = thread; + XACMLPdpServlet.configThread.start(); + } + + private static void setDependencyNodes(String dependencyGroups) { + // dependency_groups is a semicolon-delimited list of groups, and + // each group is a comma-separated list of nodes. For our purposes + // we just need a list of dependencies without regard to grouping, + // so split the list into nodes separated by either comma or semicolon. + dependencyNodes = dependencyGroups.split("[;,]"); + for (int i = 0 ; i < dependencyNodes.length ; i++){ + dependencyNodes[i] = dependencyNodes[i].trim(); + } + } + + private static void setPDPResourceName(Properties properties) throws ServletException { + pdpResourceName = properties.getProperty(XACMLRestProperties.PDP_RESOURCE_NAME); + if(pdpResourceName == null){ + PolicyLogger.error(MessageCodes.MISS_PROPERTY_ERROR, XACMLRestProperties.PDP_RESOURCE_NAME, "xacml.pdp"); + throw new ServletException("pdpResourceName is null"); + } + } + + private static void initQueue(int queueSize) { + queue = new LinkedBlockingQueue<>(queueSize); + } + + private static void setNotificationDelay() { + try{ + XACMLPdpServlet.notificationDelay = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_DELAY)); + }catch(NumberFormatException e){ + logger.error("Error in notification delay format, Taking the default value.", e); + } + } + + /** * @see Servlet#destroy() */ @Override @@ -310,33 +329,39 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { // // Make sure the register thread is not running // - if (this.registerRunnable != null) { + if (XACMLPdpServlet.registerRunnable != null) { try { - this.registerRunnable.terminate(); - if (this.registerThread != null) { - this.registerThread.interrupt(); - this.registerThread.join(); + XACMLPdpServlet.registerRunnable.terminate(); + if (XACMLPdpServlet.registerThread != null) { + XACMLPdpServlet.registerThread.interrupt(); + XACMLPdpServlet.registerThread.join(); } } catch (InterruptedException e) { logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, ""); + XACMLPdpServlet.registerThread.interrupt(); } } // // Make sure the configure thread is not running // - this.configThreadTerminate = true; + setConfigThreadTerminate(true); try { - this.configThread.interrupt(); - this.configThread.join(); + XACMLPdpServlet.configThread.interrupt(); + XACMLPdpServlet.configThread.join(); } catch (InterruptedException e) { logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, ""); + XACMLPdpServlet.configThread.interrupt(); } logger.info("Destroyed."); } - /** + private static void setConfigThreadTerminate(boolean value) { + XACMLPdpServlet.configThreadTerminate = value; + } + + /** * PUT - The PAP engine sends configuration information using HTTP PUT request. * * One parameter is expected: @@ -937,7 +962,13 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { // Read in the string // StringBuilder buffer = new StringBuilder(); - BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream())); + BufferedReader reader = null; + try{ + reader = new BufferedReader(new InputStreamReader(request.getInputStream())); + }catch(IOException e){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error during reading input stream",e); + return; + } String line; try{ while((line = reader.readLine()) != null){ @@ -1198,7 +1229,7 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable { // try { // variable not used, but constructor has needed side-effects so don't remove: - while (! this.configThreadTerminate) { + while (! XACMLPdpServlet.configThreadTerminate) { PutRequest request = XACMLPdpServlet.queue.take(); StdPDPStatus newStatus = new StdPDPStatus(); diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PAPServices.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PAPServices.java index e7216e152..f7c175c0c 100644 --- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PAPServices.java +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PAPServices.java @@ -227,112 +227,96 @@ public class PAPServices { String [] parameters = {"apiflag=version","policyScope="+policyScope, "filePrefix="+filePrefix, "policyName="+policyName}; if (paps == null || paps.isEmpty()) { LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty."); - try { - throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"PAPs List is empty."); - } catch (Exception e) { - LOGGER.error(e.getMessage() + e); - } - }else { - int papsCount = 0; - boolean connected = false; - while (papsCount < paps.size()) { - try { - String fullURL = getPAP(); - if (parameters != null && parameters.length > 0) { - String queryString = ""; - for (String p : parameters) { - queryString += "&" + p; - } - fullURL += "?" + queryString.substring(1); + }else { + int papsCount = 0; + boolean connected = false; + while (papsCount < paps.size()) { + try { + String fullURL = getPAP(); + if (parameters != null && parameters.length > 0) { + String queryString = ""; + for (String p : parameters) { + queryString += "&" + p; } - - URL url = new URL (fullURL); - - //Open the connection - connection = (HttpURLConnection)url.openConnection(); - - // Setting Content-Type - connection.setRequestProperty("Content-Type", - "application/json"); - - // Adding Authorization - connection.setRequestProperty("Authorization", "Basic " - + getPAPEncoding()); - - connection.setRequestProperty("Environment", environment); - connection.setRequestProperty("ClientScope", clientScope); + fullURL += "?" + queryString.substring(1); + } - - //set the method and headers - connection.setRequestMethod("GET"); - connection.setUseCaches(false); - connection.setInstanceFollowRedirects(false); - connection.setDoOutput(true); - connection.setDoInput(true); - connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString()); - - //DO the connect - connection.connect(); - - // If Connected to PAP then break from the loop and continue with the Request - if (connection.getResponseCode() > 0) { - connected = true; - break; + URL url = new URL (fullURL); - } else { - LOGGER.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error"); - } - } catch (Exception e) { - // This means that the PAP is not working - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error : " + e); - rotatePAPList(); + //Open the connection + connection = (HttpURLConnection)url.openConnection(); + + // Setting Content-Type + connection.setRequestProperty("Content-Type", + "application/json"); + + // Adding Authorization + connection.setRequestProperty("Authorization", "Basic " + + getPAPEncoding()); + + connection.setRequestProperty("Environment", environment); + connection.setRequestProperty("ClientScope", clientScope); + + + //set the method and headers + connection.setRequestMethod("GET"); + connection.setUseCaches(false); + connection.setInstanceFollowRedirects(false); + connection.setDoOutput(true); + connection.setDoInput(true); + connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString()); + + //DO the connect + connection.connect(); + + // If Connected to PAP then break from the loop and continue with the Request + if (connection.getResponseCode() > 0) { + connected = true; + break; + + } else { + LOGGER.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error"); } - papsCount++; + } catch (Exception e) { + // This means that the PAP is not working + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error : " + e); + rotatePAPList(); } - - if (connected) { - //Read the Response - LOGGER.debug("connected to the PAP : " + getPAP()); - LOGGER.debug("--- Response: ---"); - Map<String, List<String>> headers = connection.getHeaderFields(); - for (String key : headers.keySet()) { - LOGGER.debug("Header :" + key + " Value: " + headers.get(key)); - } - try { - if (connection.getResponseCode() == 200) { - // Check for successful creation of policy - version = connection.getHeaderField("version"); - LOGGER.debug("ActiveVersion from the Header: " + version); - } else if (connection.getResponseCode() == 403) { - LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + "response code of the URL is " - + connection.getResponseCode() + ". PEP is not Authorized for making this Request!! \n Contact Administrator for this Scope. "); - version = "pe100"; - } else if (connection.getResponseCode() == 404) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "response code of the URL is " - + connection.getResponseCode() + ". This indicates a problem with getting the version from the PAP"); - version = "pe300"; - } else { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: Error occured while getting the version from the PAP. The request may be incorrect."); - } - } catch (IOException e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); - try { - throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ", e); - } catch (Exception e1) { - LOGGER.error(e1.getMessage() + e1); - } - } - - } else { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get valid response from PAP(s) " + paps); - try { - throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP "); - } catch (Exception e) { - LOGGER.error(e.getMessage() + e); - } - } + papsCount++; } - return version; + + if (connected) { + //Read the Response + LOGGER.debug("connected to the PAP : " + getPAP()); + LOGGER.debug("--- Response: ---"); + Map<String, List<String>> headers = connection.getHeaderFields(); + for (String key : headers.keySet()) { + LOGGER.debug("Header :" + key + " Value: " + headers.get(key)); + } + try { + if (connection.getResponseCode() == 200) { + // Check for successful creation of policy + version = connection.getHeaderField("version"); + LOGGER.debug("ActiveVersion from the Header: " + version); + } else if (connection.getResponseCode() == 403) { + LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + "response code of the URL is " + + connection.getResponseCode() + ". PEP is not Authorized for making this Request!! \n Contact Administrator for this Scope. "); + version = "pe100"; + } else if (connection.getResponseCode() == 404) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "response code of the URL is " + + connection.getResponseCode() + ". This indicates a problem with getting the version from the PAP"); + version = "pe300"; + } else { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: Error occured while getting the version from the PAP. The request may be incorrect."); + } + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + } + } else { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get valid response from PAP(s) " + paps); + } + } + return version; } private String checkResponse(HttpURLConnection connection, UUID requestID) throws IOException { diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PDPServices.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PDPServices.java index e495c9950..efaa5c167 100644 --- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PDPServices.java +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PDPServices.java @@ -21,10 +21,10 @@ package org.onap.policy.pdp.rest.api.services; import java.io.File; import java.io.FileInputStream; +import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; -import java.net.MalformedURLException; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; @@ -37,6 +37,7 @@ import javax.json.JsonReader; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; @@ -65,6 +66,7 @@ import com.att.research.xacml.api.Request; import com.att.research.xacml.api.Response; import com.att.research.xacml.api.Result; import com.att.research.xacml.api.pdp.PDPEngine; +import com.att.research.xacml.api.pdp.PDPException; import com.att.research.xacml.std.json.JSONRequest; import com.att.research.xacml.std.json.JSONResponse; import com.att.research.xacml.util.XACMLProperties; @@ -333,7 +335,7 @@ public class PDPServices { return treatment; } - private PDPResponse configCall(String pdpConfigLocation) throws Exception{ + private PDPResponse configCall(String pdpConfigLocation) throws PDPException, IOException{ PDPResponse pdpResponse = new PDPResponse(); if(pdpConfigLocation.contains("/")){ pdpConfigLocation = pdpConfigLocation.replace("/", File.separator); @@ -366,7 +368,7 @@ public class PDPServices { pdpResponse.setConfig(writer.toString()); } catch (Exception e) { LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID+ e); - throw new Exception(XACMLErrorConstants.ERROR_SCHEMA_INVALID+ "Unable to parse the XML config", e); + throw new PDPException(XACMLErrorConstants.ERROR_SCHEMA_INVALID+ "Unable to parse the XML config", e); } } else if (pdpConfigLocation.endsWith("properties")) { pdpResponse.setType(PolicyType.PROPERTIES); @@ -394,14 +396,14 @@ public class PDPServices { PolicyResponseStatus.NO_ACTION_REQUIRED, PolicyConfigStatus.CONFIG_RETRIEVED); return pdpResponse; - } catch (IOException e) { + } catch (IOException | ParserConfigurationException e) { LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - throw new Exception(XACMLErrorConstants.ERROR_PROCESS_FLOW + + throw new PDPException(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Cannot open a connection to the configURL", e); } - } catch (MalformedURLException e) { + } catch (FileNotFoundException e) { LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); - throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in ConfigURL", e); + throw new PDPException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in ConfigURL", e); }finally{ if(inputStream != null){ inputStream.close(); @@ -409,8 +411,7 @@ public class PDPServices { } } - private Response callPDP(Request request, - UUID requestID) throws Exception{ + private Response callPDP(Request request, UUID requestID){ Response response = null; // Get the PDPEngine if (requestID == null) { diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PolicyEngineImportService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PolicyEngineImportService.java index 2d8af54c5..d0649d78a 100644 --- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PolicyEngineImportService.java +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PolicyEngineImportService.java @@ -62,7 +62,7 @@ public class PolicyEngineImportService { requestUUID = UUID.fromString(requestID); } catch (IllegalArgumentException e) { requestUUID = UUID.randomUUID(); - LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + LOGGER.info("Generated Random UUID: " + requestUUID.toString(), e); } }else{ requestUUID = UUID.randomUUID(); diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/ManualNotificationUpdateThread.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/ManualNotificationUpdateThread.java index c1306572f..9027e27a5 100644 --- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/ManualNotificationUpdateThread.java +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/ManualNotificationUpdateThread.java @@ -44,186 +44,205 @@ import com.att.research.xacml.util.XACMLProperties; @SuppressWarnings("deprecation") public class ManualNotificationUpdateThread implements Runnable { - private static final Logger LOGGER = FlexLogger.getLogger(ManualNotificationUpdateThread.class); - - private static String topic = null; - private static CambriaConsumer CConsumer = null; - private static String clusterList = null; - private static String update = null; - private static BusConsumer dmaapConsumer = null; - private static List<String> dmaapList = null; - private static String propNotificationType = null; - private static String aafLogin = null; - private static String aafPassword = null; - - public volatile boolean isRunning = false; - - public synchronized boolean isRunning() { - return this.isRunning; - } - - public synchronized void terminate() { - this.isRunning = false; - } - - /** - * - * This is our thread that runs on startup if the system is configured to UEB to accept manual update requests - * - */ - @Override - public void run() { - synchronized(this) { - this.isRunning = true; - } - - URL aURL = null; - String group = UUID.randomUUID ().toString (); - String id = "0"; - String returnTopic = null; - propNotificationType = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_TYPE); - if ("ueb".equals(propNotificationType)){ - try { - clusterList = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_SERVERS).trim(); - String url = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_ID); - aURL = new URL(url); - topic = aURL.getHost() + aURL.getPort(); - } catch (NumberFormatException e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Unable to get UEB cluster list or pdp url: ", e); - this.isRunning = false; - } catch (MalformedURLException e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in processing URL to create topic for Notification ", e); - } - if(aURL != null){ - String consumerTopic = aURL.getHost() + aURL.getPort() + "UpdateRequest"; - SendMessage(consumerTopic, "Starting-Topic"); - final LinkedList<String> urlList = new LinkedList<> (); - for ( String u : clusterList.split ( "," ) ){ - urlList.add ( u ); - } - - try { - CConsumer = CambriaClientFactory.createConsumer ( null, urlList, consumerTopic , group, id, 20*1000, 1000 ); - } catch (MalformedURLException | GeneralSecurityException e1) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Unable to create UEB Consumer: ", e1); - } - - while (this.isRunning()) { - LOGGER.debug("While loop test _ take out "); - try { - for ( String msg : CConsumer.fetch () ){ - LOGGER.debug("Manual Notification Recieved Message " + msg + " from UEB cluster : "); - returnTopic = processMessage(msg); - if(returnTopic != null){ - SendMessage(returnTopic, update); - } - } - } catch (IOException e) { - LOGGER.debug(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in processing UEB message" + e); - } - } - LOGGER.debug("Stopping UEB Consumer loop will no longer fetch messages from the cluster"); - } - } else if ("dmaap".equals(propNotificationType)) { - String dmaapServers = null; - try { - dmaapServers = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_SERVERS); - topic = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_TOPIC); - aafLogin = XACMLProperties.getProperty("DMAAP_AAF_LOGIN"); - aafPassword = XACMLProperties.getProperty("DMAAP_AAF_PASSWORD"); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Unable to get DMaaP servers list:", e); - this.isRunning = false; - } - - if(dmaapServers==null || topic==null){ - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file "); - try { - throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file "); - } catch (Exception e) { - LOGGER.error(e); - } - } - - dmaapServers.trim(); - topic.trim(); - aafLogin.trim(); - aafPassword.trim(); - - String consumerTopic = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_TOPIC).trim(); - SendMessage(consumerTopic, "Starting-Topic"); - dmaapList = new ArrayList<>(); - for ( String u : dmaapServers.split ( "," ) ){ - dmaapList.add ( u ); - } - - try { - - dmaapConsumer = new BusConsumer.DmaapConsumerWrapper(dmaapList, consumerTopic, aafLogin, aafPassword, group, id, 20*1000, 1000); - } catch (Exception e1) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Unable to create DMaaP Consumer: ", e1); - } - - while (this.isRunning()) { - LOGGER.debug("While loop test _ take out "); - try { - for ( String msg : dmaapConsumer.fetch () ){ - LOGGER.debug("Manual Notification Recieved Message " + msg + " from DMaaP server : "); - returnTopic = processMessage(msg); - if(returnTopic != null){ - SendMessage(returnTopic, update); - } - } - }catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in processing DMaaP message: ", e); } - } - LOGGER.debug("Stopping DMaaP Consumer loop will no longer fetch messages from the servers"); - } - } - - private void SendMessage( String topic, String message) { - CambriaPublisher pub = null; - BusPublisher publisher = null; - try { - if ("ueb".equals(propNotificationType)) { - pub = CambriaClientFactory.createSimplePublisher (null, clusterList, topic ); - pub.send( "pdpReturnMessage", message ); - LOGGER.debug("Sending Message to UEB topic: " + topic); - pub.close(); - - } else if ("dmaap".equals(propNotificationType)){ - publisher = new BusPublisher.DmaapPublisherWrapper(dmaapList,topic,aafLogin,aafPassword); - publisher.send( "pdpReturnMessage", message ); - LOGGER.debug("Sending to Message to DMaaP topic: " + topic); - publisher.close(); - } - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+ "Error sending notification update: ", e); - } - if(pub != null){ - try { - pub.send( "pdpReturnMessage", message ); - LOGGER.debug("Sending to Message to tpoic" + topic); - pub.close(); - } catch (IOException e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+ "Error sending notification update" +e); - } - } - } - - private String processMessage(String msg) { - LOGGER.debug("notification message: " + msg); - String[] UID = msg.split("=")[1].split("\""); - - String returnTopic = topic + UID[0]; - if(msg.contains("Starting-Topic")){ - return null; - } - return returnTopic; - } - public static void setUpdate(String update) { - ManualNotificationUpdateThread.update = update; - } - + private static final Logger LOGGER = FlexLogger.getLogger(ManualNotificationUpdateThread.class); + + private String topic = null; + private CambriaConsumer cConsumer = null; + private static String clusterList = null; + private static String update = null; + private BusConsumer dmaapConsumer = null; + private List<String> dmaapList = null; + private static String propNotificationType = null; + private static String aafLogin = null; + private static String aafPassword = null; + + public volatile boolean isRunning = false; + + public synchronized boolean isRunning() { + return this.isRunning; + } + + public synchronized void terminate() { + this.isRunning = false; + } + + /** + * + * This is our thread that runs on startup if the system is configured to UEB to accept manual update requests + * + */ + @Override + public void run() { + synchronized (this) { + this.isRunning = true; + } + + URL aURL = null; + String group = UUID.randomUUID().toString(); + String id = "0"; + String returnTopic = null; + setPropNotification(); + if ("ueb".equals(propNotificationType)) { + try { + setCluster(); + String url = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_ID); + aURL = new URL(url); + topic = aURL.getHost() + aURL.getPort(); + } catch (NumberFormatException e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Unable to get UEB cluster list or pdp url: ", e); + this.isRunning = false; + } catch (MalformedURLException e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + + "Error in processing URL to create topic for Notification ", e); + } + if (aURL != null) { + String consumerTopic = aURL.getHost() + aURL.getPort() + "UpdateRequest"; + sendMessage(consumerTopic, "Starting-Topic"); + final LinkedList<String> urlList = new LinkedList<>(); + for (String u : clusterList.split(",")) { + urlList.add(u); + } + + try { + cConsumer = CambriaClientFactory.createConsumer(null, urlList, consumerTopic, group, id, 20 * 1000, + 1000); + } catch (MalformedURLException | GeneralSecurityException e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Unable to create UEB Consumer: ", e1); + } + + while (this.isRunning()) { + LOGGER.debug("While loop test _ take out "); + try { + for (String msg : cConsumer.fetch()) { + LOGGER.debug("Manual Notification Recieved Message " + msg + " from UEB cluster : "); + returnTopic = processMessage(msg); + if (returnTopic != null) { + sendMessage(returnTopic, update); + } + } + } catch (IOException e) { + LOGGER.debug(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in processing UEB message" + e); + } + } + LOGGER.debug("Stopping UEB Consumer loop will no longer fetch messages from the cluster"); + } + } else if ("dmaap".equals(propNotificationType)) { + String dmaapServers = null; + try { + dmaapServers = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_SERVERS); + topic = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_TOPIC); + setAAFCreds(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Unable to get DMaaP servers list:", e); + this.isRunning = false; + } + + if (dmaapServers == null || topic == null) { + LOGGER.error( + XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file "); + } + + dmaapServers = dmaapServers.trim(); + topic = topic.trim(); + + String consumerTopic = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_TOPIC).trim(); + sendMessage(consumerTopic, "Starting-Topic"); + dmaapList = new ArrayList<>(); + for (String u : dmaapServers.split(",")) { + dmaapList.add(u); + } + + try { + dmaapConsumer = new BusConsumer.DmaapConsumerWrapper(dmaapList, consumerTopic, aafLogin, aafPassword, + group, id, 20 * 1000, 1000); + } catch (Exception e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Unable to create DMaaP Consumer: ", e1); + } + + while (this.isRunning()) { + LOGGER.debug("While loop test _ take out "); + try { + for (String msg : dmaapConsumer.fetch()) { + LOGGER.debug("Manual Notification Recieved Message " + msg + " from DMaaP server : "); + returnTopic = processMessage(msg); + if (returnTopic != null) { + sendMessage(returnTopic, update); + } + } + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in processing DMaaP message: ", e); + } + } + LOGGER.debug("Stopping DMaaP Consumer loop will no longer fetch messages from the servers"); + } + } + + private static void setAAFCreds() { + aafLogin = XACMLProperties.getProperty("DMAAP_AAF_LOGIN"); + aafPassword = XACMLProperties.getProperty("DMAAP_AAF_PASSWORD"); + if (aafLogin != null) { + aafLogin = aafLogin.trim(); + } + if (aafPassword != null) { + aafPassword = aafPassword.trim(); + } + } + + private static void setCluster() { + clusterList = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_SERVERS); + if (clusterList != null) { + clusterList = clusterList.trim(); + } + } + + private static void setPropNotification() { + propNotificationType = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_TYPE); + } + + private void sendMessage(String topic, String message) { + CambriaPublisher pub = null; + BusPublisher publisher = null; + try { + if ("ueb".equals(propNotificationType)) { + pub = CambriaClientFactory.createSimplePublisher(null, clusterList, topic); + pub.send("pdpReturnMessage", message); + LOGGER.debug("Sending Message to UEB topic: " + topic); + pub.close(); + + } else if ("dmaap".equals(propNotificationType)) { + publisher = new BusPublisher.DmaapPublisherWrapper(dmaapList, topic, aafLogin, aafPassword); + publisher.send("pdpReturnMessage", message); + LOGGER.debug("Sending to Message to DMaaP topic: " + topic); + publisher.close(); + } + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error sending notification update: ", e); + } + if (pub != null) { + try { + pub.send("pdpReturnMessage", message); + LOGGER.debug("Sending to Message to tpoic" + topic); + pub.close(); + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error sending notification update" + e); + } + } + } + + private String processMessage(String msg) { + LOGGER.debug("notification message: " + msg); + String[] uID = msg.split("=")[1].split("\""); + + String returnTopic = topic + uID[0]; + if (msg.contains("Starting-Topic")) { + return null; + } + return returnTopic; + } + + public static void setUpdate(String update) { + ManualNotificationUpdateThread.update = update; + } + } diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/NotificationController.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/NotificationController.java index 109d421f8..577d5b347 100644 --- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/NotificationController.java +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/NotificationController.java @@ -59,284 +59,301 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; /** - * NotificationController Checks for the Updated and Removed policies. It - * notifies the Server to send Notifications to the Client. + * NotificationController Checks for the Updated and Removed policies. It notifies the Server to send Notifications to + * the Client. * * @version 0.2 * */ public class NotificationController { - private static final Logger LOGGER = FlexLogger.getLogger(NotificationController.class); - private static Notification record = new Notification(); - private PDPStatus oldStatus = null; - private Removed removed = null; - private Updated updated = null; - private ManualNotificationUpdateThread registerMaunualNotificationRunnable = null; - private Thread manualNotificationThread = null; - private boolean manualThreadStarted = false; - - private static String notificationJSON = null; - private static String propNotificationType = null; - private static String pdpURL = null; - private static Boolean notificationFlag = false; - - public void check(PDPStatus newStatus,Map<String, PolicyDef> policyContainer) { - boolean updated = false; - boolean removed = false; - Notification notification = new Notification(); - HashSet<Removed> removedPolicies = new HashSet<>(); - HashSet<Updated> updatedPolicies = new HashSet<>(); + private static final Logger LOGGER = FlexLogger.getLogger(NotificationController.class); + private static Notification record = new Notification(); + private PDPStatus oldStatus = null; + private Removed removed = null; + private Updated updated = null; + private ManualNotificationUpdateThread registerMaunualNotificationRunnable = null; + private Thread manualNotificationThread = null; + private boolean manualThreadStarted = false; - if (oldStatus == null) { - oldStatus = newStatus; - } - // Debugging purpose only. - LOGGER.debug("old config Status :" + oldStatus.getStatus()); - LOGGER.debug("new config Status :" + newStatus.getStatus()); + private static String notificationJSON = null; + private static String propNotificationType = null; + private static String pdpURL = null; + private static Boolean notificationFlag = false; - // Depending on the above condition taking the Change as an Update. - if (oldStatus.getStatus().toString() != newStatus.getStatus().toString()) { - LOGGER.info("There is an Update to the PDP"); - LOGGER.debug(oldStatus.getLoadedPolicies()); - LOGGER.debug(newStatus.getLoadedPolicies()); - // Check if there is an Update/additions in the policy. - for (PDPPolicy newPolicy : newStatus.getLoadedPolicies()) { - boolean change = true; - for (PDPPolicy oldPolicy : oldStatus.getLoadedPolicies()) { - // Check if there are same policies. - if (oldPolicy.getId().equals(newPolicy.getId())) { - // Check if they have same version. - if (oldPolicy.getVersion().equals(newPolicy.getVersion())) { - change = false; - } - } - } - // if there is a change Send the notifications to the Client. - if (change) { - sendUpdate(newPolicy, policyContainer); - updated = true; - updatedPolicies.add(this.updated); - } - } - // Check if there is any removal of policy. - for (PDPPolicy oldPolicy : oldStatus.getLoadedPolicies()) { - boolean change = true; - for (PDPPolicy newPolicy : newStatus.getLoadedPolicies()) { - // Check if there are same policies. - if (oldPolicy.getId().equals(newPolicy.getId())) { - // Check if they have same version. - if (oldPolicy.getVersion().equals(newPolicy.getVersion())) { - change = false; - } - } - } - // if there is a change Send the notifications to the Client. - if (change) { - sendremove(oldPolicy); - removed = true; - removedPolicies.add(this.removed); - } - } - } - // At the end the oldStatus must be updated with the newStatus. - oldStatus = newStatus; - // Sending Notification to the Server to pass over to the clients - if (updated || removed) { - // Call the Notification Server.. - notification.setRemovedPolicies(removedPolicies); - notification.setLoadedPolicies(updatedPolicies); - notification = setUpdateTypes(updated, removed, notification); - ObjectWriter om = new ObjectMapper().writer(); - try { - notificationJSON = om.writeValueAsString(notification); - LOGGER.info(notificationJSON); - // NotificationServer Method here. - propNotificationType = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_TYPE); - pdpURL = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_ID); - if (("ueb".equals(propNotificationType)||"dmaap".equals(propNotificationType)) && !manualThreadStarted) { - LOGGER.debug("Starting Thread to accept UEB or DMAAP notfications."); - this.registerMaunualNotificationRunnable = new ManualNotificationUpdateThread(); - this.manualNotificationThread = new Thread(this.registerMaunualNotificationRunnable); - this.manualNotificationThread.start(); - manualThreadStarted = true; - } - String notificationJSON= null; - notificationFlag = true; - try{ - notificationJSON= record(notification); - }catch(Exception e){ - LOGGER.error(e); - } - NotificationServer.setUpdate(notificationJSON); - ManualNotificationUpdateThread.setUpdate(notificationJSON); - } catch (JsonProcessingException e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage() +e); - } - } - } - - public static void sendNotification(){ - if(notificationFlag){ - try { - NotificationServer.sendNotification(notificationJSON, propNotificationType, pdpURL); - } catch (Exception e) { - LOGGER.info(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error in sending the Event Notification: "+ e.getMessage() + e); - } - notificationFlag = false; - } - } - - private void sendremove(PDPPolicy oldPolicy) { - removed = new Removed(); - // Want to know what is removed ? - LOGGER.info("Policy removed: " + oldPolicy.getId()+ " with version number: " + oldPolicy.getVersion()); - removed.setPolicyName(oldPolicy.getId()); - removed.setVersionNo(oldPolicy.getVersion()); - removeFile(oldPolicy); - } + public void check(PDPStatus newStatus, Map<String, PolicyDef> policyContainer) { + boolean updated = false; + boolean removed = false; + Notification notification = new Notification(); + HashSet<Removed> removedPolicies = new HashSet<>(); + HashSet<Updated> updatedPolicies = new HashSet<>(); - private void sendUpdate(PDPPolicy newPolicy,Map<String, PolicyDef> policyContainer) { - updated = new Updated(); - // Want to know what is new ? - LOGGER.info("The new Policy is: " + newPolicy.getId()); - LOGGER.info("The version no. is: " + newPolicy.getVersion()); - updated.setPolicyName(newPolicy.getId()); - updated.setVersionNo(newPolicy.getVersion()); - updated.setUpdateType(UpdateType.NEW); - // If the policy is of Config type then retrieve its matches. - if (newPolicy.getName().contains(".Config_")) { - // Take a Configuration copy to PDP webapps. - final String urlStart = "attributeId=URLID,expression"; - final String urlEnd = "}}},{"; - String policy = policyContainer.get(newPolicy.getId()).toString(); - if(policy.contains(urlStart)){ - String urlFinePartOne = policy.substring(policy.indexOf(urlStart)+urlStart.length()); - String urlFinePart = urlFinePartOne.substring(0,urlFinePartOne.indexOf(urlEnd)); - String urlString = urlFinePart.substring(urlFinePart.indexOf("value=$URL")+6); - callPap(urlString, "Config"); - } - Iterator<AnyOf> anyOfs = policyContainer.get(newPolicy.getId()).getTarget().getAnyOfs(); - while (anyOfs.hasNext()) { - AnyOf anyOf = anyOfs.next(); - Iterator<AllOf> allOfs = anyOf.getAllOfs(); - while (allOfs.hasNext()) { - AllOf allOf = allOfs.next(); - Iterator<Match> matches = allOf.getMatches(); - HashMap<String, String> matchValues = new HashMap<>(); - while (matches.hasNext()) { - Match match = matches.next(); - LOGGER.info("Attribute Value is: "+ match.getAttributeValue().getValue().toString()); - String[] result = match.getAttributeRetrievalBase().toString().split("attributeId="); - result[1] = result[1].replaceAll("}", ""); - if (!result[1].equals("urn:oasis:names:tc:xacml:1.0:subject:subject-id")) { - LOGGER.info("Attribute id is: " + result[1]); - } - matchValues.put(result[1], match.getAttributeValue().getValue().toString()); - LOGGER.info("Match is : "+ result[1]+ " , " + match.getAttributeValue().getValue().toString()); - } - updated.setMatches(matchValues); - } - } - }else if(newPolicy.getName().contains(".Action_")){ - // Take Configuration copy to PDP Webapps. - // Action policies have .json as extension. - String urlString = "$URL/Action/" + newPolicy.getId().substring(0, newPolicy.getId().lastIndexOf(".")) + ".json"; - callPap(urlString, "Action"); - } - } + if (oldStatus == null) { + oldStatus = newStatus; + } + // Debugging purpose only. + LOGGER.debug("old config Status :" + oldStatus.getStatus()); + LOGGER.debug("new config Status :" + newStatus.getStatus()); + + // Depending on the above condition taking the Change as an Update. + if (oldStatus.getStatus().toString() != newStatus.getStatus().toString()) { + LOGGER.info("There is an Update to the PDP"); + LOGGER.debug(oldStatus.getLoadedPolicies()); + LOGGER.debug(newStatus.getLoadedPolicies()); + // Check if there is an Update/additions in the policy. + for (PDPPolicy newPolicy : newStatus.getLoadedPolicies()) { + boolean change = true; + for (PDPPolicy oldPolicy : oldStatus.getLoadedPolicies()) { + // Check if there are same policies. + if (oldPolicy.getId().equals(newPolicy.getId())) { + // Check if they have same version. + if (oldPolicy.getVersion().equals(newPolicy.getVersion())) { + change = false; + } + } + } + // if there is a change Send the notifications to the Client. + if (change) { + sendUpdate(newPolicy, policyContainer); + updated = true; + updatedPolicies.add(this.updated); + } + } + // Check if there is any removal of policy. + for (PDPPolicy oldPolicy : oldStatus.getLoadedPolicies()) { + boolean change = true; + for (PDPPolicy newPolicy : newStatus.getLoadedPolicies()) { + // Check if there are same policies. + if (oldPolicy.getId().equals(newPolicy.getId())) { + // Check if they have same version. + if (oldPolicy.getVersion().equals(newPolicy.getVersion())) { + change = false; + } + } + } + // if there is a change Send the notifications to the Client. + if (change) { + sendremove(oldPolicy); + removed = true; + removedPolicies.add(this.removed); + } + } + } + // At the end the oldStatus must be updated with the newStatus. + oldStatus = newStatus; + // Sending Notification to the Server to pass over to the clients + if (updated || removed) { + // Call the Notification Server.. + notification.setRemovedPolicies(removedPolicies); + notification.setLoadedPolicies(updatedPolicies); + notification = setUpdateTypes(updated, removed, notification); + ObjectWriter om = new ObjectMapper().writer(); + try { + setNotificationJSON(om.writeValueAsString(notification)); + LOGGER.info(notificationJSON); + // NotificationServer Method here. + setPropNotification(); + if (("ueb".equals(propNotificationType) || "dmaap".equals(propNotificationType)) + && !manualThreadStarted) { + LOGGER.debug("Starting Thread to accept UEB or DMAAP notfications."); + this.registerMaunualNotificationRunnable = new ManualNotificationUpdateThread(); + this.manualNotificationThread = new Thread(this.registerMaunualNotificationRunnable); + this.manualNotificationThread.start(); + manualThreadStarted = true; + } + String notificationJSONString = null; + setNotificationFlag(true); + try { + notificationJSONString = record(notification); + } catch (Exception e) { + LOGGER.error(e); + } + NotificationServer.setUpdate(notificationJSONString); + ManualNotificationUpdateThread.setUpdate(notificationJSONString); + } catch (JsonProcessingException e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage() + e); + } + } + } + + private void setNotificationFlag(boolean value) { + notificationFlag = value; + } + + private static void setNotificationJSON(String message) { + notificationJSON = message; + } + + private static void setPropNotification() { + propNotificationType = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_TYPE); + pdpURL = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_ID); + } + + public static void sendNotification() { + if (notificationFlag) { + try { + NotificationServer.sendNotification(notificationJSON, propNotificationType, pdpURL); + } catch (Exception e) { + LOGGER.info(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error in sending the Event Notification: " + + e.getMessage() + e); + } + notificationFlag = false; + } + } + + private void sendremove(PDPPolicy oldPolicy) { + removed = new Removed(); + // Want to know what is removed ? + LOGGER.info("Policy removed: " + oldPolicy.getId() + " with version number: " + oldPolicy.getVersion()); + removed.setPolicyName(oldPolicy.getId()); + removed.setVersionNo(oldPolicy.getVersion()); + removeFile(oldPolicy); + } + + private void sendUpdate(PDPPolicy newPolicy, Map<String, PolicyDef> policyContainer) { + updated = new Updated(); + // Want to know what is new ? + LOGGER.info("The new Policy is: " + newPolicy.getId()); + LOGGER.info("The version no. is: " + newPolicy.getVersion()); + updated.setPolicyName(newPolicy.getId()); + updated.setVersionNo(newPolicy.getVersion()); + updated.setUpdateType(UpdateType.NEW); + // If the policy is of Config type then retrieve its matches. + if (newPolicy.getName().contains(".Config_")) { + // Take a Configuration copy to PDP webapps. + final String urlStart = "attributeId=URLID,expression"; + final String urlEnd = "}}},{"; + String policy = policyContainer.get(newPolicy.getId()).toString(); + if (policy.contains(urlStart)) { + String urlFinePartOne = policy.substring(policy.indexOf(urlStart) + urlStart.length()); + String urlFinePart = urlFinePartOne.substring(0, urlFinePartOne.indexOf(urlEnd)); + String urlString = urlFinePart.substring(urlFinePart.indexOf("value=$URL") + 6); + callPap(urlString, "Config"); + } + Iterator<AnyOf> anyOfs = policyContainer.get(newPolicy.getId()).getTarget().getAnyOfs(); + while (anyOfs.hasNext()) { + AnyOf anyOf = anyOfs.next(); + Iterator<AllOf> allOfs = anyOf.getAllOfs(); + while (allOfs.hasNext()) { + AllOf allOf = allOfs.next(); + Iterator<Match> matches = allOf.getMatches(); + HashMap<String, String> matchValues = new HashMap<>(); + while (matches.hasNext()) { + Match match = matches.next(); + LOGGER.info("Attribute Value is: " + match.getAttributeValue().getValue().toString()); + String[] result = match.getAttributeRetrievalBase().toString().split("attributeId="); + result[1] = result[1].replaceAll("}", ""); + if (!result[1].equals("urn:oasis:names:tc:xacml:1.0:subject:subject-id")) { + LOGGER.info("Attribute id is: " + result[1]); + } + matchValues.put(result[1], match.getAttributeValue().getValue().toString()); + LOGGER.info( + "Match is : " + result[1] + " , " + match.getAttributeValue().getValue().toString()); + } + updated.setMatches(matchValues); + } + } + } else if (newPolicy.getName().contains(".Action_")) { + // Take Configuration copy to PDP Webapps. + // Action policies have .json as extension. + String urlString = "$URL/Action/" + newPolicy.getId().substring(0, newPolicy.getId().lastIndexOf(".")) + + ".json"; + callPap(urlString, "Action"); + } + } + + // Adding this for Recording the changes to serve Polling requests.. + private static String record(Notification notification) { + // Initialization with updates. + if (record.getRemovedPolicies() == null || record.getLoadedPolicies() == null) { + record.setRemovedPolicies(notification.getRemovedPolicies()); + record.setLoadedPolicies(notification.getLoadedPolicies()); + } else { + // Check if there is anything new and update the record.. + if (record.getLoadedPolicies() != null || record.getRemovedPolicies() != null) { + HashSet<Removed> removedPolicies = (HashSet<Removed>) record.getRemovedPolicies(); + HashSet<Updated> updatedPolicies = (HashSet<Updated>) record.getLoadedPolicies(); - // Adding this for Recording the changes to serve Polling requests.. - private static String record(Notification notification) throws Exception { - // Initialization with updates. - if (record.getRemovedPolicies() == null || record.getLoadedPolicies() == null) { - record.setRemovedPolicies(notification.getRemovedPolicies()); - record.setLoadedPolicies(notification.getLoadedPolicies()); - } else { - // Check if there is anything new and update the record.. - if (record.getLoadedPolicies() != null || record.getRemovedPolicies() != null) { - HashSet<Removed> removedPolicies = (HashSet<Removed>) record.getRemovedPolicies(); - HashSet<Updated> updatedPolicies = (HashSet<Updated>) record.getLoadedPolicies(); + // Checking with New updated policies. + if (notification.getLoadedPolicies() != null && !notification.getLoadedPolicies().isEmpty()) { + for (Updated newUpdatedPolicy : notification.getLoadedPolicies()) { + // If it was removed earlier then we need to remove from our record + Iterator<Removed> oldRemovedPolicy = removedPolicies.iterator(); + while (oldRemovedPolicy.hasNext()) { + Removed policy = oldRemovedPolicy.next(); + if (newUpdatedPolicy.getPolicyName().equals(policy.getPolicyName())) { + if (newUpdatedPolicy.getVersionNo().equals(policy.getVersionNo())) { + oldRemovedPolicy.remove(); + } + } + } + // If it was previously updated need to Overwrite it to the record. + Iterator<Updated> oldUpdatedPolicy = updatedPolicies.iterator(); + while (oldUpdatedPolicy.hasNext()) { + Updated policy = oldUpdatedPolicy.next(); + if (newUpdatedPolicy.getPolicyName().equals(policy.getPolicyName())) { + if (newUpdatedPolicy.getVersionNo().equals(policy.getVersionNo())) { + oldUpdatedPolicy.remove(); + } + } + } + updatedPolicies.add(newUpdatedPolicy); + } + } + // Checking with New Removed policies. + if (notification.getRemovedPolicies() != null && !notification.getRemovedPolicies().isEmpty()) { + for (Removed newRemovedPolicy : notification.getRemovedPolicies()) { + // If it was previously removed Overwrite it to the record. + Iterator<Removed> oldRemovedPolicy = removedPolicies.iterator(); + while (oldRemovedPolicy.hasNext()) { + Removed policy = oldRemovedPolicy.next(); + if (newRemovedPolicy.getPolicyName().equals(policy.getPolicyName())) { + if (newRemovedPolicy.getVersionNo().equals(policy.getVersionNo())) { + oldRemovedPolicy.remove(); + } + } + } + // If it was added earlier then we need to remove from our record. + Iterator<Updated> oldUpdatedPolicy = updatedPolicies.iterator(); + while (oldUpdatedPolicy.hasNext()) { + Updated policy = oldUpdatedPolicy.next(); + if (newRemovedPolicy.getPolicyName().equals(policy.getPolicyName())) { + if (newRemovedPolicy.getVersionNo().equals(policy.getVersionNo())) { + oldUpdatedPolicy.remove(); + } + } + } + removedPolicies.add(newRemovedPolicy); + } + } + record.setRemovedPolicies(removedPolicies); + record.setLoadedPolicies(updatedPolicies); + } + } + // Send the Result to the caller. + ObjectWriter om = new ObjectMapper().writer(); + String json = null; + try { + json = om.writeValueAsString(record); + } catch (JsonProcessingException e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage() + e); + } + LOGGER.info(json); + return json; + } - // Checking with New updated policies. - if (notification.getLoadedPolicies() != null && !notification.getLoadedPolicies().isEmpty()) { - for (Updated newUpdatedPolicy : notification.getLoadedPolicies()) { - // If it was removed earlier then we need to remove from our record - Iterator<Removed> oldRemovedPolicy = removedPolicies.iterator(); - while (oldRemovedPolicy.hasNext()) { - Removed policy = oldRemovedPolicy.next(); - if (newUpdatedPolicy.getPolicyName().equals(policy.getPolicyName())) { - if (newUpdatedPolicy.getVersionNo().equals(policy.getVersionNo())) { - oldRemovedPolicy.remove(); - } - } - } - // If it was previously updated need to Overwrite it to the record. - Iterator<Updated> oldUpdatedPolicy = updatedPolicies.iterator(); - while (oldUpdatedPolicy.hasNext()) { - Updated policy = oldUpdatedPolicy.next(); - if (newUpdatedPolicy.getPolicyName().equals(policy.getPolicyName())) { - if (newUpdatedPolicy.getVersionNo().equals(policy.getVersionNo())) { - oldUpdatedPolicy.remove(); - } - } - } - updatedPolicies.add(newUpdatedPolicy); - } - } - // Checking with New Removed policies. - if (notification.getRemovedPolicies() != null && !notification.getRemovedPolicies().isEmpty()) { - for (Removed newRemovedPolicy : notification.getRemovedPolicies()) { - // If it was previously removed Overwrite it to the record. - Iterator<Removed> oldRemovedPolicy = removedPolicies.iterator(); - while (oldRemovedPolicy.hasNext()) { - Removed policy = oldRemovedPolicy.next(); - if (newRemovedPolicy.getPolicyName().equals(policy.getPolicyName())) { - if (newRemovedPolicy.getVersionNo().equals(policy.getVersionNo())) { - oldRemovedPolicy.remove(); - } - } - } - // If it was added earlier then we need to remove from our record. - Iterator<Updated> oldUpdatedPolicy = updatedPolicies.iterator(); - while (oldUpdatedPolicy.hasNext()) { - Updated policy = oldUpdatedPolicy.next(); - if (newRemovedPolicy.getPolicyName().equals(policy.getPolicyName())) { - if (newRemovedPolicy.getVersionNo().equals(policy.getVersionNo())) { - oldUpdatedPolicy.remove(); - } - } - } - removedPolicies.add(newRemovedPolicy); - } - } - record.setRemovedPolicies(removedPolicies); - record.setLoadedPolicies(updatedPolicies); - } - } - // Send the Result to the caller. - ObjectWriter om = new ObjectMapper().writer(); - String json = null; - try { - json = om.writeValueAsString(record); - } catch (JsonProcessingException e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage() + e); - } - LOGGER.info(json); - return json; - } - - private static Notification setUpdateTypes(boolean updated, boolean removed, Notification notification) { - if(notification!=null){ - if(updated && removed){ + private static Notification setUpdateTypes(boolean updated, boolean removed, Notification notification) { + if (notification != null) { + if (updated && removed) { notification.setNotificationType(NotificationType.BOTH); - if(notification.getLoadedPolicies()!=null){ - HashSet<Updated> updatedPolicies = new HashSet<>(); - for(Updated oldUpdatedPolicy: notification.getLoadedPolicies()){ + if (notification.getLoadedPolicies() != null) { + HashSet<Updated> updatedPolicies = new HashSet<>(); + for (Updated oldUpdatedPolicy : notification.getLoadedPolicies()) { Updated updatePolicy = oldUpdatedPolicy; - if(notification.getRemovedPolicies()!=null){ - for(RemovedPolicy removedPolicy: notification.getRemovedPolicies()){ + if (notification.getRemovedPolicies() != null) { + for (RemovedPolicy removedPolicy : notification.getRemovedPolicies()) { String regex = ".(\\d)*.xml"; - if(removedPolicy.getPolicyName().replaceAll(regex, "").equals(oldUpdatedPolicy.getPolicyName().replaceAll(regex, ""))){ + if (removedPolicy.getPolicyName().replaceAll(regex, "") + .equals(oldUpdatedPolicy.getPolicyName().replaceAll(regex, ""))) { updatePolicy.setUpdateType(UpdateType.UPDATE); break; } @@ -346,70 +363,76 @@ public class NotificationController { } notification.setLoadedPolicies(updatedPolicies); } - }else if(updated){ + } else if (updated) { notification.setNotificationType(NotificationType.UPDATE); - }else if(removed){ + } else if (removed) { notification.setNotificationType(NotificationType.REMOVE); } } return notification; } - - private void removeFile(PDPPolicy oldPolicy) { - try{ - Path removedPolicyFile = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_CONFIG)+File.separator+oldPolicy.getId()); - Files.deleteIfExists(removedPolicyFile); - boolean delete=false; - File dir= null; - if(oldPolicy.getName().contains(".Config_")){ - delete = true; - dir = new File(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_WEBAPPS)+File.separator+"Config"); - }else if(oldPolicy.getName().contains(".Action_")){ - delete = true; - dir = new File(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_WEBAPPS)+File.separator+"Action"); - } - if(delete){ - FileFilter fileFilter = new WildcardFileFilter(oldPolicy.getId().substring(0, oldPolicy.getId().lastIndexOf("."))+".*"); - File[] configFile = dir.listFiles(fileFilter); - if(configFile.length==1){ - Files.deleteIfExists(configFile[0].toPath()); - } - } - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Couldn't remove the policy/config file " + oldPolicy.getName() + e); - } - } - - private void callPap(String urlString, String type) { - Path configLocation = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_WEBAPPS)+File.separator+type); - if(Files.notExists(configLocation)){ - try { - Files.createDirectories(configLocation); - } catch (IOException e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW +"Failed to create config directory: " + configLocation.toAbsolutePath().toString(), e); - } - } - PapUrlResolver papUrls = PapUrlResolver.getInstance(); - while(papUrls.hasMoreUrls()){ - String papPath = papUrls.getUrl(); - papPath = papPath.substring(0, papPath.lastIndexOf("/pap")); - String papAddress= urlString.replace("$URL", papPath); - String fileName = papAddress.substring(papAddress.lastIndexOf("/")+1); - String fileLocation = configLocation.toString() + File.separator + fileName; - try { - URL papURL = new URL(papAddress); - LOGGER.info("Calling " +papAddress + " for Configuration Copy."); - URLConnection urlConnection = papURL.openConnection(); - File file= new File(fileLocation); - try (InputStream is = urlConnection.getInputStream(); - OutputStream os = new FileOutputStream(file)) { - IOUtils.copy(is, os); - break; - } - } catch (Exception e) { - LOGGER.error(e + e.getMessage()); - } - papUrls.getNext(); - } - } + + private void removeFile(PDPPolicy oldPolicy) { + try { + Path removedPolicyFile = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_CONFIG) + + File.separator + oldPolicy.getId()); + Files.deleteIfExists(removedPolicyFile); + boolean delete = false; + File dir = null; + if (oldPolicy.getName().contains(".Config_")) { + delete = true; + dir = new File( + XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_WEBAPPS) + File.separator + "Config"); + } else if (oldPolicy.getName().contains(".Action_")) { + delete = true; + dir = new File( + XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_WEBAPPS) + File.separator + "Action"); + } + if (delete) { + FileFilter fileFilter = new WildcardFileFilter( + oldPolicy.getId().substring(0, oldPolicy.getId().lastIndexOf(".")) + ".*"); + File[] configFile = dir.listFiles(fileFilter); + if (configFile.length == 1) { + Files.deleteIfExists(configFile[0].toPath()); + } + } + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Couldn't remove the policy/config file " + + oldPolicy.getName() + e); + } + } + + private void callPap(String urlString, String type) { + Path configLocation = Paths + .get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_WEBAPPS) + File.separator + type); + if (Files.notExists(configLocation)) { + try { + Files.createDirectories(configLocation); + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create config directory: " + + configLocation.toAbsolutePath().toString(), e); + } + } + PapUrlResolver papUrls = PapUrlResolver.getInstance(); + while (papUrls.hasMoreUrls()) { + String papPath = papUrls.getUrl(); + papPath = papPath.substring(0, papPath.lastIndexOf("/pap")); + String papAddress = urlString.replace("$URL", papPath); + String fileName = papAddress.substring(papAddress.lastIndexOf("/") + 1); + String fileLocation = configLocation.toString() + File.separator + fileName; + try { + URL papURL = new URL(papAddress); + LOGGER.info("Calling " + papAddress + " for Configuration Copy."); + URLConnection urlConnection = papURL.openConnection(); + File file = new File(fileLocation); + try (InputStream is = urlConnection.getInputStream(); OutputStream os = new FileOutputStream(file)) { + IOUtils.copy(is, os); + break; + } + } catch (Exception e) { + LOGGER.error(e + e.getMessage()); + } + papUrls.getNext(); + } + } } diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/NotificationServer.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/NotificationServer.java index 690d8c517..2f3d58203 100644 --- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/NotificationServer.java +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/NotificationServer.java @@ -38,6 +38,7 @@ import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; +import org.onap.policy.api.PolicyEngineException; import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -66,8 +67,6 @@ public class NotificationServer { private static final Logger LOGGER = FlexLogger.getLogger(NotificationServer.class); private static Queue<Session> queue = new ConcurrentLinkedQueue<>(); private static String update = null; - private static String hosts = null; - private static URL aURL = null; @OnOpen public void openConnection(Session session) { @@ -88,7 +87,7 @@ public class NotificationServer { } @OnMessage - public void Message(String message, Session session) { + public void message(String message, Session session) { if(message.equalsIgnoreCase("Manual")) { try { @@ -101,14 +100,14 @@ public class NotificationServer { } } - public static void sendNotification(String notification, String propNotificationType, String pdpURL) throws Exception { + public static void sendNotification(String notification, String propNotificationType, String pdpURL) throws PolicyEngineException, IOException, InterruptedException { LOGGER.debug("Notification set to " + propNotificationType); if (propNotificationType.equals("ueb")){ String topic = null; try { - aURL = new URL(pdpURL); + URL aURL = new URL(pdpURL); topic = aURL.getHost() + aURL.getPort(); } catch (MalformedURLException e1) { pdpURL = pdpURL.replace("/", ""); @@ -116,7 +115,7 @@ public class NotificationServer { LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error in parsing out pdpURL for UEB notfication "); PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e1, "Error in parsing out pdpURL for UEB notfication "); } - hosts = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_SERVERS); + String hosts = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_SERVERS); String apiKey = XACMLProperties.getProperty(XACMLRestProperties.PROP_UEB_API_KEY); String apiSecret = XACMLProperties.getProperty(XACMLRestProperties.PROP_UEB_API_SECRET); @@ -125,13 +124,13 @@ public class NotificationServer { try { if(hosts==null || topic==null || apiKey==null || apiSecret==null){ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file "); - throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file "); + throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file "); } - hosts.trim(); - topic.trim(); - apiKey.trim(); - apiSecret.trim(); + hosts = hosts.trim(); + topic = topic.trim(); + apiKey = apiKey.trim(); + apiSecret = apiSecret.trim(); pub = new CambriaClientBuilders.PublisherBuilder () .usingHosts ( hosts ) .onTopic ( topic ) @@ -175,13 +174,13 @@ public class NotificationServer { try { if(dmaapServers==null || topic==null){ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file "); - throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file "); + throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file "); } - dmaapServers.trim(); - topic.trim(); - aafLogin.trim(); - aafPassword.trim(); + dmaapServers= dmaapServers.trim(); + topic= topic.trim(); + aafLogin= aafLogin.trim(); + aafPassword= aafPassword.trim(); List<String> dmaapList = null; if(dmaapServers.contains(",")) { diff --git a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/PolicyEngineServicesTest.java b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/PolicyEngineServicesTest.java index aa55a2a14..fe4ce0599 100644 --- a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/PolicyEngineServicesTest.java +++ b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/PolicyEngineServicesTest.java @@ -195,6 +195,9 @@ public class PolicyEngineServicesTest { @Test public void getNotificationTopicValidPassTest() throws Exception{ + XACMLProperties.reloadProperties(); + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/notification.xacml.pdp.properties"); + XACMLProperties.getProperties(); // Add a Topic. mockMvc.perform(post("/getNotification").headers(headers).header(UUIDHEADER, "123").content("test")).andExpect(status().isOk()); // Try to add same topic should fail. diff --git a/ONAP-PDP-REST/src/test/resources/notification.xacml.pdp.properties b/ONAP-PDP-REST/src/test/resources/notification.xacml.pdp.properties new file mode 100644 index 000000000..9ca1bba9c --- /dev/null +++ b/ONAP-PDP-REST/src/test/resources/notification.xacml.pdp.properties @@ -0,0 +1,171 @@ +### +# ============LICENSE_START======================================================= +# ONAP-PDP-REST +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============LICENSE_END========================================================= +### + +# Default XACML Properties File for PDP RESTful servlet +# +# Standard API Factories +# +xacml.dataTypeFactory=com.att.research.xacml.std.StdDataTypeFactory +xacml.pdpEngineFactory=com.att.research.xacmlatt.pdp.ATTPDPEngineFactory +xacml.pepEngineFactory=com.att.research.xacml.std.pep.StdEngineFactory +# NOT USED SEE BELOW xacml.pipFinderFactory=org.onap.policy.xacml.std.pip.StdPIPFinderFactory +xacml.traceEngineFactory=com.att.research.xacml.std.trace.LoggingTraceEngineFactory +# +# AT&T PDP Implementation Factories +# +xacml.att.evaluationContextFactory=com.att.research.xacmlatt.pdp.std.StdEvaluationContextFactory +xacml.att.combiningAlgorithmFactory=com.att.research.xacmlatt.pdp.std.StdCombiningAlgorithmFactory +xacml.att.functionDefinitionFactory=org.onap.policy.xacml.custom.OnapFunctionDefinitionFactory +# NOT USED SEE BELOW xacml.att.policyFinderFactory=org.onap.policy.pdp.std.StdPolicyFinderFactory +# creteUpdate Policy Implementation Class details. +createUpdatePolicy.impl.className=org.onap.policy.pdp.rest.api.services.CreateUpdatePolicyServiceImpl +# AAF Implementation class details +aafClient.impl.className=org.onap.policy.utils.AAFPolicyClientImpl +# +# AT&T RESTful PDP Implementation Factories +# +xacml.pipFinderFactory=org.onap.policy.pdp.rest.impl.XACMLPdpPIPFinderFactory +xacml.att.policyFinderFactory=org.onap.policy.pdp.rest.XACMLPdpPolicyFinderFactory +# +# When set to true, this flag tells the StdPolicyFinderFactory to combined all the root policy files into +# into one PolicySet and use the given Policy Algorithm. +# +xacml.att.policyFinderFactory.combineRootPolicies=urn:com:att:xacml:3.0:policy-combining-algorithm:combined-permit-overrides +# +# PDP RESTful API properties +# +# Set this to the address where the XACML-PAP-REST servlet is running +xacml.rest.pap.url=http://localhost:8070/pap/ + +#if multiple paps exist, the xacml.rest.pap.url can be removed and they can be defined like this: +#xacml.rest.pap.urls=http://localhost:9090/pap/,http://localhost:9091/pap/ + +# +# Give the running PDP an ID for the PAP. The url that its running as is a good choice. +# The PAP identifies PDP's using the URL of the PDP. +# +xacml.rest.pdp.id=http://localhost:8082/pdp/ + +# Give the port number used for the PDP + +xacml.jmx.port=0 + + +# Notification Properties +# Notifcation type: websocket, ueb or dmaap... if left blank websocket is the default +NOTIFICATION_TYPE=websocket +NOTIFICATION_SERVERS=test +NOTIFICATION_TOPIC=test +NOTIFICATION_DELAY=5000 +UEB_API_KEY= +UEB_API_SECRET= +DMAAP_AAF_LOGIN=test +DMAAP_AAF_PASSWORD=test + +# +# Set the directory where the PDP holds its Policy Cache and PIP Configuration +# +xacml.rest.pdp.config=config + +xacml.rest.pdp.webapps=/home/users/PolicyEngine/webapps/ConfigPAP/ +# +# Initialize register with PAP servlet +# +xacml.rest.pdp.register=true +# +# Sleep period in seconds between register attempts +# +xacml.rest.pdp.register.sleep=15 +# +# number of attempts to register. -1 means keep trying forever. +# +xacml.rest.pdp.register.retries=-1 +# +# max number of bytes in a POST of a XML/JSON request +# old value #32767 +xacml.rest.pdp.maxcontent=99999999 +# +# Set UserID here +xacml.rest.pdp.userid=testpdp +# Set Password here +xacml.rest.pdp.password=alpha456 + +# id PAP +xacml.rest.pap.userid=testpap +#if multiple paps have different logins, they can be defined like this: +#http\://localhost\:9090/pap/.xacml.rest.pap.userid=testpap + +# pass PAP +xacml.rest.pap.password=alpha123 +#http\://localhost\:9090/pap/.xacml.rest.pap.password=alpha123 + +# Delay for Notifications Don't change this. Value in milliSec. +xacml.rest.notification.delay=30 +# Buffer Size. +REQUEST_BUFFER_SIZE=15 + +#properties for MySql xacml database: PLEASE DO NOT REMOVE... NEEDED FOR APIs +javax.persistence.jdbc.driver=com.mysql.jdbc.Driver +javax.persistence.jdbc.url=jdbc:mysql://localhost:3306/xacml +javax.persistence.jdbc.user=policy_user +javax.persistence.jdbc.password=policy_user + + +#***Properties for IntegrityMonitor integration defined in XACMLRestProperties.java*** + +#The name of the PDP. Must be unique across the system +xacml.rest.pdp.resource.name=site_1.pdp_1 + +#***Properties for IntegrityMonitor integration defined in IntegrityMonitorProperties.java*** + +#Interval between forward progress counter updates in seconds +fp_monitor_interval=30 + +#Number of forward progress counter failures before failover +failed_counter_threshold=3 + +#Interval in seconds between test transactions if there is no other traffic +test_trans_interval=10 + +#Interval in seconds between updates of the forward progress counter in the DB +write_fpc_interval=5 + +#Name of the site +site_name=site_1 + +#Node type +node_type=pdp_xacml + +#Dependency groups are groups of resources upon which a node operational state is dependent upon). +#Each group is a comma-separated list of resource names and groups are separated by a semicolon. +#A group may contain one or more members. Resource names must match the resource names defined +#in the respective servers' properties files +dependency_groups=site_1.pdplp_1;site_1.astragw_1;site_1.brmsgw_1 + +# this can be DEVL, TEST, PROD +ENVIRONMENT=DEVL +xacml.rest.pep.idfile = src/test/resources/client.properties + +#AAF Policy Name space +#Not Mandatory for Open Onap +policy.aaf.namespace = +policy.aaf.resource = +# +DMAAP_AAF_LOGIN = diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/XACMLRestProperties.java b/ONAP-REST/src/main/java/org/onap/policy/rest/XACMLRestProperties.java index 5c8449603..73cb0f07e 100644 --- a/ONAP-REST/src/main/java/org/onap/policy/rest/XACMLRestProperties.java +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/XACMLRestProperties.java @@ -95,7 +95,6 @@ public class XACMLRestProperties extends XACMLProperties { public static final String PROP_PAP_URLS = "xacml.rest.pap.urls"; public static final String PROP_PAP_FAILED_URLS = "xacml.rest.pap.failedUrls"; public static final String PROP_PAP_SUCCEEDED_URLS = "xacml.rest.pap.succeededUrls"; - //public static final String PROP_PAP_FAILED_URL_TIME = "xacml.rest.pap.failedUrlTime"; /** * Upon startup, have the PAP servlet send latest configuration information diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/XacmlAdminAuthorization.java b/ONAP-REST/src/main/java/org/onap/policy/rest/XacmlAdminAuthorization.java index c8dc71918..c29e17637 100644 --- a/ONAP-REST/src/main/java/org/onap/policy/rest/XacmlAdminAuthorization.java +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/XacmlAdminAuthorization.java @@ -52,7 +52,7 @@ public class XacmlAdminAuthorization { return userId; } - public void setUserId(UserInfo userId) { + public static void setUserId(UserInfo userId) { XacmlAdminAuthorization.userId = userId; } @@ -66,6 +66,7 @@ public class XacmlAdminAuthorization { AdminAction(String a) { this.action = a; } + @Override public String toString() { return this.action; } @@ -84,6 +85,7 @@ public class XacmlAdminAuthorization { AdminResource(String r) { this.resource = r; } + @Override public String toString() { return this.resource; } @@ -102,6 +104,7 @@ public class XacmlAdminAuthorization { Role(String a) { this.userRole = a; } + @Override public String toString() { return this.userRole; } diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyEntity.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyEntity.java index 57daf7ed8..6c7b8cf6f 100644 --- a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyEntity.java +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyEntity.java @@ -317,8 +317,8 @@ public class PolicyEntity implements Serializable { version == p.version && policyVersion == p.policyVersion && policyData.equals(p.policyData) && - ((configurationDataEntity == null && p.configurationDataEntity == null) || configurationDataEntity.equals(p.configurationDataEntity)) && - ((actionBodyEntity == null && p.actionBodyEntity == null) || actionBodyEntity.equals(p.actionBodyEntity)) && + ((configurationDataEntity == null && p.configurationDataEntity == null) || (configurationDataEntity!=null && configurationDataEntity.equals(p.configurationDataEntity))) && + ((actionBodyEntity == null && p.actionBodyEntity == null) || (actionBodyEntity!=null && actionBodyEntity.equals(p.actionBodyEntity))) && createdBy.equals(p.createdBy) && createdDate.equals(p.createdDate) && description.equals(p.description) && diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyManagement.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyManagement.java index 2a6571e52..c79ee1e82 100644 --- a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyManagement.java +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyManagement.java @@ -62,7 +62,7 @@ public class PolicyManagement implements Serializable { private String configName; @Column(name="XML", nullable=false) - private Clob xml; + private transient Clob xml; @Column(name="CREATE_DATE_TIME", nullable=false) private Timestamp createDateTime; diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/util/Webapps.java b/ONAP-REST/src/main/java/org/onap/policy/rest/util/Webapps.java index 908078f73..1fb8ec531 100644 --- a/ONAP-REST/src/main/java/org/onap/policy/rest/util/Webapps.java +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/util/Webapps.java @@ -30,6 +30,8 @@ import org.apache.commons.logging.LogFactory; import org.onap.policy.rest.XACMLRestProperties; import org.onap.policy.xacml.api.XACMLErrorConstants; + +import com.att.research.xacml.api.pap.PAPException; import com.att.research.xacml.util.XACMLProperties; import org.onap.policy.common.logging.eelf.MessageCodes; @@ -46,8 +48,8 @@ public class Webapps { public static String getConfigHome(){ try { loadWebapps(); - } catch (Exception e) { - logger.error("Exception Occured while loading webapps"+e); + } catch (PAPException e) { + logger.error("Exception Occured while loading webapps",e); return null; } return configHome; @@ -56,14 +58,14 @@ public class Webapps { public static String getActionHome(){ try { loadWebapps(); - } catch (Exception e) { - logger.error("Exception Occured while loading webapps"+e); + } catch (PAPException e) { + logger.error("Exception Occured while loading webapps",e); return null; } return actionHome; } - private static void loadWebapps() throws Exception{ + private static void loadWebapps() throws PAPException{ String errorMessageName = "Invalid Webapps Path Location property :"; if(actionHome == null || configHome == null){ Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS)); @@ -71,7 +73,7 @@ public class Webapps { if (webappsPath == null) { logger.error(errorMessageName + XACMLRestProperties.PROP_PAP_WEBAPPS); PolicyLogger.error(errorMessageName + XACMLRestProperties.PROP_PAP_WEBAPPS); - throw new Exception(errorMessageName + XACMLRestProperties.PROP_PAP_WEBAPPS); + throw new PAPException(errorMessageName + XACMLRestProperties.PROP_PAP_WEBAPPS); } Path webappsPathConfig; Path webappsPathAction; diff --git a/ONAP-SDK-APP/src/main/java/org/openecomp/portalapp/conf/ExternalAppConfig.java b/ONAP-SDK-APP/src/main/java/org/openecomp/portalapp/conf/ExternalAppConfig.java index 91ed598cf..1b6397c05 100644 --- a/ONAP-SDK-APP/src/main/java/org/openecomp/portalapp/conf/ExternalAppConfig.java +++ b/ONAP-SDK-APP/src/main/java/org/openecomp/portalapp/conf/ExternalAppConfig.java @@ -28,6 +28,7 @@ import org.openecomp.portalsdk.core.auth.LoginStrategy; import org.openecomp.portalsdk.core.conf.AppConfig; import org.openecomp.portalsdk.core.conf.Configurable; import org.openecomp.portalsdk.core.objectcache.AbstractCacheManager; +import org.openecomp.portalsdk.core.onboarding.exception.PortalAPIException; import org.openecomp.portalsdk.core.service.DataAccessService; import org.openecomp.portalsdk.core.util.CacheManager; import org.openecomp.portalsdk.core.util.SystemProperties; @@ -135,11 +136,15 @@ public class ExternalAppConfig extends AppConfig implements Configurable { */ // @Bean // ANNOTATION COMMENTED OUT // APPLICATIONS REQUIRING QUARTZ SHOULD RESTORE ANNOTATION - public SchedulerFactoryBean schedulerFactoryBean() throws Exception { + public SchedulerFactoryBean schedulerFactoryBean() throws PortalAPIException { SchedulerFactoryBean scheduler = new SchedulerFactoryBean(); scheduler.setTriggers(schedulerRegistryAdapter.getTriggers()); scheduler.setConfigLocation(appApplicationContext.getResource("WEB-INF/conf/quartz.properties")); - scheduler.setDataSource(dataSource()); + try{ + scheduler.setDataSource(dataSource()); + }catch(Exception e){ + throw new PortalAPIException(e); + } return scheduler; } diff --git a/ONAP-SDK-APP/src/main/java/org/openecomp/portalapp/login/LoginStrategyImpl.java b/ONAP-SDK-APP/src/main/java/org/openecomp/portalapp/login/LoginStrategyImpl.java index a4b684719..13d8836ea 100644 --- a/ONAP-SDK-APP/src/main/java/org/openecomp/portalapp/login/LoginStrategyImpl.java +++ b/ONAP-SDK-APP/src/main/java/org/openecomp/portalapp/login/LoginStrategyImpl.java @@ -14,60 +14,63 @@ import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties; import org.springframework.web.servlet.ModelAndView; public class LoginStrategyImpl extends LoginStrategy { - - private static final Logger LOGGER = FlexLogger.getLogger(LoginStrategyImpl.class); - - @Override - public ModelAndView doLogin(HttpServletRequest request, HttpServletResponse response) throws Exception { - //'login' for opensource is same as 'external' login. - return doExternalLogin(request, response); - } - - @Override - public String getUserId(HttpServletRequest request) throws PortalAPIException { - // Check ONAP Portal cookie - if (!isLoginCookieExist(request)) - return null; - String userid = null; - try { - userid = getUserIdFromCookie(request); - } catch (Exception e) { - LOGGER.error("Exception Occured"+e); - } - return userid; - } + private static final Logger LOGGER = FlexLogger.getLogger(LoginStrategyImpl.class); - private static String getUserIdFromCookie(HttpServletRequest request) throws Exception { - String userId = ""; - Cookie[] cookies = request.getCookies(); - Cookie userIdcookie = null; - if (cookies != null) - for (Cookie cookie : cookies) - if (cookie.getName().equals(USER_ID)) - userIdcookie = cookie; - if(userIdcookie!=null){ - userId = CipherUtil.decrypt(userIdcookie.getValue(), - PortalApiProperties.getProperty(PortalApiConstants.Decryption_Key)); - } - return userId; - - } - - private static boolean isLoginCookieExist(HttpServletRequest request) { - Cookie ep = getCookie(request, EP_SERVICE); - return (ep != null); - } - - private static Cookie getCookie(HttpServletRequest request, String cookieName) { - Cookie[] cookies = request.getCookies(); - if (cookies != null) - for (Cookie cookie : cookies) - if (cookie.getName().equals(cookieName)) - return cookie; + @Override + public ModelAndView doLogin(HttpServletRequest request, HttpServletResponse response) throws Exception { + // 'login' for opensource is same as 'external' login. + return doExternalLogin(request, response); + } - return null; - } + @Override + public String getUserId(HttpServletRequest request) throws PortalAPIException { + // Check ONAP Portal cookie + if (!isLoginCookieExist(request)) + return null; + + String userid = null; + try { + userid = getUserIdFromCookie(request); + } catch (Exception e) { + LOGGER.error("Exception Occured" + e); + } + return userid; + } + + private static String getUserIdFromCookie(HttpServletRequest request) throws PortalAPIException { + String userId = ""; + Cookie[] cookies = request.getCookies(); + Cookie userIdcookie = null; + if (cookies != null) + for (Cookie cookie : cookies) + if (cookie.getName().equals(USER_ID)) + userIdcookie = cookie; + if (userIdcookie != null) { + try { + userId = CipherUtil.decrypt(userIdcookie.getValue(), + PortalApiProperties.getProperty(PortalApiConstants.Decryption_Key)); + } catch (Exception e) { + throw new PortalAPIException(e); + } + } + return userId; + + } + + private static boolean isLoginCookieExist(HttpServletRequest request) { + Cookie ep = getCookie(request, EP_SERVICE); + return (ep != null); + } + + private static Cookie getCookie(HttpServletRequest request, String cookieName) { + Cookie[] cookies = request.getCookies(); + if (cookies != null) + for (Cookie cookie : cookies) + if (cookie.getName().equals(cookieName)) + return cookie; + + return null; + } - } diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdEngine.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdEngine.java index 3132b8cac..14d7c7f62 100644 --- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdEngine.java +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdEngine.java @@ -69,10 +69,10 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE private static Log logger = LogFactory.getLog(StdEngine.class); - public static String PROP_PAP_REPO = "xacml.pap.pdps"; - public static String PROP_PAP_GROUPS = "xacml.pap.groups"; - public static String PROP_PAP_GROUPS_DEFAULT = "xacml.pap.groups.default"; - public static String PROP_PAP_GROUPS_DEFAULT_NAME = "default"; + public static final String PROP_PAP_REPO = "xacml.pap.pdps"; + public static final String PROP_PAP_GROUPS = "xacml.pap.groups"; + public static final String PROP_PAP_GROUPS_DEFAULT = "xacml.pap.groups.default"; + public static final String PROP_PAP_GROUPS_DEFAULT_NAME = "default"; //this value will be accessed from XacmlPapServlet so that we know if a default group did not exist //and was just added. This way, we can add the new group to the database. public boolean wasDefaultGroupJustAdded = false; @@ -892,7 +892,7 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE try { ((StdPDPGroup)group).saveGroupConfiguration(); } catch (IOException e) { - throw new PAPException("Unable to save new configuration for '" + group.getName() + "': " + e.getMessage()); + throw new PAPException("Unable to save new configuration for '" + group.getName() + "': " + e.getMessage(), e); } // update the group in the set by simply replacing the old instance with the new one this.groups.remove(existingGroup); @@ -923,13 +923,13 @@ public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyE } } catch (Exception e) { PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "StdEngine", "Unable to rename directory"); - throw new PAPException("Unable to move directory from '" + oldPath + "' to '" + newPath + "': " + e.getMessage()); + throw new PAPException("Unable to move directory from '" + oldPath + "' to '" + newPath + "': " + e.getMessage(),e); } // update the disk try { ((StdPDPGroup)group).saveGroupConfiguration(); } catch (IOException e) { - throw new PAPException("Unable to save new configuration for '" + group.getName() + "': " + e.getMessage()); + throw new PAPException("Unable to save new configuration for '" + group.getName() + "': " + e.getMessage(), e); } // save the new group into the Set diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPAPPolicy.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPAPPolicy.java index d69f38d95..56676f38b 100644 --- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPAPPolicy.java +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPAPPolicy.java @@ -42,7 +42,7 @@ public class StdPAPPolicy implements OnapPAPPolicy, Serializable{ private List<String> dynamicRuleAlgorithmCombo; private List<String> dynamicRuleAlgorithmField1; private List<String> dynamicRuleAlgorithmField2; - private List<Object> dynamicVariableList; + private transient List<Object> dynamicVariableList; private List<String> dataTypeList; private String configBodyData = null; private String policyID = null; diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDP.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDP.java index 20dbfae07..4c1f4aadc 100644 --- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDP.java +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDP.java @@ -45,11 +45,11 @@ public class StdPDP extends StdPDPItemSetChangeNotifier implements OnapPDP, Comp private Integer jmxport = 0; - private PDPStatus status = new StdPDPStatus(); + private transient PDPStatus status = new StdPDPStatus(); - private Set<PDPPolicy> policies = new HashSet<>(); + private transient Set<PDPPolicy> policies = new HashSet<>(); - private Set<PDPPIPConfig> pipConfigs = new HashSet<>(); + private transient Set<PDPPIPConfig> pipConfigs = new HashSet<>(); public StdPDP() { @@ -89,7 +89,6 @@ public class StdPDP extends StdPDPItemSetChangeNotifier implements OnapPDP, Comp } else if (key.toString().endsWith(".description")) { this.description = properties.getProperty(key.toString()); }else if (key.toString().endsWith(".jmxport")) { - //todo fix this hackjob if (properties.getProperty(key.toString()) != null && properties.getProperty(key.toString()).trim().length() > 0){ logger.debug("initialize before: " + this.jmxport); this.jmxport = Integer.valueOf( properties.getProperty(key.toString())); diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPGroup.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPGroup.java index 63cc4b4fc..28f6a4d03 100644 --- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPGroup.java +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPGroup.java @@ -70,20 +70,20 @@ public class StdPDPGroup extends StdPDPItemSetChangeNotifier implements OnapPDPG private String description; - private StdPDPGroupStatus status = new StdPDPGroupStatus(Status.UNKNOWN); + private transient StdPDPGroupStatus status = new StdPDPGroupStatus(Status.UNKNOWN); - private Set<OnapPDP> pdps = new HashSet<>(); + private transient Set<OnapPDP> pdps = new HashSet<>(); - private Set<PDPPolicy> policies = new HashSet<>(); + private transient Set<PDPPolicy> policies = new HashSet<>(); - private Set<PDPPolicy> selectedPolicies = new HashSet<>(); + private transient Set<PDPPolicy> selectedPolicies = new HashSet<>(); - private Set<PDPPIPConfig> pipConfigs = new HashSet<>(); + private transient Set<PDPPIPConfig> pipConfigs = new HashSet<>(); private String operation; @JsonIgnore - private Path directory; + private transient Path directory; @JsonIgnore private Integer jmxport; @@ -187,7 +187,7 @@ public class StdPDPGroup extends StdPDPItemSetChangeNotifier implements OnapPDPG try (OutputStream os = Files.newOutputStream(file)) { policyProperties.store(os, ""); } catch (Exception e) { - throw new PAPException("Failed to create new default policy properties file '" + file +"'"); + throw new PAPException("Failed to create new default policy properties file '" + file +"'", e); } } else { // load previously existing file @@ -225,13 +225,13 @@ public class StdPDPGroup extends StdPDPItemSetChangeNotifier implements OnapPDPG pipProperties.store(os, ""); } } catch (Exception e) { - throw new PAPException("Failed to create new default pip properties file '" + file +"'"); + throw new PAPException("Failed to create new default pip properties file '" + file +"'", e); } //Even if we create a new pip file, we still need to parse and load the properties try{ this.readPIPProperties(directory, pipProperties); }catch(Exception e){ - throw new PAPException("Failed to load the new pip properties file"); + throw new PAPException("Failed to load the new pip properties file", e); } } else { try { diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPItemSetChangeNotifier.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPItemSetChangeNotifier.java index d23501f26..cc80b62c2 100644 --- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPItemSetChangeNotifier.java +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPItemSetChangeNotifier.java @@ -41,7 +41,7 @@ public class StdPDPItemSetChangeNotifier { public void addItemSetChangeListener(StdItemSetChangeListener listener) { if (this.listeners == null) { - this.listeners = new LinkedList<StdItemSetChangeListener>(); + this.listeners = new LinkedList<>(); } this.listeners.add(listener); } diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPStatus.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPStatus.java index f8759956c..5349f8340 100644 --- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPStatus.java +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPStatus.java @@ -38,15 +38,15 @@ public class StdPDPStatus implements Serializable, PDPStatus { private Set<String> loadWarnings = new HashSet<>(); - private Set<PDPPolicy> loadedPolicies = new HashSet<>(); + private transient Set<PDPPolicy> loadedPolicies = new HashSet<>(); - private Set<PDPPolicy> loadedRootPolicies = new HashSet<>(); + private transient Set<PDPPolicy> loadedRootPolicies = new HashSet<>(); - private Set<PDPPolicy> failedPolicies = new HashSet<>(); + private transient Set<PDPPolicy> failedPolicies = new HashSet<>(); - private Set<PDPPIPConfig> loadedPIPConfigs = new HashSet<>(); + private transient Set<PDPPIPConfig> loadedPIPConfigs = new HashSet<>(); - private Set<PDPPIPConfig> failedPIPConfigs = new HashSet<>(); + private transient Set<PDPPIPConfig> failedPIPConfigs = new HashSet<>(); public StdPDPStatus() { } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java index e99f35bde..7234a3b6a 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java @@ -361,7 +361,7 @@ public class PolicyRestController extends RestrictedBaseController{ } @RequestMapping(value={"/saveDictionary/*/*"}, method={RequestMethod.POST}) - public ModelAndView saveDictionaryController(HttpServletRequest request, HttpServletResponse response) throws Exception{ + public ModelAndView saveDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException{ String uri = request.getRequestURI().replace("/saveDictionary", ""); if(uri.contains(importDictionary)){ String userId = UserUtils.getUserSession(request).getOrgUserId(); @@ -373,7 +373,7 @@ public class PolicyRestController extends RestrictedBaseController{ } @RequestMapping(value={"/deleteDictionary/*/*"}, method={RequestMethod.POST}) - public ModelAndView deletetDictionaryController(HttpServletRequest request, HttpServletResponse response) throws Exception{ + public ModelAndView deletetDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException { String uri = request.getRequestURI().replace("/deleteDictionary", ""); String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim()); response.getWriter().write(body); @@ -381,7 +381,7 @@ public class PolicyRestController extends RestrictedBaseController{ } @RequestMapping(value={"/searchDictionary"}, method={RequestMethod.POST}) - public ModelAndView searchDictionaryController(HttpServletRequest request, HttpServletResponse response) throws Exception{ + public ModelAndView searchDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException { Object resultList = null; String uri = request.getRequestURI(); try{ @@ -410,7 +410,7 @@ public class PolicyRestController extends RestrictedBaseController{ } @RequestMapping(value={"/searchPolicy"}, method={RequestMethod.POST}) - public ModelAndView searchPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + public ModelAndView searchPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException{ Object resultList = null; String uri = request.getRequestURI()+"?action=search"; String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim()); diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java index 0a985045d..c8b7a9630 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java @@ -20,7 +20,6 @@ package org.onap.policy.controller; - import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; @@ -36,7 +35,6 @@ import org.openecomp.portalsdk.core.controller.RestrictedBaseController; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; - import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType; @@ -50,219 +48,227 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; -import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; @Controller -@RequestMapping({"/"}) -public class ActionPolicyController extends RestrictedBaseController{ - private static final Logger LOGGER = FlexLogger.getLogger(ActionPolicyController.class); - - public ActionPolicyController(){ - //Default Constructor - } +@RequestMapping({ "/" }) +public class ActionPolicyController extends RestrictedBaseController { + private static final Logger LOGGER = FlexLogger.getLogger(ActionPolicyController.class); + + public ActionPolicyController() { + // Default Constructor + } - private ArrayList<Object> attributeList; - protected LinkedList<Integer> ruleAlgoirthmTracker; - public static final String PERFORMER_ATTRIBUTEID = "performer"; - protected Map<String, String> performer = new HashMap<>(); - private ArrayList<Object> ruleAlgorithmList; + private ArrayList<Object> attributeList; + protected LinkedList<Integer> ruleAlgoirthmTracker; + public static final String PERFORMER_ATTRIBUTEID = "performer"; + protected Map<String, String> performer = new HashMap<>(); + private ArrayList<Object> ruleAlgorithmList; - public void prePopulateActionPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - attributeList = new ArrayList<>(); - ruleAlgorithmList = new ArrayList<>(); - performer.put("PDP", "PDPAction"); - performer.put("PEP", "PEPAction"); + public void prePopulateActionPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + attributeList = new ArrayList<>(); + ruleAlgorithmList = new ArrayList<>(); + performer.put("PDP", "PDPAction"); + performer.put("PEP", "PEPAction"); - if (policyAdapter.getPolicyData() instanceof PolicyType) { - Object policyData = policyAdapter.getPolicyData(); - PolicyType policy = (PolicyType) policyData; - policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("_") + 1); - policyAdapter.setPolicyName(policyNameValue); - String description = ""; - try{ - description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); - }catch(Exception e){ - description = policy.getDescription(); - } - policyAdapter.setPolicyDescription(description); - // Get the target data under policy for Action. - TargetType target = policy.getTarget(); - if (target != null) { - // under target we have AnyOFType - List<AnyOfType> anyOfList = target.getAnyOf(); - if (anyOfList != null) { - Iterator<AnyOfType> iterAnyOf = anyOfList.iterator(); - while (iterAnyOf.hasNext()) { - AnyOfType anyOf = iterAnyOf.next(); - // Under AntOfType we have AllOfType - List<AllOfType> allOfList = anyOf.getAllOf(); - if (allOfList != null) { - Iterator<AllOfType> iterAllOf = allOfList.iterator(); - while (iterAllOf.hasNext()) { - AllOfType allOf = iterAllOf.next(); - // Under AllOfType we have Mathch. - List<MatchType> matchList = allOf.getMatch(); - if (matchList != null) { - Iterator<MatchType> iterMatch = matchList.iterator(); - while (iterMatch.hasNext()) { - MatchType match = iterMatch.next(); - // - // Under the match we have attributevalue and - // attributeDesignator. So,finally down to the actual attribute. - // - AttributeValueType attributeValue = match.getAttributeValue(); - String value = (String) attributeValue.getContent().get(0); - AttributeDesignatorType designator = match.getAttributeDesignator(); - String attributeId = designator.getAttributeId(); - // Component attributes are saved under Target here we are fetching them back. - // One row is default so we are not adding dynamic component at index 0. - Map<String, String> attribute = new HashMap<>(); - attribute.put("key", attributeId); - attribute.put("value", value); - attributeList.add(attribute); - } - } - policyAdapter.setAttributes(attributeList); - } - } - } - } + if (policyAdapter.getPolicyData() instanceof PolicyType) { + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + String policyNameValue = policyAdapter.getPolicyName() + .substring(policyAdapter.getPolicyName().indexOf("_") + 1); + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try { + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + } catch (Exception e) { + LOGGER.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue, e); + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + // Get the target data under policy for Action. + TargetType target = policy.getTarget(); + if (target != null) { + // under target we have AnyOFType + List<AnyOfType> anyOfList = target.getAnyOf(); + if (anyOfList != null) { + Iterator<AnyOfType> iterAnyOf = anyOfList.iterator(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + // Under AntOfType we have AllOfType + List<AllOfType> allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator<AllOfType> iterAllOf = allOfList.iterator(); + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + // Under AllOfType we have Mathch. + List<MatchType> matchList = allOf.getMatch(); + if (matchList != null) { + Iterator<MatchType> iterMatch = matchList.iterator(); + while (iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attributevalue and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + // Component attributes are saved under Target here we are fetching them back. + // One row is default so we are not adding dynamic component at index 0. + Map<String, String> attribute = new HashMap<>(); + attribute.put("key", attributeId); + attribute.put("value", value); + attributeList.add(attribute); + } + } + policyAdapter.setAttributes(attributeList); + } + } + } + } - List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); - // Under rule we have Condition and obligation. - for (Object o : ruleList) { - if (o instanceof RuleType) { - ConditionType condition = ((RuleType) o).getCondition(); - ObligationExpressionsType obligations = ((RuleType) o).getObligationExpressions(); - if (condition != null) { - int index = 0; - ApplyType actionApply = (ApplyType) condition.getExpression().getValue(); - ruleAlgoirthmTracker = new LinkedList<>(); - // Populating Rule Algorithms starting from compound. - prePopulateCompoundRuleAlgorithm(index, actionApply); - } - policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList); - // get the Obligation data under the rule for Form elements. - if (obligations != null) { - // Under the obligationExpressions we have obligationExpression. - List<ObligationExpressionType> obligationList = obligations.getObligationExpression(); - if (obligationList != null) { - Iterator<ObligationExpressionType> iterObligation = obligationList.iterator(); - while (iterObligation.hasNext()) { - ObligationExpressionType obligation = iterObligation.next(); - policyAdapter.setActionAttributeValue(obligation.getObligationId()); - // Under the obligationExpression we have attributeAssignmentExpression. - List<AttributeAssignmentExpressionType> attributeAssignmentExpressionList = obligation.getAttributeAssignmentExpression(); - if (attributeAssignmentExpressionList != null) { - Iterator<AttributeAssignmentExpressionType> iterAttributeAssignmentExpression = attributeAssignmentExpressionList.iterator(); - while (iterAttributeAssignmentExpression.hasNext()) { - AttributeAssignmentExpressionType attributeAssignmentExpression = iterAttributeAssignmentExpression.next(); - String attributeID = attributeAssignmentExpression.getAttributeId(); - AttributeValueType attributeValue = (AttributeValueType) attributeAssignmentExpression.getExpression().getValue(); - if (attributeID.equals(PERFORMER_ATTRIBUTEID)) { - for (String key : performer.keySet()) { - String keyValue = performer.get(key); - if (keyValue.equals(attributeValue.getContent().get(0))) { - policyAdapter.setActionPerformer(key); - } - } - } - } - } - } - } - } - } - } - } - } - } + List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); + // Under rule we have Condition and obligation. + for (Object o : ruleList) { + if (o instanceof RuleType) { + ConditionType condition = ((RuleType) o).getCondition(); + ObligationExpressionsType obligations = ((RuleType) o).getObligationExpressions(); + if (condition != null) { + int index = 0; + ApplyType actionApply = (ApplyType) condition.getExpression().getValue(); + ruleAlgoirthmTracker = new LinkedList<>(); + // Populating Rule Algorithms starting from compound. + prePopulateCompoundRuleAlgorithm(index, actionApply); + } + policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList); + // get the Obligation data under the rule for Form elements. + if (obligations != null) { + // Under the obligationExpressions we have obligationExpression. + List<ObligationExpressionType> obligationList = obligations.getObligationExpression(); + if (obligationList != null) { + Iterator<ObligationExpressionType> iterObligation = obligationList.iterator(); + while (iterObligation.hasNext()) { + ObligationExpressionType obligation = iterObligation.next(); + policyAdapter.setActionAttributeValue(obligation.getObligationId()); + // Under the obligationExpression we have attributeAssignmentExpression. + List<AttributeAssignmentExpressionType> attributeAssignmentExpressionList = obligation + .getAttributeAssignmentExpression(); + if (attributeAssignmentExpressionList != null) { + Iterator<AttributeAssignmentExpressionType> iterAttributeAssignmentExpression = attributeAssignmentExpressionList + .iterator(); + while (iterAttributeAssignmentExpression.hasNext()) { + AttributeAssignmentExpressionType attributeAssignmentExpression = iterAttributeAssignmentExpression + .next(); + String attributeID = attributeAssignmentExpression.getAttributeId(); + AttributeValueType attributeValue = (AttributeValueType) attributeAssignmentExpression + .getExpression().getValue(); + if (attributeID.equals(PERFORMER_ATTRIBUTEID)) { + for (String key : performer.keySet()) { + String keyValue = performer.get(key); + if (keyValue.equals(attributeValue.getContent().get(0))) { + policyAdapter.setActionPerformer(key); + } + } + } + } + } + } + } + } + } + } + } + } + } - private int prePopulateCompoundRuleAlgorithm(int index, ApplyType actionApply) { - boolean isCompoundRule = true; - List<JAXBElement<?>> jaxbActionTypes = actionApply.getExpression(); - for (JAXBElement<?> jaxbElement : jaxbActionTypes) { - // If There is Attribute Value under Action Type that means we came to the final child - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Prepopulating rule algoirthm: " + index); - } - // Check to see if Attribute Value exists, if yes then it is not a compound rule - if (jaxbElement.getValue() instanceof AttributeValueType) { - prePopulateRuleAlgorithms(index, actionApply, jaxbActionTypes); - ruleAlgoirthmTracker.addLast(index); - isCompoundRule = false; - index++; - } - } - if (isCompoundRule) { - // As it's compound rule, Get the Apply types - for (JAXBElement<?> jaxbElement : jaxbActionTypes) { - ApplyType innerActionApply = (ApplyType) jaxbElement.getValue(); - index = prePopulateCompoundRuleAlgorithm(index, innerActionApply); - } - // Populate combo box - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Prepopulating Compound rule algorithm: " + index); - } - Map<String, String> rule = new HashMap<String, String>(); - for (String key : PolicyController.getDropDownMap().keySet()) { - String keyValue = PolicyController.getDropDownMap().get(key); - if (keyValue.equals(actionApply.getFunctionId())) { - rule.put("dynamicRuleAlgorithmCombo", key); - } - } - rule.put("id", "A" + (index +1)); - // Populate Key and values for Compound Rule - rule.put("dynamicRuleAlgorithmField1", "A" + (ruleAlgoirthmTracker.getLast() + 1 )); - ruleAlgoirthmTracker.removeLast(); - rule.put("dynamicRuleAlgorithmField2", "A" + (ruleAlgoirthmTracker.getLast() + 1)); - ruleAlgoirthmTracker.removeLast(); - ruleAlgoirthmTracker.addLast(index); - ruleAlgorithmList.add(rule); - index++; - } - return index; - } + private int prePopulateCompoundRuleAlgorithm(int index, ApplyType actionApply) { + boolean isCompoundRule = true; + List<JAXBElement<?>> jaxbActionTypes = actionApply.getExpression(); + for (JAXBElement<?> jaxbElement : jaxbActionTypes) { + // If There is Attribute Value under Action Type that means we came to the final child + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Prepopulating rule algoirthm: " + index); + } + // Check to see if Attribute Value exists, if yes then it is not a compound rule + if (jaxbElement.getValue() instanceof AttributeValueType) { + prePopulateRuleAlgorithms(index, actionApply, jaxbActionTypes); + ruleAlgoirthmTracker.addLast(index); + isCompoundRule = false; + index++; + } + } + if (isCompoundRule) { + // As it's compound rule, Get the Apply types + for (JAXBElement<?> jaxbElement : jaxbActionTypes) { + ApplyType innerActionApply = (ApplyType) jaxbElement.getValue(); + index = prePopulateCompoundRuleAlgorithm(index, innerActionApply); + } + // Populate combo box + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Prepopulating Compound rule algorithm: " + index); + } + Map<String, String> rule = new HashMap<String, String>(); + for (String key : PolicyController.getDropDownMap().keySet()) { + String keyValue = PolicyController.getDropDownMap().get(key); + if (keyValue.equals(actionApply.getFunctionId())) { + rule.put("dynamicRuleAlgorithmCombo", key); + } + } + rule.put("id", "A" + (index + 1)); + // Populate Key and values for Compound Rule + rule.put("dynamicRuleAlgorithmField1", "A" + (ruleAlgoirthmTracker.getLast() + 1)); + ruleAlgoirthmTracker.removeLast(); + rule.put("dynamicRuleAlgorithmField2", "A" + (ruleAlgoirthmTracker.getLast() + 1)); + ruleAlgoirthmTracker.removeLast(); + ruleAlgoirthmTracker.addLast(index); + ruleAlgorithmList.add(rule); + index++; + } + return index; + } - private void prePopulateRuleAlgorithms(int index, ApplyType actionApply, List<JAXBElement<?>> jaxbActionTypes) { - Map<String, String> ruleMap = new HashMap<String, String>(); - ruleMap.put("id", "A" + (index +1)); - // Populate combo box - Map<String, String> dropDownMap = PolicyController.getDropDownMap(); - for (String key : dropDownMap.keySet()) { - String keyValue = dropDownMap.get(key); - if (keyValue.equals(actionApply.getFunctionId())) { - ruleMap.put("dynamicRuleAlgorithmCombo", key); - } - } - // Populate the key and value fields - // Rule Attribute added as key - if ((jaxbActionTypes.get(0).getValue()) instanceof ApplyType) { - // Get from Attribute Designator - ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(0).getValue(); - List<JAXBElement<?>> jaxbInnerActionTypes = innerActionApply.getExpression(); - AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerActionTypes.get(0).getValue(); - ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId()); + private void prePopulateRuleAlgorithms(int index, ApplyType actionApply, List<JAXBElement<?>> jaxbActionTypes) { + Map<String, String> ruleMap = new HashMap<String, String>(); + ruleMap.put("id", "A" + (index + 1)); + // Populate combo box + Map<String, String> dropDownMap = PolicyController.getDropDownMap(); + for (String key : dropDownMap.keySet()) { + String keyValue = dropDownMap.get(key); + if (keyValue.equals(actionApply.getFunctionId())) { + ruleMap.put("dynamicRuleAlgorithmCombo", key); + } + } + // Populate the key and value fields + // Rule Attribute added as key + if ((jaxbActionTypes.get(0).getValue()) instanceof ApplyType) { + // Get from Attribute Designator + ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(0).getValue(); + List<JAXBElement<?>> jaxbInnerActionTypes = innerActionApply.getExpression(); + AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerActionTypes.get(0) + .getValue(); + ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId()); - // Get from Attribute Value - AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbActionTypes.get(1).getValue(); - String attributeValue = (String) actionConditionAttributeValue.getContent().get(0); - ruleMap.put("dynamicRuleAlgorithmField2", attributeValue); - } - // Rule Attribute added as value - else if (((jaxbActionTypes.get(0).getValue()) instanceof AttributeValueType)) { - AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbActionTypes.get(0).getValue(); - String attributeValue = (String) actionConditionAttributeValue.getContent().get(0); - ruleMap.put("dynamicRuleAlgorithmField2", attributeValue); + // Get from Attribute Value + AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbActionTypes.get(1).getValue(); + String attributeValue = (String) actionConditionAttributeValue.getContent().get(0); + ruleMap.put("dynamicRuleAlgorithmField2", attributeValue); + } + // Rule Attribute added as value + else if (((jaxbActionTypes.get(0).getValue()) instanceof AttributeValueType)) { + AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbActionTypes.get(0).getValue(); + String attributeValue = (String) actionConditionAttributeValue.getContent().get(0); + ruleMap.put("dynamicRuleAlgorithmField2", attributeValue); - ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(1).getValue(); - List<JAXBElement<?>> jaxbInnerActionTypes = innerActionApply.getExpression(); - AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerActionTypes.get(0).getValue(); - ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId()); - } - ruleAlgorithmList.add(ruleMap); - } + ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(1).getValue(); + List<JAXBElement<?>> jaxbInnerActionTypes = innerActionApply.getExpression(); + AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerActionTypes.get(0) + .getValue(); + ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId()); + } + ruleAlgorithmList.add(ruleMap); + } } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java index 820a1ebd9..3b88f8472 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java @@ -21,6 +21,7 @@ package org.onap.policy.controller; +import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; @@ -86,7 +87,7 @@ public class AdminTabController extends RestrictedBaseController{ } @RequestMapping(value={"/adminTabController/save_LockDownValue.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveAdminTabLockdownValue(HttpServletRequest request, HttpServletResponse response) throws Exception{ + public ModelAndView saveAdminTabLockdownValue(HttpServletRequest request, HttpServletResponse response) throws IOException{ try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java index b72993f19..c1468e365 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java @@ -177,7 +177,7 @@ public class AutoPushController extends RestrictedBaseController{ } @RequestMapping(value={"/auto_Push/PushPolicyToPDP.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView PushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception { + public ModelAndView pushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException { try { ArrayList<Object> selectedPDPS = new ArrayList<>(); ArrayList<String> selectedPoliciesInUI = new ArrayList<>(); @@ -256,7 +256,7 @@ public class AutoPushController extends RestrictedBaseController{ // Create the policy selectedPolicy = new StdPDPPolicy(name, true, id, selectedURI); } catch (IOException e) { - logger.error("Unable to create policy '" + name + "': "+ e.getMessage()); + logger.error("Unable to create policy '" + name + "': "+ e.getMessage(), e); } StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId; if (selectedPolicy != null) { @@ -319,7 +319,7 @@ public class AutoPushController extends RestrictedBaseController{ refreshGroups(); JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); JSONObject j = new JSONObject(msg); - out.write(j.toString()); + out.write(j.toString()); return null; } } @@ -327,6 +327,7 @@ public class AutoPushController extends RestrictedBaseController{ response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); + logger.error(e); out.write(e.getMessage()); } return null; @@ -334,7 +335,7 @@ public class AutoPushController extends RestrictedBaseController{ @SuppressWarnings("unchecked") @RequestMapping(value={"/auto_Push/remove_GroupPolicies.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception { + public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException { try { PolicyController controller = getPolicyControllerInstance(); this.container = new PDPGroupContainer(controller.getPapEngine()); @@ -376,6 +377,7 @@ public class AutoPushController extends RestrictedBaseController{ response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); + logger.error(e); out.write(e.getMessage()); } return null; diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java index a7ce45ec4..e7740c336 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java @@ -279,6 +279,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController{ } } } catch(Exception e){ + policyLogger.warn("Error during callTrap" , e); return "(" + trap + ")"; } }else{ @@ -316,7 +317,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController{ attrib = getVarbindOID(attrib); attributes = attributes + "("+ URLEncoder.encode(attrib, "UTF-8")+ ")"; } catch (UnsupportedEncodingException e1) { - //logger.error("Caused Exception while Encoding Varbind Dictionary Values"+e1); + policyLogger.error("Caused Exception while Encoding Varbind Dictionary Values",e1); } } }else{ @@ -324,7 +325,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController{ attrib = getVarbindOID(attrib); attributes = attributes + "("+ URLEncoder.encode(attrib, "UTF-8")+ ")"; } catch (UnsupportedEncodingException e) { - //logger.error("Caused Exception while Encoding Varbind Dictionary Values"+e); + policyLogger.error("Caused Exception while Encoding Varbind Dictionary Values",e); } } }else{ @@ -348,7 +349,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController{ attrib = getVarbindOID(attrib); attributes = attributes + "("+ URLEncoder.encode(attrib, "UTF-8") + ")"; } catch (UnsupportedEncodingException e1) { - //logger.error("Caused Exception while Encoding Varbind Dictionary Values"+e1); + policyLogger.error("Caused Exception while Encoding Varbind Dictionary Values",e1); } } }else{ @@ -356,7 +357,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController{ attrib = getVarbindOID(attrib); attributes = attributes + "("+ URLEncoder.encode(attrib, "UTF-8") + ")"; } catch (UnsupportedEncodingException e) { - //logger.error("Caused Exception while Encoding Varbind Dictionary Values"+e); + policyLogger.error("Caused Exception while Encoding Varbind Dictionary Values",e); } } } @@ -369,6 +370,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController{ varbindId = (VarbindDictionary) commonclassdao.getEntityItem(VarbindDictionary.class, "varbindName", attrib); return varbindId.getVarbindOID(); }catch(Exception e){ + policyLogger.error("Error during retrieving varbindName " + attrib, e); return attrib; } } @@ -511,6 +513,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController{ try{ description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); }catch(Exception e){ + policyLogger.error("Error during collecting the description tag info for createClosedLoopFault " + policyNameValue , e); description = policy.getDescription(); } policyAdapter.setPolicyDescription(description); diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java index 609a45c20..815b88f70 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java @@ -55,6 +55,7 @@ import javax.servlet.http.HttpServletResponse; import org.apache.commons.compress.utils.IOUtils; import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FileUtils; @@ -850,7 +851,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } @RequestMapping(value={"/policyController/getDCAEMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView getDCAEMSTemplateData(HttpServletRequest request, HttpServletResponse response) throws Exception{ + public ModelAndView getDCAEMSTemplateData(HttpServletRequest request, HttpServletResponse response) throws IOException{ ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); @@ -980,7 +981,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { @RequestMapping(value={"/policyController/getModelServiceVersioneData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response) throws Exception{ + public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response) throws IOException{ ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); @@ -1068,6 +1069,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { try{ description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); }catch(Exception e){ + LOGGER.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue ,e); description = policy.getDescription(); } policyAdapter.setPolicyDescription(description); @@ -1270,7 +1272,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } @RequestMapping(value={"/ms_dictionary/set_MSModelData"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public void SetMSModelData(HttpServletRequest request, HttpServletResponse response) throws Exception{ + public void SetMSModelData(HttpServletRequest request, HttpServletResponse response) throws IOException, FileUploadException{ List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); boolean zip = false; boolean yml= false; @@ -1425,7 +1427,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } } } catch (IOException e) { - LOGGER.error("Failed to unzip model file " + zipFile); + LOGGER.error("Failed to unzip model file " + zipFile, e); }finally{ try { if(zip != null) @@ -1470,7 +1472,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { try { FileUtils.forceDelete(new File(path)); } catch (IOException e) { - LOGGER.error("Failed to delete folder " + path); + LOGGER.error("Failed to delete folder " + path, e); } } } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java index 9c07876c1..4506fb84c 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java @@ -27,6 +27,8 @@ import java.util.Iterator; import java.util.List; import java.util.Map; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.rest.adapter.PolicyRestAdapter; import org.onap.policy.rest.jpa.PolicyEntity; import org.openecomp.portalsdk.core.controller.RestrictedBaseController; @@ -45,7 +47,7 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; @Controller @RequestMapping("/") public class CreatePolicyController extends RestrictedBaseController{ - + private static Logger policyLogger = FlexLogger.getLogger(CreatePolicyController.class); protected PolicyRestAdapter policyAdapter = null; private ArrayList<Object> attributeList; boolean isValidForm = false; @@ -74,12 +76,13 @@ public class CreatePolicyController extends RestrictedBaseController{ policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); policyAdapter.setConfigType(entity.getConfigurationData().getConfigType()); policyAdapter.setConfigBodyData(entity.getConfigurationData().getConfigBody()); - String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("_") + 1); + String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf(' ') + 1); policyAdapter.setPolicyName(policyNameValue); String description = ""; try{ description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); }catch(Exception e){ + policyLogger.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue ,e); description = policy.getDescription(); } policyAdapter.setPolicyDescription(description); diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java index f40587d4b..bb06cb3fe 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java @@ -34,11 +34,13 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONObject; +import org.onap.policy.admin.RESTfulPAPEngine; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.model.PDPGroupContainer; import org.onap.policy.xacml.api.XACMLErrorConstants; import org.onap.policy.xacml.api.pap.OnapPDPGroup; +import org.onap.policy.xacml.api.pap.PAPPolicyEngine; import org.onap.policy.xacml.std.pap.StdPDP; import org.onap.policy.xacml.std.pap.StdPDPGroup; import org.openecomp.policy.model.Roles; @@ -106,6 +108,9 @@ public class PDPController extends RestrictedBaseController { } } } + if(!junit&& controller.getPapEngine()==null){ + setPAPEngine(request); + } if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST) ) { if(!junit){ this.groups.addAll(controller.getPapEngine().getOnapPDPGroups()); @@ -156,7 +161,19 @@ public class PDPController extends RestrictedBaseController { } } - @RequestMapping(value={"/get_PDPGroupData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + private void setPAPEngine(HttpServletRequest request) { + String myRequestURL = request.getRequestURL().toString(); + try { + // + // Set the URL for the RESTful PAP Engine + // + PolicyController.setPapEngine((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL)); + }catch(Exception e){ + policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception Occured while loading PAP",e); + } + } + + @RequestMapping(value={"/get_PDPGroupData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) public void getPDPGroupEntityData(HttpServletRequest request, HttpServletResponse response){ try{ ObjectMapper mapper = new ObjectMapper(); diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java index 35b9b959d..4a6c230c1 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java @@ -40,6 +40,8 @@ import javax.servlet.http.HttpServletResponse; import org.json.JSONObject; import org.onap.policy.admin.PolicyNotificationMail; import org.onap.policy.admin.RESTfulPAPEngine; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.model.PDPGroupContainer; import org.onap.policy.rest.XACMLRestProperties; import org.onap.policy.rest.XacmlAdminAuthorization; @@ -49,6 +51,8 @@ import org.onap.policy.rest.jpa.FunctionDefinition; import org.onap.policy.rest.jpa.PolicyEntity; import org.onap.policy.rest.jpa.PolicyVersion; import org.onap.policy.rest.jpa.UserInfo; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.api.pap.PAPPolicyEngine; import org.openecomp.policy.model.Roles; import org.openecomp.portalsdk.core.controller.RestrictedBaseController; import org.openecomp.portalsdk.core.web.support.JsonMessage; @@ -60,15 +64,9 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; -import org.onap.policy.xacml.api.XACMLErrorConstants; -import org.onap.policy.xacml.api.pap.PAPPolicyEngine; - import com.att.research.xacml.util.XACMLProperties; import com.fasterxml.jackson.databind.ObjectMapper; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; - @Controller @RequestMapping("/") @@ -321,7 +319,7 @@ public class PolicyController extends RestrictedBaseController { } //Policy tabs Model and View - @RequestMapping(value= {"/policy", "/policy/Editor" } , method = RequestMethod.GET) + @RequestMapping(value= {"/policy", "/policy/Editor" } , method = RequestMethod.GET) public ModelAndView view(HttpServletRequest request){ String myRequestURL = request.getRequestURL().toString(); try { @@ -341,7 +339,7 @@ public class PolicyController extends RestrictedBaseController { return papEngine; } - public void setPapEngine(PAPPolicyEngine papEngine) { + public static void setPapEngine(PAPPolicyEngine papEngine) { PolicyController.papEngine = papEngine; } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java index bb6f38b8e..a6c6bf6ac 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java @@ -24,6 +24,7 @@ package org.onap.policy.controller; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; +import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashSet; @@ -116,7 +117,7 @@ public class PolicyExportAndImportController extends RestrictedBaseController { public PolicyExportAndImportController(){} @RequestMapping(value={"/policy_download/exportPolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public void exportPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + public void exportPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException{ try{ String file = null; selectedPolicy = new ArrayList<>(); @@ -202,7 +203,7 @@ public class PolicyExportAndImportController extends RestrictedBaseController { } //Policy Import - public JSONObject importRepositoryFile(String file, HttpServletRequest request) throws Exception{ + public JSONObject importRepositoryFile(String file, HttpServletRequest request) throws IOException{ boolean configExists = false; boolean actionExists = false; String configName = null; diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java index 731217573..21f3793f1 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java @@ -25,6 +25,7 @@ package org.onap.policy.controller; * * */ import java.io.File; +import java.io.IOException; import java.io.PrintWriter; import java.util.List; @@ -33,6 +34,8 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONObject; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.WatchPolicyNotificationTable; import org.openecomp.portalsdk.core.controller.RestrictedBaseController; @@ -50,12 +53,13 @@ import com.fasterxml.jackson.databind.node.ArrayNode; @Controller @RequestMapping({"/"}) public class PolicyNotificationController extends RestrictedBaseController { + private static Logger logger = FlexLogger.getLogger(PolicyNotificationController.class); @Autowired CommonClassDao commonClassDao; @RequestMapping(value={"/watchPolicy"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView watchPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + public ModelAndView watchPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException{ String path = ""; String responseValue = ""; try { @@ -118,6 +122,7 @@ public class PolicyNotificationController extends RestrictedBaseController { }catch(Exception e){ response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); + logger.error("Error druing watchPolicy function " + e); PrintWriter out = response.getWriter(); out.write(e.getMessage()); } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java index 5fb0c1a7e..d1fba383f 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java @@ -22,6 +22,7 @@ package org.onap.policy.controller; import java.io.ByteArrayInputStream; +import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringReader; @@ -97,7 +98,7 @@ public class PolicyValidationController extends RestrictedBaseController { CommonClassDao commonClassDao; @RequestMapping(value={"/policyController/validate_policy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView validatePolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + public ModelAndView validatePolicy(HttpServletRequest request, HttpServletResponse response) throws IOException{ try{ boolean valid = true; StringBuilder responseString = new StringBuilder(); @@ -266,6 +267,7 @@ public class PolicyValidationController extends RestrictedBaseController { valid = false; } }catch(Exception e){ + LOGGER.error("ERROR in ClosedLoop_PM PolicyName" , e); responseString.append("<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required</i><br>"); valid = false; } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java index 336c42ca8..946f90ac7 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java @@ -27,6 +27,7 @@ import java.util.Map; import javax.script.SimpleBindings; import org.hibernate.Criteria; +import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; @@ -277,9 +278,8 @@ public class CommonClassDaoImpl implements CommonClassDao{ }finally{ try{ session.close(); - }catch(Exception e1){ + }catch(HibernateException e1){ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - throw e1; } } return data; diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPGroupContainer.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPGroupContainer.java index ae2144b10..c05a67441 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPGroupContainer.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPGroupContainer.java @@ -40,66 +40,64 @@ import org.onap.policy.xacml.api.pap.PAPPolicyEngine; import com.att.research.xacml.api.pap.PAPException; import com.att.research.xacml.api.pap.PDP; -//import com.att.research.xacml.api.pap.PDP; -//import com.att.research.xacml.api.pap.PDPGroup; import com.att.research.xacml.api.pap.PDPPIPConfig; import com.att.research.xacml.api.pap.PDPPolicy; public class PDPGroupContainer extends PolicyItemSetChangeNotifier implements PolicyContainer.Indexed, PolicyContainer.ItemSetChangeNotifier { private static final long serialVersionUID = 1L; - private static Logger LOGGER = FlexLogger.getLogger(PDPGroupContainer.class); + private static final Logger LOGGER = FlexLogger.getLogger(PDPGroupContainer.class); /** * String identifier of a file's "Id" property. */ - private static String PROPERTY_ID = "Id"; + private static final String PROPERTY_ID = "Id"; /** * String identifier of a file's "name" property. */ - private static String PROPERTY_NAME = "Name"; + private static final String PROPERTY_NAME = "Name"; /** * String identifier of a file's "Description" property. */ - private static String PROPERTY_DESCRIPTION = "Description"; + private static final String PROPERTY_DESCRIPTION = "Description"; /** * String identifier of a file's "Default" property. */ - private static String PROPERTY_DEFAULT = "Default"; + private static final String PROPERTY_DEFAULT = "Default"; /** * String identifier of a file's "Status" property. */ - private static String PROPERTY_STATUS = "Status"; + private static final String PROPERTY_STATUS = "Status"; /** * String identifier of a file's "PDPs" property. */ - private static String PROPERTY_PDPS = "PDPs"; + private static final String PROPERTY_PDPS = "PDPs"; /** * String identifier of a file's "Policies" property. */ - private static String PROPERTY_POLICIES = "Policies"; + private static final String PROPERTY_POLICIES = "Policies"; /** * String identifier of a file's "PIP Configurations" property. */ - private static String PROPERTY_PIPCONFIG = "PIP Configurations"; + private static final String PROPERTY_PIPCONFIG = "PIP Configurations"; /** * String identifier of a file's "Selected" property. */ - private static String PROPERTY_SELECTED = "Selected"; + private static final String PROPERTY_SELECTED = "Selected"; /** * List of the string identifiers for the available properties. */ - private static Collection<String> PDP_PROPERTIES; + private static Collection<String> pDPProperties; - private PAPPolicyEngine papEngine = null; - protected List<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<OnapPDPGroup>()); + private transient PAPPolicyEngine papEngine = null; + protected transient List<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<OnapPDPGroup>()); public PDPGroupContainer(PAPPolicyEngine papPolicyEngine) { super(); @@ -107,7 +105,7 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier implements Po // // // - this.papEngine = (PAPPolicyEngine) papPolicyEngine; + this.papEngine = papPolicyEngine; // // // @@ -197,7 +195,7 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier implements Po @Override public Collection<?> getContainerPropertyIds() { - return PDP_PROPERTIES; + return pDPProperties; } @Override diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPPolicyContainer.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPPolicyContainer.java index 864078439..a3e3e28ad 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPPolicyContainer.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPPolicyContainer.java @@ -27,67 +27,68 @@ import java.util.Collections; import java.util.List; import java.util.Set; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.utils.PolicyContainer; import org.onap.policy.utils.PolicyItemSetChangeNotifier; -import org.onap.policy.common.logging.flexlogger.*; - import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.std.pap.StdPDPPolicy; + import com.att.research.xacml.api.pap.PDP; import com.att.research.xacml.api.pap.PDPGroup; import com.att.research.xacml.api.pap.PDPPolicy; -import org.onap.policy.xacml.std.pap.StdPDPPolicy; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; public class PDPPolicyContainer extends PolicyItemSetChangeNotifier implements PolicyContainer.Indexed { private static final long serialVersionUID = 1L; - private static Logger LOGGER = FlexLogger.getLogger(PDPPolicyContainer.class); + private static final Logger LOGGER = FlexLogger.getLogger(PDPPolicyContainer.class); /** * String identifier of a file's "Id" property. */ - private static String PROPERTY_ID = "Id"; + private static final String PROPERTY_ID = "Id"; /** * String identifier of a file's "name" property. */ - private static String PROPERTY_NAME = "Name"; + private static final String PROPERTY_NAME = "Name"; /** * String identifier of a file's "name" property. */ - private static String PROPERTY_VERSION = "Version"; + private static final String PROPERTY_VERSION = "Version"; /** * String identifier of a file's "Description" property. */ - private static String PROPERTY_DESCRIPTION = "Description"; + private static final String PROPERTY_DESCRIPTION = "Description"; /** * String identifier of a file's "IsRoot" property. */ - private static String PROPERTY_ISROOT = "Root"; + private static final String PROPERTY_ISROOT = "Root"; /** * List of the string identifiers for the available properties. */ - private static Collection<String> PDPPOLICY_PROPERTIES; + private static Collection<String> pDPPolicyProperties; - private final Object data; - private List<PDPPolicy> policies; + private final transient Object data; + private transient List<PDPPolicy> policies; @SuppressWarnings("unchecked") public PDPPolicyContainer(Object data) { super(); this.data = data; if (this.data instanceof PDPGroup) { - policies = new ArrayList<PDPPolicy> (((PDPGroup) this.data).getPolicies()); + policies = new ArrayList<> (((PDPGroup) this.data).getPolicies()); } if (this.data instanceof PDP) { - policies = new ArrayList<PDPPolicy> (((PDP) this.data).getPolicies()); + policies = new ArrayList<> (((PDP) this.data).getPolicies()); } if (this.data instanceof Set) { - policies = new ArrayList<PDPPolicy> ((Set<PDPPolicy>)data); + policies = new ArrayList<> ((Set<PDPPolicy>)data); } if (this.policies == null) { LOGGER.info("NULL policies"); @@ -172,7 +173,7 @@ public class PDPPolicyContainer extends PolicyItemSetChangeNotifier implements P @Override public Collection<?> getContainerPropertyIds() { - return PDPPOLICY_PROPERTIES; + return pDPPolicyProperties; } @Override diff --git a/PolicyEngineAPI/src/main/java/org/onap/policy/std/AutoClientDMAAP.java b/PolicyEngineAPI/src/main/java/org/onap/policy/std/AutoClientDMAAP.java index 3699bfcfb..d031868f0 100644 --- a/PolicyEngineAPI/src/main/java/org/onap/policy/std/AutoClientDMAAP.java +++ b/PolicyEngineAPI/src/main/java/org/onap/policy/std/AutoClientDMAAP.java @@ -10,123 +10,131 @@ import org.onap.policy.api.PDPNotification; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.utils.BusConsumer; +import org.onap.policy.utils.BusConsumer.DmaapConsumerWrapper; import org.onap.policy.xacml.api.XACMLErrorConstants; public class AutoClientDMAAP implements Runnable { - private static StdPDPNotification notification = null; - private static NotificationScheme scheme = null; - private static NotificationHandler handler = null; - private static String topic = null; - private static boolean status = false; - private static Logger logger = FlexLogger.getLogger(AutoClientDMAAP.class.getName()); - private static String notficatioinType = null; - private static BusConsumer dmaapConsumer = null; - private static List<String> dmaapList = null; - private static String aafLogin = null; - private static String aafPassword = null; - public volatile boolean isRunning = false; - - - public AutoClientDMAAP(List<String> dmaapList, String topic, String aafLogin, String aafPassword) { - AutoClientDMAAP.topic = topic; - AutoClientDMAAP.dmaapList = dmaapList; - AutoClientDMAAP.aafLogin = aafLogin; - AutoClientDMAAP.aafPassword = aafPassword; - } - - public void setAuto(NotificationScheme scheme, - NotificationHandler handler) { - AutoClientDMAAP.scheme = scheme; - AutoClientDMAAP.handler = handler; - } - - public static void setScheme(NotificationScheme scheme) { - AutoClientDMAAP.scheme = scheme; - } - - public static boolean getStatus(){ - return AutoClientDMAAP.status; - } - - public static String getTopic() { - return AutoClientDMAAP.topic; - } - - public static String getNotficationType(){ - return AutoClientDMAAP.notficatioinType; - } - - public synchronized boolean isRunning() { - return this.isRunning; - } - - public synchronized void terminate() { - this.isRunning = false; - } - - @Override - public void run() { - synchronized(this) { - this.isRunning = true; - } - String group = UUID.randomUUID ().toString (); - String id = "0"; - - // Stop and Start needs to be done. - if (scheme != null && handler!=null) { - if (scheme.equals(NotificationScheme.AUTO_ALL_NOTIFICATIONS) || scheme.equals(NotificationScheme.AUTO_NOTIFICATIONS)) { - - // create a loop to listen for messages from DMaaP server - try { - dmaapConsumer = new BusConsumer.DmaapConsumerWrapper(dmaapList, topic, aafLogin, aafPassword, group, id, 15*1000, 1000 ); - } catch (Exception e) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Unable to create DMaaP Consumer: ", e); - } - - while (this.isRunning() ) - { - try { - for ( String msg : dmaapConsumer.fetch () ) - { - logger.debug("Auto Notification Recieved Message " + msg + " from DMAAP server : " + dmaapList.toString()); - notification = NotificationUnMarshal.notificationJSON(msg); - callHandler(); - } - } catch (Exception e) { - logger.debug("Error in processing DMAAP message"); - } - - } - logger.debug("Stopping DMAAP Consumer loop will no longer fetch messages from the servers"); - } - } - } - - private static void callHandler() { - if (handler != null && scheme != null) { - if (scheme.equals(NotificationScheme.AUTO_ALL_NOTIFICATIONS)) { - boolean removed = false, updated = false; - if (notification.getRemovedPolicies() != null && !notification.getRemovedPolicies().isEmpty()) { - removed = true; - } - if (notification.getLoadedPolicies() != null && !notification.getLoadedPolicies().isEmpty()) { - updated = true; - } - if (removed && updated) { - notification.setNotificationType(NotificationType.BOTH); - } else if (removed) { - notification.setNotificationType(NotificationType.REMOVE); - } else if (updated) { - notification.setNotificationType(NotificationType.UPDATE); - } - handler.notificationReceived(notification); - } else if (scheme.equals(NotificationScheme.AUTO_NOTIFICATIONS)) { - PDPNotification newNotification = MatchStore.checkMatch(notification); - if (newNotification.getNotificationType() != null) { - handler.notificationReceived(newNotification); - } - } - } - } + private static StdPDPNotification notification = null; + private static NotificationScheme scheme = null; + private static NotificationHandler handler = null; + private static String topic = null; + private static boolean status = false; + private static Logger logger = FlexLogger.getLogger(AutoClientDMAAP.class.getName()); + private static String notficatioinType = null; + private static BusConsumer dmaapConsumer = null; + private static List<String> dmaapList = null; + private static String aafLogin = null; + private static String aafPassword = null; + private volatile boolean running = false; + + public AutoClientDMAAP(List<String> dmaapList, String topic, String aafLogin, String aafPassword) { + AutoClientDMAAP.topic = topic; + AutoClientDMAAP.dmaapList = dmaapList; + AutoClientDMAAP.aafLogin = aafLogin; + AutoClientDMAAP.aafPassword = aafPassword; + } + + public static void setAuto(NotificationScheme scheme, NotificationHandler handler) { + AutoClientDMAAP.scheme = scheme; + AutoClientDMAAP.handler = handler; + } + + public static void setScheme(NotificationScheme scheme) { + AutoClientDMAAP.scheme = scheme; + } + + public static boolean getStatus() { + return AutoClientDMAAP.status; + } + + public static String getTopic() { + return AutoClientDMAAP.topic; + } + + public static String getNotficationType() { + return AutoClientDMAAP.notficatioinType; + } + + public synchronized boolean isRunning() { + return this.running; + } + + public synchronized void terminate() { + this.running = false; + } + + @Override + public void run() { + synchronized (this) { + this.running = true; + } + String group = UUID.randomUUID().toString(); + String id = "0"; + + // Stop and Start needs to be done. + if (scheme != null && handler != null) { + if (scheme.equals(NotificationScheme.AUTO_ALL_NOTIFICATIONS) + || scheme.equals(NotificationScheme.AUTO_NOTIFICATIONS)) { + + // create a loop to listen for messages from DMaaP server + try { + setDmaapCosumer(new BusConsumer.DmaapConsumerWrapper(dmaapList, topic, aafLogin, aafPassword, group, + id, 15 * 1000, 1000)); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Unable to create DMaaP Consumer: ", e); + } + + while (this.isRunning()) { + try { + for (String msg : dmaapConsumer.fetch()) { + logger.debug("Auto Notification Recieved Message " + msg + " from DMAAP server : " + + dmaapList.toString()); + setNotification(NotificationUnMarshal.notificationJSON(msg)); + callHandler(); + } + } catch (Exception e) { + logger.debug("Error in processing DMAAP message", e); + } + + } + logger.debug("Stopping DMAAP Consumer loop will no longer fetch messages from the servers"); + } + } + } + + private void setNotification(StdPDPNotification notificationJSON) { + notification = notificationJSON; + } + + private static void setDmaapCosumer(DmaapConsumerWrapper dmaapConsumerWrapper) { + dmaapConsumer = dmaapConsumerWrapper; + } + + private static void callHandler() { + if (handler != null && scheme != null) { + if (scheme.equals(NotificationScheme.AUTO_ALL_NOTIFICATIONS)) { + boolean removed = false, updated = false; + if (notification.getRemovedPolicies() != null && !notification.getRemovedPolicies().isEmpty()) { + removed = true; + } + if (notification.getLoadedPolicies() != null && !notification.getLoadedPolicies().isEmpty()) { + updated = true; + } + if (removed && updated) { + notification.setNotificationType(NotificationType.BOTH); + } else if (removed) { + notification.setNotificationType(NotificationType.REMOVE); + } else if (updated) { + notification.setNotificationType(NotificationType.UPDATE); + } + handler.notificationReceived(notification); + } else if (scheme.equals(NotificationScheme.AUTO_NOTIFICATIONS)) { + PDPNotification newNotification = MatchStore.checkMatch(notification); + if (newNotification.getNotificationType() != null) { + handler.notificationReceived(newNotification); + } + } + } + } } diff --git a/PolicyEngineAPI/src/main/java/org/onap/policy/std/AutoClientEnd.java b/PolicyEngineAPI/src/main/java/org/onap/policy/std/AutoClientEnd.java index 976b57058..f0d99d09e 100644 --- a/PolicyEngineAPI/src/main/java/org/onap/policy/std/AutoClientEnd.java +++ b/PolicyEngineAPI/src/main/java/org/onap/policy/std/AutoClientEnd.java @@ -32,19 +32,14 @@ import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; -//import org.apache.log4j.Logger; import org.glassfish.tyrus.client.ClientManager; import org.onap.policy.api.NotificationHandler; import org.onap.policy.api.NotificationScheme; import org.onap.policy.api.NotificationType; import org.onap.policy.api.PDPNotification; -import org.onap.policy.std.NotificationStore; -import org.onap.policy.std.StdPDPNotification; - -import org.onap.policy.xacml.api.XACMLErrorConstants; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import org.onap.policy.common.logging.flexlogger.*; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.xacml.api.XACMLErrorConstants; @ClientEndpoint public class AutoClientEnd { @@ -99,12 +94,10 @@ public class AutoClientEnd { // The URL's will be in Sync according to design Spec. ManualClientEnd.start(AutoClientEnd.url); StdPDPNotification notification = NotificationStore.getDeltaNotification((StdPDPNotification)ManualClientEnd.result(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)); - if(notification.getNotificationType()!=null){ - if(oldNotification!=notification){ - oldNotification= notification; - AutoClientEnd.notification = notification; - callHandler(); - } + if(notification.getNotificationType()!=null&&oldNotification!=notification){ + oldNotification= notification; + AutoClientEnd.notification = notification; + callHandler(); } error = false; } @@ -136,7 +129,7 @@ public class AutoClientEnd { session.close(); session = null; } catch (IOException e) { - // + logger.error("Error closing websocket connection", e); } } client = null; @@ -148,7 +141,8 @@ public class AutoClientEnd { private static void callHandler() { if (handler != null && scheme != null) { if (scheme.equals(NotificationScheme.AUTO_ALL_NOTIFICATIONS)) { - boolean removed = false, updated = false; + boolean removed = false; + boolean updated = false; if (notification.getRemovedPolicies() != null && !notification.getRemovedPolicies().isEmpty()) { removed = true; } @@ -182,9 +176,7 @@ public class AutoClientEnd { // WebSockets Code.. @OnOpen - public void onOpen(Session session) throws IOException { - // session.getBasicRemote().sendText("Connected to Client with Session: " - // + session.getId()); + public static void onOpen(Session session){ logger.debug("Auto Notification Session Started... " + session.getId()); if(AutoClientEnd.session == null){ AutoClientEnd.session = session; @@ -192,10 +184,9 @@ public class AutoClientEnd { } @OnError - public void onError(Session session, Throwable e) { + public static void onError(Session session, Throwable e) { // trying to Restart by self. logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Session Error.. "+ session.getId() + "\n Error is : " + e ); - // logger.error("Exception Occured"+e); stop(); if (url != null) { client = null; @@ -206,7 +197,7 @@ public class AutoClientEnd { } @OnClose - public void onClose(Session session) { + public static void onClose(Session session) { logger.info("Session ended with "+ session.getId()); if(!stop && !message){ // This Block of code is executed if there is any Network Failure or if the Notification is Down. @@ -222,7 +213,7 @@ public class AutoClientEnd { } @OnMessage - public void onMessage(String message, Session session) throws JsonParseException, JsonMappingException, IOException { + public static void onMessage(String message, Session session) throws IOException { AutoClientEnd.message = true; logger.debug("Auto Notification Recieved Message " + message + " Session info is : " + session.getId()); try { diff --git a/PolicyEngineAPI/src/main/java/org/onap/policy/std/AutoClientUEB.java b/PolicyEngineAPI/src/main/java/org/onap/policy/std/AutoClientUEB.java index 37413f416..f84568aba 100644 --- a/PolicyEngineAPI/src/main/java/org/onap/policy/std/AutoClientUEB.java +++ b/PolicyEngineAPI/src/main/java/org/onap/policy/std/AutoClientUEB.java @@ -51,11 +51,11 @@ public class AutoClientUEB implements Runnable { private static boolean status = false; private static Logger logger = FlexLogger.getLogger(AutoClientUEB.class.getName()); private static String notficatioinType = null; - private static CambriaConsumer CConsumer = null; + private static CambriaConsumer cConsumer = null; private static String apiKey = null; private static String apiSecret = null; private static List<String> uebURLList = null; - public volatile boolean isRunning = false; + private volatile boolean running = false; public AutoClientUEB(String url, List<String> uebURLList, String apiKey, String apiSecret) { @@ -65,7 +65,7 @@ public class AutoClientUEB implements Runnable { AutoClientUEB.apiKey = apiKey; } - public void setAuto(NotificationScheme scheme, + public static void setAuto(NotificationScheme scheme, NotificationHandler handler) { AutoClientUEB.scheme = scheme; AutoClientUEB.handler = handler; @@ -88,34 +88,31 @@ public class AutoClientUEB implements Runnable { } public synchronized boolean isRunning() { - return this.isRunning; + return this.running; } public synchronized void terminate() { - this.isRunning = false; + this.running = false; } @Override public void run() { synchronized(this) { - this.isRunning = true; + this.running = true; } String group = UUID.randomUUID ().toString (); String id = "0"; - //String topic = null; // Stop and Start needs to be done. if (scheme != null && handler!=null) { if (scheme.equals(NotificationScheme.AUTO_ALL_NOTIFICATIONS) || scheme.equals(NotificationScheme.AUTO_NOTIFICATIONS)) { URL aURL; try { aURL = new URL(AutoClientUEB.topic); - topic = aURL.getHost() + aURL.getPort(); + setTopic(aURL.getHost() + aURL.getPort()); } catch (MalformedURLException e) { - topic = AutoClientUEB.url.replace("[:/]", ""); + setTopic(AutoClientUEB.url.replace("[:/]", "")); } - try { - //CConsumer = CambriaClientFactory.createConsumer ( null, uebURLList, topic, group, id, 15*1000, 1000 ); ConsumerBuilder builder = new CambriaClientBuilders.ConsumerBuilder(); builder.knownAs(group, id) .usingHosts(uebURLList) @@ -123,35 +120,46 @@ public class AutoClientUEB implements Runnable { .waitAtServer(15*1000) .receivingAtMost(1000) .authenticatedBy(apiKey, apiSecret); - - CConsumer = builder.build(); - + setConsumer(builder.build()); } catch (Exception e1) { logger.error("Exception Occured" + e1); } - while (this.isRunning() ) - { - try { - for ( String msg : CConsumer.fetch () ) - { - logger.debug("Auto Notification Recieved Message " + msg + " from UEB cluster : " + uebURLList.toString()); - notification = NotificationUnMarshal.notificationJSON(msg); - callHandler(); - } - } catch (Exception e) { - logger.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Error in processing UEB message" + e.getMessage()); - } + while (this.isRunning()) { + try { + for (String msg : cConsumer.fetch()) { + logger.debug("Auto Notification Recieved Message " + msg + " from UEB cluster : " + + uebURLList.toString()); + setNotification(NotificationUnMarshal.notificationJSON(msg)); + callHandler(); + } + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Error in processing UEB message" + + e.getMessage(), e); + } - } + } logger.debug("Stopping UEB Consumer loop will not logger fetch messages from the cluster"); } } } - private static void callHandler() { + private static void setNotification(StdPDPNotification notificationJSON) { + notification = notificationJSON; + } + + private static void setConsumer(CambriaConsumer build) { + cConsumer = build; + } + + private static void setTopic(String topic) { + AutoClientUEB.topic = topic; + } + + private static void callHandler() { if (handler != null && scheme != null) { if (scheme.equals(NotificationScheme.AUTO_ALL_NOTIFICATIONS)) { - boolean removed = false, updated = false; + boolean removed = false; + boolean updated = false; if (notification.getRemovedPolicies() != null && !notification.getRemovedPolicies().isEmpty()) { removed = true; } diff --git a/PolicyEngineAPI/src/main/java/org/onap/policy/std/ManualClientEnd.java b/PolicyEngineAPI/src/main/java/org/onap/policy/std/ManualClientEnd.java index 7e4ba07e8..db3fdf194 100644 --- a/PolicyEngineAPI/src/main/java/org/onap/policy/std/ManualClientEnd.java +++ b/PolicyEngineAPI/src/main/java/org/onap/policy/std/ManualClientEnd.java @@ -33,7 +33,6 @@ import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; -//import org.apache.log4j.Logger; import org.glassfish.tyrus.client.ClientManager; import org.onap.policy.api.NotificationScheme; import org.onap.policy.api.NotificationType; @@ -62,9 +61,7 @@ public class ManualClientEnd { try { client.connectToServer(ManualClientEnd.class, new URI(url+"notifications")); latch.await(); - } catch (DeploymentException | URISyntaxException | InterruptedException e) { - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); - } catch (IOException e) { + } catch (DeploymentException | URISyntaxException | InterruptedException |IOException e) { logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); } } @@ -75,7 +72,8 @@ public class ManualClientEnd { return null; } else { if(scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)) { - boolean removed = false, updated = false; + boolean removed = false; + boolean updated = false; if(notification.getRemovedPolicies()!=null && !notification.getRemovedPolicies().isEmpty()){ removed = true; } @@ -118,7 +116,7 @@ public class ManualClientEnd { } @OnMessage - public void onMessage(String message, Session session){ + public static void onMessage(String message, Session session){ logger.debug(" Manual Notification Recieved Message : " + message +" Session info is : "+ session.getId()); resultJson = message; try { diff --git a/PolicyEngineAPI/src/main/java/org/onap/policy/std/ManualClientEndUEB.java b/PolicyEngineAPI/src/main/java/org/onap/policy/std/ManualClientEndUEB.java index dcd86eb1f..29c85a2ad 100644 --- a/PolicyEngineAPI/src/main/java/org/onap/policy/std/ManualClientEndUEB.java +++ b/PolicyEngineAPI/src/main/java/org/onap/policy/std/ManualClientEndUEB.java @@ -145,13 +145,12 @@ public class ManualClientEndUEB { logger.debug("Manual Notification Recieved Message " + msg + " from UEB cluster : " + uebURLList.toString()); resultJson = msg; if (!msg.contains("UEB Update")){ -// System.out.println("Manual Notification Recieved Message " + msg + " from UEB cluster : " + uebURLList.toString()); notification = NotificationUnMarshal.notificationJSON(msg); count = 4; } } }catch (Exception e) { - + logger.error("Error in Manual CLient UEB notification ", e); } count++; } diff --git a/PolicyEngineAPI/src/main/java/org/onap/policy/std/NotificationUnMarshal.java b/PolicyEngineAPI/src/main/java/org/onap/policy/std/NotificationUnMarshal.java index 2ec174c84..447e7cb26 100644 --- a/PolicyEngineAPI/src/main/java/org/onap/policy/std/NotificationUnMarshal.java +++ b/PolicyEngineAPI/src/main/java/org/onap/policy/std/NotificationUnMarshal.java @@ -20,49 +20,45 @@ package org.onap.policy.std; +import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import org.onap.policy.api.LoadedPolicy; import org.onap.policy.api.RemovedPolicy; import org.onap.policy.api.UpdateType; -import org.onap.policy.std.StdLoadedPolicy; -import org.onap.policy.std.StdPDPNotification; import com.fasterxml.jackson.databind.ObjectMapper; public class NotificationUnMarshal { - private static StdPDPNotification notification; - public static StdPDPNotification notificationJSON(String json) throws Exception{ + public static StdPDPNotification notificationJSON(String json) throws IOException{ ObjectMapper mapper = new ObjectMapper(); - notification = mapper.readValue(json, StdPDPNotification.class); - if(notification!=null){ - if(notification.getLoadedPolicies()!=null){ - Collection<StdLoadedPolicy> stdLoadedPolicies = new ArrayList<>(); - for(LoadedPolicy loadedPolicy: notification.getLoadedPolicies()){ - StdLoadedPolicy stdLoadedPolicy = (StdLoadedPolicy) loadedPolicy; - if(notification.getRemovedPolicies()!=null){ - Boolean updated = false; - for(RemovedPolicy removedPolicy: notification.getRemovedPolicies()){ - String regex = ".(\\d)*.xml"; - if(removedPolicy.getPolicyName().replaceAll(regex, "").equals(stdLoadedPolicy.getPolicyName().replaceAll(regex, ""))){ - updated = true; - break; - } - } - if(updated){ - stdLoadedPolicy.setUpdateType(UpdateType.UPDATE); - }else{ - stdLoadedPolicy.setUpdateType(UpdateType.NEW); - } - }else{ - stdLoadedPolicy.setUpdateType(UpdateType.NEW); - } - stdLoadedPolicies.add(stdLoadedPolicy); - } - notification.setLoadedPolicies(stdLoadedPolicies); - } + StdPDPNotification notification = mapper.readValue(json, StdPDPNotification.class); + if(notification!=null&¬ification.getLoadedPolicies()!=null){ + Collection<StdLoadedPolicy> stdLoadedPolicies = new ArrayList<>(); + for(LoadedPolicy loadedPolicy: notification.getLoadedPolicies()){ + StdLoadedPolicy stdLoadedPolicy = (StdLoadedPolicy) loadedPolicy; + if(notification.getRemovedPolicies()!=null){ + Boolean updated = false; + for(RemovedPolicy removedPolicy: notification.getRemovedPolicies()){ + String regex = ".(\\d)*.xml"; + if(removedPolicy.getPolicyName().replaceAll(regex, "").equals(stdLoadedPolicy.getPolicyName().replaceAll(regex, ""))){ + updated = true; + break; + } + } + if(updated){ + stdLoadedPolicy.setUpdateType(UpdateType.UPDATE); + }else{ + stdLoadedPolicy.setUpdateType(UpdateType.NEW); + } + }else{ + stdLoadedPolicy.setUpdateType(UpdateType.NEW); + } + stdLoadedPolicies.add(stdLoadedPolicy); + } + notification.setLoadedPolicies(stdLoadedPolicies); } return notification; } diff --git a/PolicyEngineAPI/src/main/java/org/onap/policy/std/StdPolicyEngine.java b/PolicyEngineAPI/src/main/java/org/onap/policy/std/StdPolicyEngine.java index 8a6c6c668..4e904b6e1 100644 --- a/PolicyEngineAPI/src/main/java/org/onap/policy/std/StdPolicyEngine.java +++ b/PolicyEngineAPI/src/main/java/org/onap/policy/std/StdPolicyEngine.java @@ -18,7 +18,6 @@ * ============LICENSE_END========================================================= */ - package org.onap.policy.std; import java.io.FileInputStream; @@ -107,184 +106,189 @@ import com.google.gson.GsonBuilder; * @version 1.0 */ public class StdPolicyEngine { - private static final String ERROR_AUTH_GET_PERM = "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to: "; - private static final String DEFAULT_NOTIFICATION = "websocket"; - - private String propertyFilePath = null; - private String clientEncoding = null; - private String contentType = null; - private static List<String> pdps = null; - private static String environment= null; - private static String userName = null; - private static String pass = null; - private static List<String> encoding = null; - private static boolean junit = false; - private List<String> pdpDefault = null; - private List<String> typeDefault = null; - private List<String> notificationType = new ArrayList<String>(); - private List<String> notificationURLList = new ArrayList<String>(); - private NotificationScheme scheme = null; - private NotificationHandler handler = null; - private AutoClientUEB uebClientThread = null; - private Thread registerUEBThread = null; - private boolean uebThread = false; - private AutoClientDMAAP dmaapClientThread = null; - private Thread registerDMAAPThread = null; - private boolean dmaapThread = false; - private String topic = null; - private String apiKey = null; - private String apiSecret = null; - - private static final String UNIQUEID = UUID.randomUUID ().toString (); - private static final Logger LOGGER = FlexLogger.getLogger(StdPolicyConfig.class.getName()); - - /* - * Taking the Property file even if it null. - */ - public StdPolicyEngine(String propertyFilePath, String clientKey) throws PolicyEngineException { - setProperty(propertyFilePath, clientKey); - } - - /* - * Taking the Notification Constructor. - */ - public StdPolicyEngine(String propertyFilePath, - NotificationScheme scheme, - NotificationHandler handler) throws PolicyEngineException { - setProperty(propertyFilePath, null); - this.scheme = scheme; - this.handler = handler; - if ((!"ueb".equals(notificationType.get(0)))||(!"dmaap".equals(notificationType.get(0)))){ - AutoClientEnd.setAuto(scheme, handler); - } - notification(scheme, handler); - } - - /* - * Taking the Notification Constructor. - */ - public StdPolicyEngine(String propertyFilePath, NotificationScheme scheme) throws PolicyEngineException { - setProperty(propertyFilePath, null); - this.scheme = scheme; - setScheme(scheme); - } - - /* - * sendEvent API Implementation - */ - public Collection<PolicyResponse> sendEvent(Map<String, String> eventAttributes, UUID requestID) throws PolicyEventException { - return sendEventImpl(eventAttributes, requestID); - } - - /* - * sendEvent API Implementation for eventRequestParameters - */ - public Collection<PolicyResponse> sendEvent(EventRequestParameters eventRequestParameters) throws PolicyEventException{ - if(eventRequestParameters==null){ - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No event Request Parameters Given. "; - LOGGER.error(message); - throw new PolicyEventException(message); - } - return sendEventImpl(eventRequestParameters.getEventAttributes(), eventRequestParameters.getRequestID()); - } - - /* - * getConfig using configRequestParameters Implementation - */ - public Collection<PolicyConfig> getConfig(ConfigRequestParameters configRequestParameters) throws PolicyConfigException{ - return getConfigImpl(configRequestParameters); - } - - /* - * listPolicies using configRequestParameters Implementation - */ - public Collection<String> listConfig(ConfigRequestParameters listPolicyRequestParameters) throws PolicyConfigException{ - return listConfigImpl(listPolicyRequestParameters); - } - - /* - * getDecision using the decision Attributes. - */ - public DecisionResponse getDecision(String onapName, Map<String, String> decisionAttributes, UUID requestID) throws PolicyDecisionException { - return getDecisionImpl(onapName, decisionAttributes, requestID); - } - - /* - * getDecision Using decisionRequestParameters. - */ - public DecisionResponse getDecision(DecisionRequestParameters decisionRequestParameters) throws PolicyDecisionException{ - if(decisionRequestParameters==null){ - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Decision Request Parameters Given. "; - LOGGER.error(message); - throw new PolicyDecisionException(message); - } - return getDecisionImpl(decisionRequestParameters.getOnapName(), decisionRequestParameters.getDecisionAttributes(), decisionRequestParameters.getRequestID()); - } - - /* - * getMetrics using metricsRequestParameters - */ - public MetricsResponse getMetrics(MetricsRequestParameters parameters) throws PolicyException{ - return getMetricsImpl(parameters); - } - - public MetricsResponse getMetricsImpl(MetricsRequestParameters parameters) throws PolicyException{ - StdMetricsResponse response = new StdMetricsResponse(); - String resource = "getMetrics"; - String body = new String(); - - // Create the Request - try { - if (parameters!=null) { - body = PolicyUtils.objectToJsonString(parameters); - } - } catch (JsonProcessingException e) { - String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; - LOGGER.error(message); - throw new PolicyException(message, e); - } - // Get Response. + private static final String ERROR_AUTH_GET_PERM = "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to: "; + private static final String DEFAULT_NOTIFICATION = "websocket"; + + private String clientEncoding = null; + private String contentType = null; + private static List<String> pdps = null; + private static String environment = null; + private static String userName = null; + private static String pass = null; + private static List<String> encoding = null; + private static boolean junit = false; + private List<String> pdpDefault = null; + private List<String> typeDefault = null; + private List<String> notificationType = new ArrayList<>(); + private List<String> notificationURLList = new ArrayList<>(); + private NotificationScheme scheme = null; + private NotificationHandler handler = null; + private AutoClientUEB uebClientThread = null; + private Thread registerUEBThread = null; + private boolean uebThread = false; + private AutoClientDMAAP dmaapClientThread = null; + private Thread registerDMAAPThread = null; + private boolean dmaapThread = false; + private String topic = null; + private String apiKey = null; + private String apiSecret = null; + + private static final String UNIQUEID = UUID.randomUUID().toString(); + private static final Logger LOGGER = FlexLogger.getLogger(StdPolicyConfig.class.getName()); + + /* + * Taking the Property file even if it null. + */ + public StdPolicyEngine(String propertyFilePath, String clientKey) throws PolicyEngineException { + setProperty(propertyFilePath, clientKey); + } + + /* + * Taking the Notification Constructor. + */ + public StdPolicyEngine(String propertyFilePath, NotificationScheme scheme, NotificationHandler handler) + throws PolicyEngineException { + setProperty(propertyFilePath, null); + this.scheme = scheme; + this.handler = handler; + if ((!"ueb".equals(notificationType.get(0))) || (!"dmaap".equals(notificationType.get(0)))) { + AutoClientEnd.setAuto(scheme, handler); + } + notification(scheme, handler); + } + + /* + * Taking the Notification Constructor. + */ + public StdPolicyEngine(String propertyFilePath, NotificationScheme scheme) throws PolicyEngineException { + setProperty(propertyFilePath, null); + this.scheme = scheme; + setScheme(scheme); + } + + /* + * sendEvent API Implementation + */ + public Collection<PolicyResponse> sendEvent(Map<String, String> eventAttributes, UUID requestID) + throws PolicyEventException { + return sendEventImpl(eventAttributes, requestID); + } + + /* + * sendEvent API Implementation for eventRequestParameters + */ + public Collection<PolicyResponse> sendEvent(EventRequestParameters eventRequestParameters) + throws PolicyEventException { + if (eventRequestParameters == null) { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No event Request Parameters Given. "; + LOGGER.error(message); + throw new PolicyEventException(message); + } + return sendEventImpl(eventRequestParameters.getEventAttributes(), eventRequestParameters.getRequestID()); + } + + /* + * getConfig using configRequestParameters Implementation + */ + public Collection<PolicyConfig> getConfig(ConfigRequestParameters configRequestParameters) + throws PolicyConfigException { + return getConfigImpl(configRequestParameters); + } + + /* + * listPolicies using configRequestParameters Implementation + */ + public Collection<String> listConfig(ConfigRequestParameters listPolicyRequestParameters) + throws PolicyConfigException { + return listConfigImpl(listPolicyRequestParameters); + } + + /* + * getDecision using the decision Attributes. + */ + public DecisionResponse getDecision(String onapName, Map<String, String> decisionAttributes, UUID requestID) + throws PolicyDecisionException { + return getDecisionImpl(onapName, decisionAttributes, requestID); + } + + /* + * getDecision Using decisionRequestParameters. + */ + public DecisionResponse getDecision(DecisionRequestParameters decisionRequestParameters) + throws PolicyDecisionException { + if (decisionRequestParameters == null) { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Decision Request Parameters Given. "; + LOGGER.error(message); + throw new PolicyDecisionException(message); + } + return getDecisionImpl(decisionRequestParameters.getOnapName(), + decisionRequestParameters.getDecisionAttributes(), decisionRequestParameters.getRequestID()); + } + + /* + * getMetrics using metricsRequestParameters + */ + public MetricsResponse getMetrics(MetricsRequestParameters parameters) throws PolicyException { + return getMetricsImpl(parameters); + } + + public MetricsResponse getMetricsImpl(MetricsRequestParameters parameters) throws PolicyException { + StdMetricsResponse response = new StdMetricsResponse(); + String resource = "getMetrics"; + String body = null; + // Create the Request + try { + if (parameters != null) { + body = PolicyUtils.objectToJsonString(parameters); + } + } catch (JsonProcessingException e) { + String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; + LOGGER.error(message); + throw new PolicyException(message, e); + } + // Get Response. try { ResponseEntity<String> result = callNewPDP(resource, HttpMethod.GET, body, String.class); // Process response response.setResponseMessage(result.getBody()); response.setResponseCode(result.getStatusCode().value()); } catch (PolicyException exception) { - if(exception.getCause()!=null && exception.getCause() instanceof HttpClientErrorException){ + if (exception.getCause() != null && exception.getCause() instanceof HttpClientErrorException) { LOGGER.error(exception); HttpClientErrorException ex = (HttpClientErrorException) exception.getCause(); response.setResponseCode(ex.getRawStatusCode()); response.setResponseMessage(exception.getMessage()); return response; - }else{ - String message = XACMLErrorConstants.ERROR_SYSTEM_ERROR+ "Error while processing results. please check logs."; + } else { + String message = XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "Error while processing results. please check logs."; LOGGER.error(message, exception); throw new PolicyException(message, exception); - } + } } - return response; - } - - /* - * PushPolicy using pushPolicyParameters. - */ - public PolicyChangeResponse pushPolicy(PushPolicyParameters pushPolicyParameters) throws PolicyException{ - return pushPolicyImpl(pushPolicyParameters); - } - - public PolicyChangeResponse pushPolicyImpl(PushPolicyParameters pushPolicyParameters) throws PolicyException{ - StdPolicyChangeResponse response = new StdPolicyChangeResponse(); - String resource= "pushPolicy"; - String body = new String(); - // Create Request. + return response; + } + + /* + * PushPolicy using pushPolicyParameters. + */ + public PolicyChangeResponse pushPolicy(PushPolicyParameters pushPolicyParameters) throws PolicyException { + return pushPolicyImpl(pushPolicyParameters); + } + + public PolicyChangeResponse pushPolicyImpl(PushPolicyParameters pushPolicyParameters) throws PolicyException { + StdPolicyChangeResponse response = new StdPolicyChangeResponse(); + String resource = "pushPolicy"; + String body = null; + // Create Request. try { body = PolicyUtils.objectToJsonString(pushPolicyParameters); } catch (JsonProcessingException e) { - String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; + String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; LOGGER.error(message); throw new PolicyException(message, e); } - // Get Response. + // Get Response. try { ResponseEntity<String> result = callNewPDP(resource, HttpMethod.PUT, body, String.class); // Process response @@ -294,28 +298,28 @@ public class StdPolicyEngine { return processException(exception); } return response; - } - - /* - * Delete a Policy using deletePolicyParameters - */ - public PolicyChangeResponse deletePolicy(DeletePolicyParameters parameters) throws PolicyException { - return deletePolicyImpl(parameters); - } - - public PolicyChangeResponse deletePolicyImpl(DeletePolicyParameters parameters) throws PolicyException { - StdPolicyChangeResponse response = new StdPolicyChangeResponse(); - String resource= "deletePolicy"; - String body = new String(); - // Create Request. + } + + /* + * Delete a Policy using deletePolicyParameters + */ + public PolicyChangeResponse deletePolicy(DeletePolicyParameters parameters) throws PolicyException { + return deletePolicyImpl(parameters); + } + + public PolicyChangeResponse deletePolicyImpl(DeletePolicyParameters parameters) throws PolicyException { + StdPolicyChangeResponse response = new StdPolicyChangeResponse(); + String resource = "deletePolicy"; + String body = null; + // Create Request. try { body = PolicyUtils.objectToJsonString(parameters); } catch (JsonProcessingException e) { - String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; + String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; LOGGER.error(message); throw new PolicyException(message, e); } - // Get Response. + // Get Response. try { ResponseEntity<String> result = callNewPDP(resource, HttpMethod.DELETE, body, String.class); // Process response @@ -325,61 +329,64 @@ public class StdPolicyEngine { return processException(exception); } return response; - } - - /* - * getDictionaryItem Using dictionaryParameters - */ - public DictionaryResponse getDictionaryItem(DictionaryParameters parameters) throws PolicyException { - return getDictionaryItemImpl(parameters); - } - - public DictionaryResponse getDictionaryItemImpl(DictionaryParameters parameters) throws PolicyException{ - StdDictionaryResponse response = new StdDictionaryResponse(); - String resource="getDictionaryItems"; - String body = "{}"; - // Create Request. + } + + /* + * getDictionaryItem Using dictionaryParameters + */ + public DictionaryResponse getDictionaryItem(DictionaryParameters parameters) throws PolicyException { + return getDictionaryItemImpl(parameters); + } + + public DictionaryResponse getDictionaryItemImpl(DictionaryParameters parameters) throws PolicyException { + StdDictionaryResponse response = new StdDictionaryResponse(); + String resource = "getDictionaryItems"; + String body = "{}"; + // Create Request. try { body = PolicyUtils.objectToJsonString(parameters); } catch (JsonProcessingException e) { - String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; + String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; LOGGER.error(message); throw new PolicyException(message, e); } - // Get Response. + // Get Response. try { - ResponseEntity<APIDictionaryResponse> result = callNewPDP(resource, HttpMethod.POST, body, APIDictionaryResponse.class); + ResponseEntity<APIDictionaryResponse> result = callNewPDP(resource, HttpMethod.POST, body, + APIDictionaryResponse.class); // Process response response = dictionaryResult(result.getBody()); } catch (Exception exception) { - if(exception.getCause().getMessage().contains("401")){ + if (exception.getCause().getMessage().contains("401")) { String message = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_AUTH_GET_PERM + resource; LOGGER.error(message); response.setResponseMessage(message); response.setResponseCode(401); return response; - }if(exception.getCause().getMessage().contains("400")){ + } + if (exception.getCause().getMessage().contains("400")) { String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Data is given."; response.setResponseMessage(message); response.setResponseCode(400); return response; } - String message = XACMLErrorConstants.ERROR_PERMISSIONS+ "Unable to get valid Response from PDP(s) " + pdps; + String message = XACMLErrorConstants.ERROR_PERMISSIONS + "Unable to get valid Response from PDP(s) " + + pdps; LOGGER.error(message, exception); response.setResponseMessage(message); response.setResponseCode(500); return response; } - return response; - } - - @SuppressWarnings("unchecked") + return response; + } + + @SuppressWarnings("unchecked") private StdDictionaryResponse dictionaryResult(APIDictionaryResponse body) { StdDictionaryResponse response = new StdDictionaryResponse(); response.setResponseCode(body.getResponseCode()); response.setResponseMessage(body.getResponseMessage()); response.setDictionaryData((Map<String, String>) body.getDictionaryData()); - if(body.getDictionaryJson()!=null){ + if (body.getDictionaryJson() != null) { Gson objGson = new GsonBuilder().create(); String mapToJson = objGson.toJson(body.getDictionaryJson()); JsonReader jsonReader = Json.createReader(new StringReader(mapToJson)); @@ -391,35 +398,36 @@ public class StdPolicyEngine { } /* - * createDictinaryItem Using dictionaryParameters. - */ - public PolicyChangeResponse createDictionaryItem(DictionaryParameters parameters) throws PolicyException{ - return createUpdateDictionaryItemImpl(parameters, false); - } - - /* - * updateDictinaryItem Using dictionaryParameters. - */ - public PolicyChangeResponse updateDictionaryItem(DictionaryParameters parameters) throws PolicyException{ - return createUpdateDictionaryItemImpl(parameters, true); - } - - public PolicyChangeResponse createUpdateDictionaryItemImpl(DictionaryParameters parameters, boolean updateFlag) throws PolicyException{ - StdPolicyChangeResponse response = new StdPolicyChangeResponse(); - String resource = "createDictionaryItem"; - if(updateFlag){ - resource = "updateDictionaryItem"; - } - String body = new String(); - // Create Request. + * createDictinaryItem Using dictionaryParameters. + */ + public PolicyChangeResponse createDictionaryItem(DictionaryParameters parameters) throws PolicyException { + return createUpdateDictionaryItemImpl(parameters, false); + } + + /* + * updateDictinaryItem Using dictionaryParameters. + */ + public PolicyChangeResponse updateDictionaryItem(DictionaryParameters parameters) throws PolicyException { + return createUpdateDictionaryItemImpl(parameters, true); + } + + public PolicyChangeResponse createUpdateDictionaryItemImpl(DictionaryParameters parameters, boolean updateFlag) + throws PolicyException { + StdPolicyChangeResponse response = new StdPolicyChangeResponse(); + String resource = "createDictionaryItem"; + if (updateFlag) { + resource = "updateDictionaryItem"; + } + String body = null; + // Create Request. try { body = PolicyUtils.objectToJsonString(parameters); } catch (JsonProcessingException e) { - String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; + String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; LOGGER.error(message); throw new PolicyException(message, e); } - // Get Response. + // Get Response. try { ResponseEntity<String> result = callNewPDP(resource, HttpMethod.PUT, body, String.class); // Process response @@ -429,31 +437,31 @@ public class StdPolicyEngine { return processException(exception); } return response; - } - - /* - * PolicyEngine Import - */ - public PolicyChangeResponse policyEngineImport(ImportParameters importParameters) throws PolicyException { - return policyEngineImportImpl(importParameters); - } - - public PolicyChangeResponse policyEngineImportImpl(ImportParameters importParameters) throws PolicyException { - StdPolicyChangeResponse response = new StdPolicyChangeResponse(); - String resource= "policyEngineImport"; - LinkedMultiValueMap<String, Object> parameters = new LinkedMultiValueMap<String, Object>(); - // Create Request. + } + + /* + * PolicyEngine Import + */ + public PolicyChangeResponse policyEngineImport(ImportParameters importParameters) throws PolicyException { + return policyEngineImportImpl(importParameters); + } + + public PolicyChangeResponse policyEngineImportImpl(ImportParameters importParameters) throws PolicyException { + StdPolicyChangeResponse response = new StdPolicyChangeResponse(); + String resource = "policyEngineImport"; + LinkedMultiValueMap<String, Object> parameters = new LinkedMultiValueMap<String, Object>(); + // Create Request. try { String body = PolicyUtils.objectToJsonString(importParameters); parameters.set("importParametersJson", body); parameters.set("file", new FileSystemResource(importParameters.getFilePath())); } catch (Exception e) { - String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; + String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; LOGGER.error(message); throw new PolicyException(message, e); } contentType = MediaType.MULTIPART_FORM_DATA_VALUE; - // Get Response. + // Get Response. try { ResponseEntity<String> result = callNewPDP(resource, HttpMethod.POST, parameters, String.class); // Process response @@ -461,42 +469,43 @@ public class StdPolicyEngine { response.setResponseCode(result.getStatusCode().value()); } catch (PolicyException exception) { return processException(exception); - } finally{ + } finally { contentType = null; } return response; - } - - /* - * createPolicy Using policyParameters. - */ - public PolicyChangeResponse createPolicy(PolicyParameters policyParameters) throws PolicyException{ - return createUpdatePolicyImpl(policyParameters, false); - } - - /* - * updatePolicy using policyParameters. - */ - public PolicyChangeResponse updatePolicy(PolicyParameters policyParameters) throws PolicyException{ - return createUpdatePolicyImpl(policyParameters, true); - } - - public PolicyChangeResponse createUpdatePolicyImpl(PolicyParameters policyParameters, boolean updateFlag) throws PolicyException{ - StdPolicyChangeResponse response = new StdPolicyChangeResponse(); - String resource= "createPolicy"; - if(updateFlag){ - resource="updatePolicy"; - } - String body = new String(); - // Create Request. + } + + /* + * createPolicy Using policyParameters. + */ + public PolicyChangeResponse createPolicy(PolicyParameters policyParameters) throws PolicyException { + return createUpdatePolicyImpl(policyParameters, false); + } + + /* + * updatePolicy using policyParameters. + */ + public PolicyChangeResponse updatePolicy(PolicyParameters policyParameters) throws PolicyException { + return createUpdatePolicyImpl(policyParameters, true); + } + + public PolicyChangeResponse createUpdatePolicyImpl(PolicyParameters policyParameters, boolean updateFlag) + throws PolicyException { + StdPolicyChangeResponse response = new StdPolicyChangeResponse(); + String resource = "createPolicy"; + if (updateFlag) { + resource = "updatePolicy"; + } + String body = null; + // Create Request. try { body = PolicyUtils.objectToJsonString(policyParameters); } catch (JsonProcessingException e) { - String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; + String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; LOGGER.error(message); throw new PolicyException(message, e); } - // Get Response. + // Get Response. try { ResponseEntity<String> result = callNewPDP(resource, HttpMethod.PUT, body, String.class); // Process response @@ -506,30 +515,30 @@ public class StdPolicyEngine { return processException(exception); } return response; - } - - private PolicyChangeResponse processException(PolicyException exception) throws PolicyException { - StdPolicyChangeResponse response = new StdPolicyChangeResponse(); - if(exception.getCause()!=null && exception.getCause() instanceof HttpClientErrorException){ + } + + private PolicyChangeResponse processException(PolicyException exception) throws PolicyException { + StdPolicyChangeResponse response = new StdPolicyChangeResponse(); + if (exception.getCause() != null && exception.getCause() instanceof HttpClientErrorException) { LOGGER.error(exception); HttpClientErrorException ex = (HttpClientErrorException) exception.getCause(); response.setResponseCode(ex.getRawStatusCode()); response.setResponseMessage(exception.getMessage()); return response; - }else{ - String message = XACMLErrorConstants.ERROR_SYSTEM_ERROR+ "Error while processing results. please check logs."; + } else { + String message = XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "Error while processing results. please check logs."; LOGGER.error(message, exception); throw new PolicyException(message, exception); } } - public DecisionResponse getDecisionImpl(String onapName, - Map<String, String> decisionAttributes, - UUID requestID) throws PolicyDecisionException { - String resource= "getDecision"; - StdDecisionResponse response = new StdDecisionResponse(); - String body = new String(); - // Create Request. + public DecisionResponse getDecisionImpl(String onapName, Map<String, String> decisionAttributes, UUID requestID) + throws PolicyDecisionException { + String resource = "getDecision"; + StdDecisionResponse response = new StdDecisionResponse(); + String body = null; + // Create Request. try { DecisionRequestParameters decisionRequestParameters = new DecisionRequestParameters(); decisionRequestParameters.setDecisionAttributes(decisionAttributes); @@ -537,70 +546,77 @@ public class StdPolicyEngine { decisionRequestParameters.setRequestID(requestID); body = PolicyUtils.objectToJsonString(decisionRequestParameters); } catch (JsonProcessingException e) { - String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; + String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; LOGGER.error(message); throw new PolicyDecisionException(message, e); } - // Get Response. + // Get Response. try { - ResponseEntity<StdDecisionResponse> result = callNewPDP(resource, HttpMethod.POST, body, StdDecisionResponse.class); + ResponseEntity<StdDecisionResponse> result = callNewPDP(resource, HttpMethod.POST, body, + StdDecisionResponse.class); // Process response response = result.getBody(); } catch (Exception exception) { - if(exception.getCause().getMessage().contains("401")){ + if (exception.getCause().getMessage().contains("401")) { String message = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_AUTH_GET_PERM + resource; LOGGER.error(message); throw new PolicyDecisionException(message, exception); - }if(exception.getCause().getMessage().contains("400")){ + } + if (exception.getCause().getMessage().contains("400")) { String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Data is given."; LOGGER.error(message); throw new PolicyDecisionException(message, exception); } - String message = XACMLErrorConstants.ERROR_PERMISSIONS+ "Unable to get valid Response from PDP(s) " + pdps; + String message = XACMLErrorConstants.ERROR_PERMISSIONS + "Unable to get valid Response from PDP(s) " + + pdps; LOGGER.error(message, exception); throw new PolicyDecisionException(message, exception); } return response; - } - - public Collection<PolicyConfig> getConfigImpl(ConfigRequestParameters configRequestParameters) throws PolicyConfigException{ - String resource= "getConfig"; - ArrayList<PolicyConfig> response = new ArrayList<>(); - String body = new String(); - // Create Request. - try { + } + + public Collection<PolicyConfig> getConfigImpl(ConfigRequestParameters configRequestParameters) + throws PolicyConfigException { + String resource = "getConfig"; + ArrayList<PolicyConfig> response = new ArrayList<>(); + String body = null; + // Create Request. + try { body = PolicyUtils.objectToJsonString(configRequestParameters); } catch (JsonProcessingException e) { - String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; + String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; LOGGER.error(message); throw new PolicyConfigException(message, e); } - // Get Response. - try { - ResponseEntity<APIPolicyConfigResponse[]> result = callNewPDP(resource, HttpMethod.POST, body, APIPolicyConfigResponse[].class); + // Get Response. + try { + ResponseEntity<APIPolicyConfigResponse[]> result = callNewPDP(resource, HttpMethod.POST, body, + APIPolicyConfigResponse[].class); // Process Response response = configResult(result.getBody()); } catch (Exception exception) { - if(exception.getCause().getMessage().contains("401")){ + if (exception.getCause().getMessage().contains("401")) { String message = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_AUTH_GET_PERM + resource; LOGGER.error(message); throw new PolicyConfigException(message, exception); - }if(exception.getCause().getMessage().contains("400")){ + } + if (exception.getCause().getMessage().contains("400")) { String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Data is given."; LOGGER.error(message); throw new PolicyConfigException(message, exception); } - String message = XACMLErrorConstants.ERROR_PROCESS_FLOW+ "Unable to get valid Response from PDP(s) " + pdps; + String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Unable to get valid Response from PDP(s) " + + pdps; LOGGER.error(message, exception); throw new PolicyConfigException(message, exception); } - return response; - } - + return response; + } + private ArrayList<PolicyConfig> configResult(APIPolicyConfigResponse[] response) throws PolicyConfigException { ArrayList<PolicyConfig> result = new ArrayList<>(); - if(response!=null && response.length>0){ - for(APIPolicyConfigResponse policyConfigResponse: response){ + if (response != null && response.length > 0) { + for (APIPolicyConfigResponse policyConfigResponse : response) { StdPolicyConfig policyConfig = new StdPolicyConfig(); policyConfig.setConfigStatus(policyConfigResponse.getPolicyConfigMessage()); policyConfig.setMatchingConditions(policyConfigResponse.getMatchingConditions()); @@ -610,11 +626,12 @@ public class StdPolicyEngine { policyConfig.setPolicyVersion(policyConfigResponse.getPolicyVersion()); policyConfig.setResponseAttributes(policyConfigResponse.getResponseAttributes()); setMatches(policyConfig.getMatchingConditions()); - if(policyConfigResponse.getType()!=null){ + if (policyConfigResponse.getType() != null) { try { switch (policyConfigResponse.getType()) { case JSON: - JsonReader jsonReader = Json.createReader(new StringReader(policyConfigResponse.getConfig())); + JsonReader jsonReader = Json + .createReader(new StringReader(policyConfigResponse.getConfig())); JsonObject object = jsonReader.readObject(); jsonReader.close(); policyConfig.setJsonObject(object); @@ -631,12 +648,14 @@ public class StdPolicyEngine { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; builder = factory.newDocumentBuilder(); - policyConfig.setDocument(builder.parse(new InputSource(new StringReader(policyConfigResponse.getConfig())))); + policyConfig.setDocument(builder + .parse(new InputSource(new StringReader(policyConfigResponse.getConfig())))); break; } } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID+ e); - throw new PolicyConfigException(XACMLErrorConstants.ERROR_SCHEMA_INVALID+ "Unable to parse the config", e); + LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + e); + throw new PolicyConfigException( + XACMLErrorConstants.ERROR_SCHEMA_INVALID + "Unable to parse the config", e); } } result.add(policyConfig); @@ -648,72 +667,74 @@ public class StdPolicyEngine { private void setMatches(Map<String, String> matchingConditions) { Matches match = new Matches(); HashMap<String, String> configAttributes = new HashMap<>(); - try{ - for(String key: matchingConditions.keySet()){ - if(key.equalsIgnoreCase("ONAPName")){ + try { + for (String key : matchingConditions.keySet()) { + if (key.equalsIgnoreCase("ONAPName")) { match.setOnapName(matchingConditions.get(key)); - }else if(key.equalsIgnoreCase("ConfigName")){ + } else if (key.equalsIgnoreCase("ConfigName")) { match.setConfigName(matchingConditions.get(key)); - }else{ + } else { configAttributes.put(key, matchingConditions.get(key)); } } - if(!configAttributes.isEmpty()){ + if (!configAttributes.isEmpty()) { match.setConfigAttributes(configAttributes); } MatchStore.storeMatch(match); - }catch(Exception e){ - LOGGER.info("StoreMatch failed for Onap:" - + match.getOnapName() + " Config: " - + match.getConfigName()); + } catch (Exception e) { + LOGGER.error("StoreMatch failed for Onap:" + match.getOnapName() + " Config: " + match.getConfigName(), e); } } /* - * Generic Rest Client to call PDP services. + * Generic Rest Client to call PDP services. */ - private <T> ResponseEntity<T> callNewPDP(String resource, - HttpMethod method, Object body, Class<T> responseType) throws PolicyException{ + private <T> ResponseEntity<T> callNewPDP(String resource, HttpMethod method, Object body, Class<T> responseType) + throws PolicyException { RestTemplate restTemplate = new RestTemplate(); HttpEntity<?> requestEntity = new HttpEntity<>(body, getHeaders()); ResponseEntity<T> result = null; HttpClientErrorException exception = null; int pdpsCount = 0; - while(pdpsCount < pdps.size()){ - try{ - result = restTemplate.exchange(pdps.get(0)+"/api/" + resource, method, requestEntity, responseType); - }catch(HttpClientErrorException e){ + while (pdpsCount < pdps.size()) { + try { + result = restTemplate.exchange(pdps.get(0) + "/api/" + resource, method, requestEntity, responseType); + } catch (HttpClientErrorException e) { LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + pdps.get(0), e); exception = e; - }catch(Exception e){ + } catch (Exception e) { LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + pdps.get(0), e); exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage()); } - if(result == null){ - Collections.rotate(pdps, -1); - Collections.rotate(encoding, -1); - pdpsCount++; - }else{ - break; - } + if (result == null) { + Collections.rotate(pdps, -1); + Collections.rotate(encoding, -1); + pdpsCount++; + } else { + break; + } } - if(exception != null && exception.getStatusCode()!=null){ - if(exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)){ - String message = XACMLErrorConstants.ERROR_PERMISSIONS +":"+exception.getStatusCode()+":" +ERROR_AUTH_GET_PERM + resource; + if (exception != null && exception.getStatusCode() != null) { + if (exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)) { + String message = XACMLErrorConstants.ERROR_PERMISSIONS + ":" + exception.getStatusCode() + ":" + + ERROR_AUTH_GET_PERM + resource; LOGGER.error(message); throw new PolicyException(message, exception); } - if(exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)){ - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString(); + if (exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)) { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":" + exception.getStatusCode() + ":" + + exception.getResponseBodyAsString(); LOGGER.error(message); throw new PolicyException(message, exception); } - if(exception.getStatusCode().equals(HttpStatus.NOT_FOUND)){ - String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + pdps + exception; + if (exception.getStatusCode().equals(HttpStatus.NOT_FOUND)) { + String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + pdps + + exception; LOGGER.error(message); throw new PolicyException(message, exception); } - String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString(); + String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + exception.getStatusCode() + ":" + + exception.getResponseBodyAsString(); LOGGER.error(message); throw new PolicyException(message, exception); } @@ -724,9 +745,9 @@ public class StdPolicyEngine { HttpHeaders headers = new HttpHeaders(); headers.set("ClientAuth", "Basic " + clientEncoding); headers.set("Authorization", "Basic " + encoding.get(0)); - if(contentType!=null){ + if (contentType != null) { headers.set("Content-Type", contentType.toString()); - }else{ + } else { headers.set("Content-Type", MediaType.APPLICATION_JSON_VALUE); } headers.set("Environment", environment); @@ -735,520 +756,558 @@ public class StdPolicyEngine { private void setClientEncoding() { Base64.Encoder encoder = Base64.getEncoder(); - clientEncoding = encoder.encodeToString((userName+":"+pass).getBytes(StandardCharsets.UTF_8)); + clientEncoding = encoder.encodeToString((userName + ":" + pass).getBytes(StandardCharsets.UTF_8)); + } + + public Collection<String> listConfigImpl(ConfigRequestParameters listRequestParameters) + throws PolicyConfigException { + Collection<String> policyList = new ArrayList<>(); + if (junit) { + policyList.add("Policy Name: listConfigTest"); + return policyList; + } + Collection<PolicyConfig> policyConfig = getConfigImpl(listRequestParameters); + for (PolicyConfig policy : policyConfig) { + if (policy.getPolicyConfigMessage() != null && policy.getPolicyConfigMessage().contains("PE300")) { + policyList.add(policy.getPolicyConfigMessage()); + } else { + policyList.add("Policy Name: " + policy.getPolicyName()); + } + } + return policyList; } - public Collection<String> listConfigImpl(ConfigRequestParameters listRequestParameters) throws PolicyConfigException{ - Collection<String> policyList = new ArrayList<>(); - if (junit){ - policyList.add("Policy Name: listConfigTest"); - return policyList; - } - Collection<PolicyConfig> policyConfig = getConfigImpl(listRequestParameters); - for(PolicyConfig policy : policyConfig){ - if(policy.getPolicyConfigMessage()!=null && policy.getPolicyConfigMessage().contains("PE300")){ - policyList.add(policy.getPolicyConfigMessage()); - } else { - policyList.add("Policy Name: " + policy.getPolicyName()); - } - } - return policyList; - } - - public Collection<PolicyResponse> sendEventImpl(Map<String, String> eventAttributes, UUID requestID) throws PolicyEventException { - String resource= "sendEvent"; + public Collection<PolicyResponse> sendEventImpl(Map<String, String> eventAttributes, UUID requestID) + throws PolicyEventException { + String resource = "sendEvent"; ArrayList<PolicyResponse> response = new ArrayList<PolicyResponse>(); String body = new String(); - // Create Request. + // Create Request. try { - // Long way here, can be shortened and will be done. + // Long way here, can be shortened and will be done. EventRequestParameters eventRequestParameters = new EventRequestParameters(); eventRequestParameters.setEventAttributes(eventAttributes); eventRequestParameters.setRequestID(requestID); body = PolicyUtils.objectToJsonString(eventRequestParameters); } catch (JsonProcessingException e) { - String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; + String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e; LOGGER.error(message); throw new PolicyEventException(message, e); } - // Get Response. + // Get Response. try { - ResponseEntity<StdPolicyResponse[]> result = callNewPDP(resource, HttpMethod.POST, body, StdPolicyResponse[].class); + ResponseEntity<StdPolicyResponse[]> result = callNewPDP(resource, HttpMethod.POST, body, + StdPolicyResponse[].class); // Process Response response = eventResult(result.getBody()); } catch (Exception exception) { - if(exception.getCause().getMessage().contains("401")){ + if (exception.getCause().getMessage().contains("401")) { String message = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_AUTH_GET_PERM + resource; LOGGER.error(message); throw new PolicyEventException(message, exception); - }if(exception.getCause().getMessage().contains("400")){ + } + if (exception.getCause().getMessage().contains("400")) { String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Data is given."; LOGGER.error(message); throw new PolicyEventException(message, exception); } - String message = XACMLErrorConstants.ERROR_PERMISSIONS+ "Unable to get valid Response from PDP(s) " + pdps; + String message = XACMLErrorConstants.ERROR_PERMISSIONS + "Unable to get valid Response from PDP(s) " + + pdps; LOGGER.error(message, exception); throw new PolicyEventException(message, exception); } return response; - } + } - private ArrayList<PolicyResponse> eventResult(StdPolicyResponse[] response) throws PolicyEventException{ + private ArrayList<PolicyResponse> eventResult(StdPolicyResponse[] response) throws PolicyEventException { ArrayList<PolicyResponse> eventResult = new ArrayList<>(); - if(response!=null && response.length>0){ - for(StdPolicyResponse policyConfigResponse: response){ + if (response != null && response.length > 0) { + for (StdPolicyResponse policyConfigResponse : response) { eventResult.add(policyConfigResponse); } } return eventResult; } - private void setProperty(String propertyFilePath, String clientKey) - throws PolicyEngineException { - this.propertyFilePath = propertyFilePath; - if (this.propertyFilePath == null) { - throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error NO PropertyFile Path provided"); - } else { - // Adding logic for remote Properties file. - Properties prop = new Properties(); - if (propertyFilePath.startsWith("http")) { - URL configURL; - try { - configURL = new URL(propertyFilePath); - URLConnection connection = null; - connection = configURL.openConnection(); - prop.load(connection.getInputStream()); - } catch (IOException e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); - throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Maformed property URL "+ e.getMessage()); - } - } else { - Path file = Paths.get(propertyFilePath); - if (Files.notExists(file)) { - throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "File doesn't exist in the specified Path " + file.toString()); - } - if (file.toString().endsWith(".properties")) { - InputStream in; - prop = new Properties(); - try { - in = new FileInputStream(file.toFile()); - prop.load(in); - } catch (IOException e) { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); - throw new PolicyEngineException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Load the Properties file", e); - } - } else { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file " + propertyFilePath); - throw new PolicyEngineException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file"); - } - } - // UEB and DMAAP Settings - String check_type = prop.getProperty("NOTIFICATION_TYPE"); - String serverList = prop.getProperty("NOTIFICATION_SERVERS"); - topic = prop.getProperty("NOTIFICATION_TOPIC"); - apiKey = prop.getProperty("UEB_API_KEY"); - apiSecret = prop.getProperty("UEB_API_SECRET"); - - if(check_type==null) { - notificationType.add(DEFAULT_NOTIFICATION); - LOGGER.info("Properties file doesn't have the NOTIFICATION_TYPE parameter system will use defualt websockets"); - }else{ - check_type = check_type.trim(); - if(check_type.contains(",")) { - typeDefault = new ArrayList<String>(Arrays.asList(prop.getProperty("NOTIFICATION_TYPE").split(","))); - notificationType = typeDefault; - } else { - notificationType = new ArrayList<>(); - notificationType.add(check_type); - } - } - if(serverList==null) { - notificationType.clear(); - notificationType.add(DEFAULT_NOTIFICATION); - LOGGER.info("Properties file doesn't have the NOTIFICATION_SERVERS parameter system will use defualt websockets"); - }else{ - serverList = serverList.trim(); - if(serverList.contains(",")) { - notificationURLList = new ArrayList<String>(Arrays.asList(serverList.split(","))); - } else { - notificationURLList = new ArrayList<>(); - notificationURLList.add(serverList); - } - } - - if(topic!=null) { - topic = topic.trim(); - } else { - LOGGER.error("Properties file doesn't have the NOTIFICATION_TOPIC parameter."); - } - - // Client ID Authorization Settings. - String clientID = prop.getProperty("CLIENT_ID"); - if(clientKey==null){ - clientKey = prop.getProperty("CLIENT_KEY"); - try { - clientKey = PolicyUtils.decode(clientKey); - } catch (UnsupportedEncodingException|IllegalArgumentException e) { - LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS+" Cannot Decode the given Password Proceeding with given Password!!"); - } - } - if(clientID ==null || clientKey == null || clientID.isEmpty() || clientKey.isEmpty()){ - LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS+" Cannot proceed without the CLIENT_KEY and CLIENT_ID values !!"); - throw new PolicyEngineException(XACMLErrorConstants.ERROR_PERMISSIONS+ " Cannot proceed without the CLIENT_KEY and CLIENT_ID values !!"); - }else{ - userName = clientID.trim(); - pass = clientKey.trim(); - } - setClientEncoding(); - environment = prop.getProperty("ENVIRONMENT", AAFEnvironment.DEVL.toString()); - if(environment.equalsIgnoreCase(AAFEnvironment.TEST.toString())){ - environment = AAFEnvironment.TEST.toString(); - }else if(environment.equalsIgnoreCase(AAFEnvironment.PROD.toString())){ - environment = AAFEnvironment.PROD.toString(); - }else{ - environment = AAFEnvironment.DEVL.toString(); - } - // Initializing the values. - pdps = new ArrayList<>(); - encoding = new ArrayList<>(); - // Check the Keys for PDP_URLs - Collection<Object> unsorted = prop.keySet(); - @SuppressWarnings({ "rawtypes", "unchecked" }) - List<String> sorted = new ArrayList(unsorted); - Collections.sort(sorted); - for (String propKey : sorted) { - if (propKey.startsWith("PDP_URL")) { - String check_val = prop.getProperty(propKey); - if (check_val == null) { - throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Properties file doesn't have the PDP_URL parameter"); - } - if (check_val.contains(";")) { - pdpDefault = new ArrayList<String>(Arrays.asList(check_val.split("\\s*;\\s*"))); - int pdpCount = 0; - while (pdpCount < pdpDefault.size()) { - String pdpVal = pdpDefault.get(pdpCount); - readPDPParam(pdpVal); - pdpCount++; - } - } else { - readPDPParam(check_val); - } - } - } - if (pdps == null || pdps.isEmpty()) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot Proceed without PDP_URLs"); - throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot Proceed without PDP_URLs"); - } - - // Get JUNIT property from properties file when running tests - String junit = prop.getProperty("JUNIT"); - if(junit == null || junit.isEmpty()){ - LOGGER.info("No JUNIT property provided, this will not be executed as a test."); - }else{ - if(junit.equalsIgnoreCase("test")){ - StdPolicyEngine.junit = true; - } else { - StdPolicyEngine.junit = false; - } - } - } - } - - /* - * Read the PDP_URL parameter - */ - private void readPDPParam(String pdpVal) throws PolicyEngineException{ - if(pdpVal.contains(",")){ - List<String> pdpValues = new ArrayList<String>(Arrays.asList(pdpVal.split("\\s*,\\s*"))); - if(pdpValues.size()==3){ - // 0 - PDPURL - pdps.add(pdpValues.get(0)); - // 1:2 will be UserID:Password - String userID = pdpValues.get(1); - String pass = pdpValues.get(2); - Base64.Encoder encoder = Base64.getEncoder(); - encoding.add(encoder.encodeToString((userID+":"+pass).getBytes(StandardCharsets.UTF_8))); - }else{ - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Credentials to send Request: " + pdpValues); - throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "No enough Credentials to send Request. " + pdpValues); - } - }else{ - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP value is improper/missing required values: " + pdpVal); - throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP value is improper/missing required values."); - } - } - /* - * Allowing changes to the scheme and Handler. - */ - public void notification(NotificationScheme scheme, NotificationHandler handler) { - this.scheme = scheme; - this.handler = handler; - LOGGER.debug("Scheme is : " + scheme.toString()); - LOGGER.debug("Handler is : " + handler.getClass().getName()); - - if (notificationType.get(0).equals("ueb")){ - if (this.uebThread) { - uebClientThread.setAuto(scheme, handler); - this.uebThread = registerUEBThread.isAlive(); - } - } else if (notificationType.get(0).equals("dmaap")){ - if (this.dmaapThread) { - dmaapClientThread.setAuto(scheme, handler); - this.dmaapThread = registerDMAAPThread.isAlive(); - } - } else { - AutoClientEnd.setAuto(scheme, handler); - } - - if(junit){ - return; - } - - if(pdps!=null){ - if (notificationType.get(0).equals("ueb") && !this.uebThread){ - this.uebClientThread = new AutoClientUEB(pdps.get(0), notificationURLList, apiKey, apiSecret); - this.uebClientThread.setAuto(scheme, handler); - this.registerUEBThread = new Thread(this.uebClientThread); - this.registerUEBThread.start(); - this.uebThread = true; - }else if (notificationType.get(0).equals("dmaap") && !this.dmaapThread){ - this.dmaapClientThread = new AutoClientDMAAP(notificationURLList,topic,userName,pass); - this.dmaapClientThread.setAuto(scheme, handler); - this.registerDMAAPThread = new Thread(this.dmaapClientThread); - this.registerDMAAPThread.start(); - this.dmaapThread = true; - }else{ - if(pdps.get(0)!=null){ - if(AutoClientEnd.getURL()==null){ - AutoClientEnd.start(pdps.get(0)); - }else { - AutoClientEnd.stop(); - AutoClientEnd.start(pdps.get(0)); - } - } - } - } - } - - /* - * Gets the Notification if one exists. Used only for Manual Polling - * purposes. - */ - public PDPNotification getNotification(){ - //Check if there is proper scheme.. - PDPNotification notification = null; - if(this.scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS) || this.scheme.equals(NotificationScheme.MANUAL_NOTIFICATIONS)) { - if (notificationType.get(0).equals("ueb")){ - ManualClientEndUEB.start(pdps.get(0), notificationURLList, UNIQUEID); - notification = ManualClientEndUEB.result(scheme); - }else if (notificationType.get(0).equals("dmaap")){ - ManualClientEndDMAAP.start(notificationURLList, topic, UNIQUEID, userName, pass); - notification = ManualClientEndDMAAP.result(scheme); - }else{ - ManualClientEnd.start(pdps.get(0)); - LOGGER.debug("manual notification requested.. : " + scheme.toString()); - notification = ManualClientEnd.result(scheme); - } - if (notification == null){ - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Notification yet.."); - return null; - } else { - return notification; - } - }else { - return null; - } - } - - /* - * Setting the Scheme. - */ - public void setScheme(NotificationScheme scheme) { - this.scheme = scheme; - if (notificationType.get(0).equals("ueb")){ - AutoClientUEB.setScheme(this.scheme); - if (this.scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)){ - ManualClientEndUEB.createTopic(pdps.get(0), UNIQUEID, notificationURLList); - } - }else if (notificationType.get(0).equals("dmaap")){ - AutoClientDMAAP.setScheme(this.scheme); - if (this.scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)){ - ManualClientEndDMAAP.createTopic(topic, UNIQUEID, notificationURLList, userName, pass); - } - }else{ - AutoClientEnd.setScheme(this.scheme); - } - } - - /* - * Returns the Scheme - */ - public NotificationScheme getScheme() { - return this.scheme; - } - - /* - * Returns the NotificationHandler - */ - public NotificationHandler getNotificationHandler() { - return this.handler; - } - - /* - * Stop the Notification Service if its running. - */ - public void stopNotification() { - if (this.scheme != null && this.handler != null) { - if (this.scheme.equals(NotificationScheme.AUTO_ALL_NOTIFICATIONS) - || this.scheme - .equals(NotificationScheme.AUTO_NOTIFICATIONS)) { - LOGGER.info("Clear Notification called.. "); - if (notificationType.get(0).equals("ueb")){ - this.uebClientThread.terminate(); - this.uebThread = false; - }else if (notificationType.get(0).equals("dmaap")){ - this.dmaapClientThread.terminate(); - this.dmaapThread = false; - }else{ - AutoClientEnd.stop(); - } - } - } - } - - /* - * Push a policy to the PDP API implementation - */ - public String pushPolicy(String policyScope, String policyName, String policyType, String pdpGroup, UUID requestID) throws PolicyException { - PushPolicyParameters pushPolicyParameters = new PushPolicyParameters(); - if(policyScope==null|| policyScope.trim().isEmpty()){ - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given."; - LOGGER.error(message); - throw new PolicyException(message); - } - if(policyName==null|| policyName.trim().isEmpty()){ - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; - LOGGER.error(message); - throw new PolicyException(message); - } - pushPolicyParameters.setPolicyName(policyScope+"."+policyName); - pushPolicyParameters.setPolicyType(policyType); - pushPolicyParameters.setPdpGroup(pdpGroup); - pushPolicyParameters.setRequestID(requestID); - return pushPolicyImpl(pushPolicyParameters).getResponseMessage(); - } - - public String createUpdateConfigPolicy(String policyName, String policyDescription, String onapName, String configName, - Map<String, String> configAttributes, String configType, String body, String policyScope, UUID requestID, - String riskLevel, String riskType, String guard, String ttlDate, boolean updateFlag) throws PolicyException { - return createUpdateConfigPolicyImpl(policyName, policyDescription, onapName, configName, - configAttributes, configType, body, policyScope, requestID, - riskLevel, riskType, guard, ttlDate, updateFlag); - } - - /* - * Create Config Policy API Implementation - */ - public String createUpdateConfigPolicyImpl(String policyName, String policyDescription, String onapName, String configName, - Map<String, String> configAttributes, String configType, String body, String policyScope, UUID requestID, - String riskLevel, String riskType, String guard, String ttlDate, boolean updateFlag) throws PolicyException { - PolicyParameters policyParameters = new PolicyParameters(); - policyParameters.setPolicyClass(PolicyClass.Config); - policyParameters.setPolicyConfigType(PolicyConfigType.Base); - if(policyScope==null|| policyScope.trim().isEmpty()){ - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given."; - LOGGER.error(message); - throw new PolicyException(message); - } - if(policyName==null|| policyName.trim().isEmpty()){ - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; - LOGGER.error(message); - throw new PolicyException(message); - } - policyParameters.setPolicyName(policyScope+"."+policyName); - policyParameters.setPolicyDescription(policyDescription); - policyParameters.setOnapName(onapName); - policyParameters.setConfigName(configName); - Map<AttributeType, Map<String, String>> attributes = new HashMap<AttributeType, Map<String, String>>(); - attributes.put(AttributeType.MATCHING, configAttributes); - policyParameters.setAttributes(attributes); - policyParameters.setConfigBodyType(PolicyType.valueOf(configType)); - policyParameters.setConfigBody(body); - policyParameters.setRequestID(requestID); - policyParameters.setRiskLevel(riskLevel); - policyParameters.setRiskType(riskType); - policyParameters.setGuard(Boolean.parseBoolean(guard)); - try { - policyParameters.setTtlDate(new SimpleDateFormat("dd-MM-yyyy").parse(ttlDate)); - } catch (ParseException e) { - LOGGER.warn("Error Parsing date given " + ttlDate); - policyParameters.setTtlDate(null); - } - return createUpdatePolicyImpl(policyParameters, updateFlag).getResponseMessage(); - } - - public String createUpdateConfigFirewallPolicy(String policyName, JsonObject firewallJson, String policyScope, UUID requestID, - String riskLevel, String riskType, String guard, String ttlDate, boolean updateFlag) throws PolicyException { - return createUpdateConfigFirewallPolicyImpl(policyName, firewallJson, policyScope, requestID, - riskLevel, riskType, guard, ttlDate, updateFlag); - } - - /* - * Create Update Config Firewall Policy API implementation - */ - public String createUpdateConfigFirewallPolicyImpl(String policyName, JsonObject firewallJson, String policyScope, UUID requestID, - String riskLevel, String riskType, String guard, String ttlDate, boolean updateFlag) throws PolicyException { - PolicyParameters policyParameters = new PolicyParameters(); - policyParameters.setPolicyClass(PolicyClass.Config); - policyParameters.setPolicyConfigType(PolicyConfigType.Firewall); - if(policyScope==null|| policyScope.trim().isEmpty()){ - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given."; - LOGGER.error(message); - throw new PolicyException(message); - } - if(policyName==null|| policyName.trim().isEmpty()){ - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; - LOGGER.error(message); - throw new PolicyException(message); - } - policyParameters.setPolicyName(policyScope+"."+policyName); - policyParameters.setConfigBody(firewallJson.toString()); - policyParameters.setRequestID(requestID); - policyParameters.setRiskLevel(riskLevel); - policyParameters.setRiskType(riskType); - policyParameters.setGuard(Boolean.parseBoolean(guard)); - try { - policyParameters.setTtlDate(new SimpleDateFormat("dd-MM-yyyy").parse(ttlDate)); - } catch (NullPointerException | ParseException e) { - LOGGER.warn("Error Parsing date given " + ttlDate); - policyParameters.setTtlDate(null); - } - return createUpdatePolicyImpl(policyParameters, updateFlag).getResponseMessage(); - } - - public void setClientKey(String clientKey){ - if(clientKey!=null && !clientKey.isEmpty()){ - StdPolicyEngine.pass = clientKey; - setClientEncoding(); - } - } - /* - * Get the Environment. - */ - public static String getEnvironment() { - return environment; - } - /* - * Rotate the PDP list upon WEBsocket Failures - */ - public static void rotatePDPList() { - Collections.rotate(pdps, -1); - Collections.rotate(encoding, -1); - } - /* - * Get the latest PDP - */ - public static String getPDPURL() { - return pdps.get(0); - } + private void setProperty(String propertyFilePath, String clientKey) throws PolicyEngineException { + if (propertyFilePath == null) { + throw new PolicyEngineException( + XACMLErrorConstants.ERROR_DATA_ISSUE + "Error NO PropertyFile Path provided"); + } else { + // Adding logic for remote Properties file. + Properties prop = new Properties(); + if (propertyFilePath.startsWith("http")) { + URL configURL; + try { + configURL = new URL(propertyFilePath); + URLConnection connection = null; + connection = configURL.openConnection(); + prop.load(connection.getInputStream()); + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + throw new PolicyEngineException( + XACMLErrorConstants.ERROR_DATA_ISSUE + "Maformed property URL " + e.getMessage()); + } + } else { + Path file = Paths.get(propertyFilePath); + if (Files.notExists(file)) { + throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + + "File doesn't exist in the specified Path " + file.toString()); + } + if (file.toString().endsWith(".properties")) { + InputStream in; + prop = new Properties(); + try { + in = new FileInputStream(file.toFile()); + prop.load(in); + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + throw new PolicyEngineException( + XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Load the Properties file", e); + } + } else { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file " + propertyFilePath); + throw new PolicyEngineException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file"); + } + } + // UEB and DMAAP Settings + String checkType = prop.getProperty("NOTIFICATION_TYPE"); + String serverList = prop.getProperty("NOTIFICATION_SERVERS"); + topic = prop.getProperty("NOTIFICATION_TOPIC"); + apiKey = prop.getProperty("UEB_API_KEY"); + apiSecret = prop.getProperty("UEB_API_SECRET"); + + if (checkType == null) { + notificationType.add(DEFAULT_NOTIFICATION); + LOGGER.info( + "Properties file doesn't have the NOTIFICATION_TYPE parameter system will use defualt websockets"); + } else { + checkType = checkType.trim(); + if (checkType.contains(",")) { + typeDefault = new ArrayList<>(Arrays.asList(prop.getProperty("NOTIFICATION_TYPE").split(","))); + notificationType = typeDefault; + } else { + notificationType = new ArrayList<>(); + notificationType.add(checkType); + } + } + if (serverList == null) { + notificationType.clear(); + notificationType.add(DEFAULT_NOTIFICATION); + LOGGER.info( + "Properties file doesn't have the NOTIFICATION_SERVERS parameter system will use defualt websockets"); + } else { + serverList = serverList.trim(); + if (serverList.contains(",")) { + notificationURLList = new ArrayList<String>(Arrays.asList(serverList.split(","))); + } else { + notificationURLList = new ArrayList<>(); + notificationURLList.add(serverList); + } + } + + if (topic != null) { + topic = topic.trim(); + } else { + LOGGER.error("Properties file doesn't have the NOTIFICATION_TOPIC parameter."); + } + + // Client ID Authorization Settings. + String clientID = prop.getProperty("CLIENT_ID"); + if (clientKey == null) { + clientKey = prop.getProperty("CLIENT_KEY"); + try { + clientKey = PolicyUtils.decode(clientKey); + } catch (UnsupportedEncodingException | IllegalArgumentException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + + " Cannot Decode the given Password Proceeding with given Password!!", e); + } + } + if (clientID == null || clientKey == null || clientID.isEmpty() || clientKey.isEmpty()) { + LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + + " Cannot proceed without the CLIENT_KEY and CLIENT_ID values !!"); + throw new PolicyEngineException(XACMLErrorConstants.ERROR_PERMISSIONS + + " Cannot proceed without the CLIENT_KEY and CLIENT_ID values !!"); + } else { + setClientId(clientID.trim()); + setClientKey(clientKey.trim()); + } + setEnvironment(prop); + // Initializing the values. + init(); + // Check the Keys for PDP_URLs + Collection<Object> unsorted = prop.keySet(); + @SuppressWarnings({ "rawtypes", "unchecked" }) + List<String> sorted = new ArrayList(unsorted); + Collections.sort(sorted); + for (String propKey : sorted) { + if (propKey.startsWith("PDP_URL")) { + String checkVal = prop.getProperty(propKey); + if (checkVal == null) { + throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + + "Properties file doesn't have the PDP_URL parameter"); + } + if (checkVal.contains(";")) { + pdpDefault = new ArrayList<>(Arrays.asList(checkVal.split("\\s*;\\s*"))); + int pdpCount = 0; + while (pdpCount < pdpDefault.size()) { + String pdpVal = pdpDefault.get(pdpCount); + readPDPParam(pdpVal); + pdpCount++; + } + } else { + readPDPParam(checkVal); + } + } + } + if (pdps == null || pdps.isEmpty()) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot Proceed without PDP_URLs"); + throw new PolicyEngineException( + XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot Proceed without PDP_URLs"); + } + // Get JUNIT property from properties file when running tests + checkJunit(prop); + } + } + + private static void checkJunit(Properties prop) { + String junitFlag = prop.getProperty("JUNIT"); + if (junitFlag == null || junitFlag.isEmpty()) { + LOGGER.info("No JUNIT property provided, this will not be executed as a test."); + } else { + if (junitFlag.equalsIgnoreCase("test")) { + StdPolicyEngine.junit = true; + } else { + StdPolicyEngine.junit = false; + } + } + } + + private static void init() { + pdps = new ArrayList<>(); + encoding = new ArrayList<>(); + } + + private static void setEnvironment(Properties prop) { + environment = prop.getProperty("ENVIRONMENT", AAFEnvironment.DEVL.toString()); + if (environment.equalsIgnoreCase(AAFEnvironment.TEST.toString())) { + environment = AAFEnvironment.TEST.toString(); + } else if (environment.equalsIgnoreCase(AAFEnvironment.PROD.toString())) { + environment = AAFEnvironment.PROD.toString(); + } else { + environment = AAFEnvironment.DEVL.toString(); + } + } + + private static void setClientId(String clientID) { + userName = clientID; + } + + /* + * Read the PDP_URL parameter + */ + private void readPDPParam(String pdpVal) throws PolicyEngineException { + if (pdpVal.contains(",")) { + List<String> pdpValues = new ArrayList<String>(Arrays.asList(pdpVal.split("\\s*,\\s*"))); + if (pdpValues.size() == 3) { + // 0 - PDPURL + pdps.add(pdpValues.get(0)); + // 1:2 will be UserID:Password + String userID = pdpValues.get(1); + String pass = pdpValues.get(2); + Base64.Encoder encoder = Base64.getEncoder(); + encoding.add(encoder.encodeToString((userID + ":" + pass).getBytes(StandardCharsets.UTF_8))); + } else { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Credentials to send Request: " + pdpValues); + throw new PolicyEngineException( + XACMLErrorConstants.ERROR_DATA_ISSUE + "No enough Credentials to send Request. " + pdpValues); + } + } else { + LOGGER.error( + XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP value is improper/missing required values: " + pdpVal); + throw new PolicyEngineException( + XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP value is improper/missing required values."); + } + } + + /* + * Allowing changes to the scheme and Handler. + */ + public void notification(NotificationScheme scheme, NotificationHandler handler) { + this.scheme = scheme; + this.handler = handler; + LOGGER.debug("Scheme is : " + scheme.toString()); + LOGGER.debug("Handler is : " + handler.getClass().getName()); + + if (notificationType.get(0).equals("ueb")) { + if (this.uebThread) { + AutoClientUEB.setAuto(scheme, handler); + this.uebThread = registerUEBThread.isAlive(); + } + } else if (notificationType.get(0).equals("dmaap")) { + if (this.dmaapThread) { + AutoClientDMAAP.setAuto(scheme, handler); + this.dmaapThread = registerDMAAPThread.isAlive(); + } + } else { + AutoClientEnd.setAuto(scheme, handler); + } + + if (junit) { + return; + } + + if (pdps != null) { + if (notificationType.get(0).equals("ueb") && !this.uebThread) { + this.uebClientThread = new AutoClientUEB(pdps.get(0), notificationURLList, apiKey, apiSecret); + AutoClientUEB.setAuto(scheme, handler); + this.registerUEBThread = new Thread(this.uebClientThread); + this.registerUEBThread.start(); + this.uebThread = true; + } else if (notificationType.get(0).equals("dmaap") && !this.dmaapThread) { + this.dmaapClientThread = new AutoClientDMAAP(notificationURLList, topic, userName, pass); + AutoClientDMAAP.setAuto(scheme, handler); + this.registerDMAAPThread = new Thread(this.dmaapClientThread); + this.registerDMAAPThread.start(); + this.dmaapThread = true; + } else { + if (pdps.get(0) != null) { + if (AutoClientEnd.getURL() == null) { + AutoClientEnd.start(pdps.get(0)); + } else { + AutoClientEnd.stop(); + AutoClientEnd.start(pdps.get(0)); + } + } + } + } + } + + /* + * Gets the Notification if one exists. Used only for Manual Polling purposes. + */ + public PDPNotification getNotification() { + // Check if there is proper scheme.. + PDPNotification notification = null; + if (this.scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS) + || this.scheme.equals(NotificationScheme.MANUAL_NOTIFICATIONS)) { + if (notificationType.get(0).equals("ueb")) { + ManualClientEndUEB.start(pdps.get(0), notificationURLList, UNIQUEID); + notification = ManualClientEndUEB.result(scheme); + } else if (notificationType.get(0).equals("dmaap")) { + ManualClientEndDMAAP.start(notificationURLList, topic, UNIQUEID, userName, pass); + notification = ManualClientEndDMAAP.result(scheme); + } else { + ManualClientEnd.start(pdps.get(0)); + LOGGER.debug("manual notification requested.. : " + scheme.toString()); + notification = ManualClientEnd.result(scheme); + } + if (notification == null) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Notification yet.."); + return null; + } else { + return notification; + } + } else { + return null; + } + } + + /* + * Setting the Scheme. + */ + public void setScheme(NotificationScheme scheme) { + this.scheme = scheme; + if (notificationType.get(0).equals("ueb")) { + AutoClientUEB.setScheme(this.scheme); + if (this.scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)) { + ManualClientEndUEB.createTopic(pdps.get(0), UNIQUEID, notificationURLList); + } + } else if (notificationType.get(0).equals("dmaap")) { + AutoClientDMAAP.setScheme(this.scheme); + if (this.scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)) { + ManualClientEndDMAAP.createTopic(topic, UNIQUEID, notificationURLList, userName, pass); + } + } else { + AutoClientEnd.setScheme(this.scheme); + } + } + + /* + * Returns the Scheme + */ + public NotificationScheme getScheme() { + return this.scheme; + } + + /* + * Returns the NotificationHandler + */ + public NotificationHandler getNotificationHandler() { + return this.handler; + } + + /* + * Stop the Notification Service if its running. + */ + public void stopNotification() { + if (this.scheme != null && this.handler != null) { + if (this.scheme.equals(NotificationScheme.AUTO_ALL_NOTIFICATIONS) + || this.scheme.equals(NotificationScheme.AUTO_NOTIFICATIONS)) { + LOGGER.info("Clear Notification called.. "); + if (notificationType.get(0).equals("ueb")) { + this.uebClientThread.terminate(); + this.uebThread = false; + } else if (notificationType.get(0).equals("dmaap")) { + this.dmaapClientThread.terminate(); + this.dmaapThread = false; + } else { + AutoClientEnd.stop(); + } + } + } + } + + /* + * Push a policy to the PDP API implementation + */ + public String pushPolicy(String policyScope, String policyName, String policyType, String pdpGroup, UUID requestID) + throws PolicyException { + PushPolicyParameters pushPolicyParameters = new PushPolicyParameters(); + if (policyScope == null || policyScope.trim().isEmpty()) { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given."; + LOGGER.error(message); + throw new PolicyException(message); + } + if (policyName == null || policyName.trim().isEmpty()) { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; + LOGGER.error(message); + throw new PolicyException(message); + } + pushPolicyParameters.setPolicyName(policyScope + "." + policyName); + pushPolicyParameters.setPolicyType(policyType); + pushPolicyParameters.setPdpGroup(pdpGroup); + pushPolicyParameters.setRequestID(requestID); + return pushPolicyImpl(pushPolicyParameters).getResponseMessage(); + } + + public String createUpdateConfigPolicy(String policyName, String policyDescription, String onapName, + String configName, Map<String, String> configAttributes, String configType, String body, String policyScope, + UUID requestID, String riskLevel, String riskType, String guard, String ttlDate, boolean updateFlag) + throws PolicyException { + return createUpdateConfigPolicyImpl(policyName, policyDescription, onapName, configName, configAttributes, + configType, body, policyScope, requestID, riskLevel, riskType, guard, ttlDate, updateFlag); + } + + /* + * Create Config Policy API Implementation + */ + public String createUpdateConfigPolicyImpl(String policyName, String policyDescription, String onapName, + String configName, Map<String, String> configAttributes, String configType, String body, String policyScope, + UUID requestID, String riskLevel, String riskType, String guard, String ttlDate, boolean updateFlag) + throws PolicyException { + PolicyParameters policyParameters = new PolicyParameters(); + policyParameters.setPolicyClass(PolicyClass.Config); + policyParameters.setPolicyConfigType(PolicyConfigType.Base); + if (policyScope == null || policyScope.trim().isEmpty()) { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given."; + LOGGER.error(message); + throw new PolicyException(message); + } + if (policyName == null || policyName.trim().isEmpty()) { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; + LOGGER.error(message); + throw new PolicyException(message); + } + policyParameters.setPolicyName(policyScope + "." + policyName); + policyParameters.setPolicyDescription(policyDescription); + policyParameters.setOnapName(onapName); + policyParameters.setConfigName(configName); + Map<AttributeType, Map<String, String>> attributes = new HashMap<AttributeType, Map<String, String>>(); + attributes.put(AttributeType.MATCHING, configAttributes); + policyParameters.setAttributes(attributes); + policyParameters.setConfigBodyType(PolicyType.valueOf(configType)); + policyParameters.setConfigBody(body); + policyParameters.setRequestID(requestID); + policyParameters.setRiskLevel(riskLevel); + policyParameters.setRiskType(riskType); + policyParameters.setGuard(Boolean.parseBoolean(guard)); + try { + policyParameters.setTtlDate(new SimpleDateFormat("dd-MM-yyyy").parse(ttlDate)); + } catch (ParseException e) { + LOGGER.warn("Error Parsing date given " + ttlDate); + policyParameters.setTtlDate(null); + } + return createUpdatePolicyImpl(policyParameters, updateFlag).getResponseMessage(); + } + + public String createUpdateConfigFirewallPolicy(String policyName, JsonObject firewallJson, String policyScope, + UUID requestID, String riskLevel, String riskType, String guard, String ttlDate, boolean updateFlag) + throws PolicyException { + return createUpdateConfigFirewallPolicyImpl(policyName, firewallJson, policyScope, requestID, riskLevel, + riskType, guard, ttlDate, updateFlag); + } + + /* + * Create Update Config Firewall Policy API implementation + */ + public String createUpdateConfigFirewallPolicyImpl(String policyName, JsonObject firewallJson, String policyScope, + UUID requestID, String riskLevel, String riskType, String guard, String ttlDate, boolean updateFlag) + throws PolicyException { + PolicyParameters policyParameters = new PolicyParameters(); + policyParameters.setPolicyClass(PolicyClass.Config); + policyParameters.setPolicyConfigType(PolicyConfigType.Firewall); + if (policyScope == null || policyScope.trim().isEmpty()) { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given."; + LOGGER.error(message); + throw new PolicyException(message); + } + if (policyName == null || policyName.trim().isEmpty()) { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; + LOGGER.error(message); + throw new PolicyException(message); + } + policyParameters.setPolicyName(policyScope + "." + policyName); + policyParameters.setConfigBody(firewallJson.toString()); + policyParameters.setRequestID(requestID); + policyParameters.setRiskLevel(riskLevel); + policyParameters.setRiskType(riskType); + policyParameters.setGuard(Boolean.parseBoolean(guard)); + try { + policyParameters.setTtlDate(new SimpleDateFormat("dd-MM-yyyy").parse(ttlDate)); + } catch (NullPointerException | ParseException e) { + LOGGER.warn("Error Parsing date given " + ttlDate); + policyParameters.setTtlDate(null); + } + return createUpdatePolicyImpl(policyParameters, updateFlag).getResponseMessage(); + } + + public void setClientKey(String clientKey) { + if (clientKey != null && !clientKey.isEmpty()) { + StdPolicyEngine.pass = clientKey; + setClientEncoding(); + } + } + + /* + * Get the Environment. + */ + public static String getEnvironment() { + return environment; + } + + /* + * Rotate the PDP list upon WEBsocket Failures + */ + public static void rotatePDPList() { + Collections.rotate(pdps, -1); + Collections.rotate(encoding, -1); + } + + /* + * Get the latest PDP + */ + public static String getPDPURL() { + return pdps.get(0); + } }
\ No newline at end of file diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/AutoClientUEBTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/AutoClientUEBTest.java index 94c2ac781..eef76bdd7 100644 --- a/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/AutoClientUEBTest.java +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/AutoClientUEBTest.java @@ -120,369 +120,6 @@ public class AutoClientUEBTest { } /** - * Run the boolean isRunning() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testIsRunning_1() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList<String>(), "", ""); - fixture.isRunning = true; - - boolean result = fixture.isRunning(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB - assertTrue(result); - } - - /** - * Run the void run() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRun_1() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList<String>(), "", ""); - fixture.isRunning = true; - - fixture.run(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB - } - - /** - * Run the void run() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRun_2() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList<String>(), "", ""); - fixture.isRunning = true; - - fixture.run(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB - } - - /** - * Run the void run() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRun_3() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList<String>(), "", ""); - fixture.isRunning = true; - - fixture.run(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB - } - - /** - * Run the void run() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRun_4() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList<String>(), "", ""); - fixture.isRunning = true; - - fixture.run(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB - } - - /** - * Run the void run() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRun_5() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList<String>(),"",""); - fixture.isRunning = true; - - fixture.run(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB - } - - /** - * Run the void run() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRun_6() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList<String>(),"",""); - fixture.isRunning = true; - - fixture.run(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB - } - - /** - * Run the void run() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRun_7() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList<String>(),"",""); - fixture.isRunning = true; - - fixture.run(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB - } - - /** - * Run the void run() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRun_8() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList<String>(),"",""); - fixture.isRunning = true; - - fixture.run(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB - } - - /** - * Run the void run() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRun_9() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList<String>(),"",""); - fixture.isRunning = true; - - fixture.run(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB - } - - /** - * Run the void run() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRun_10() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList<String>(),"",""); - fixture.isRunning = true; - - fixture.run(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB - } - - /** - * Run the void run() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRun_11() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList<String>(),"",""); - fixture.isRunning = true; - - fixture.run(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB - } - - /** - * Run the void run() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRun_12() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList<String>(),"",""); - fixture.isRunning = true; - - fixture.run(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB - } - - /** - * Run the void run() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRun_13() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList<String>(),"",""); - fixture.isRunning = true; - - fixture.run(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB - } - - /** - * Run the void run() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRun_14() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList<String>(),"",""); - fixture.isRunning = true; - - fixture.run(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB - } - - /** - * Run the void run() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRun_15() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList<String>(),"",""); - fixture.isRunning = true; - - fixture.run(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB - } - - /** - * Run the void run() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRun_16() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList<String>(),"",""); - fixture.isRunning = true; - - fixture.run(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB - } - - /** - * Run the void setAuto(NotificationScheme,NotificationHandler) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetAuto_1() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList<String>(),"",""); - fixture.isRunning = true; - NotificationScheme scheme = NotificationScheme.AUTO_ALL_NOTIFICATIONS; - NotificationHandler handler = null; - - fixture.setAuto(scheme, handler); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB - } - - /** * Run the void setScheme(NotificationScheme) method test. * * @throws Exception @@ -502,26 +139,6 @@ public class AutoClientUEBTest { } /** - * Run the void terminate() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testTerminate_1() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList<String>(),"",""); - fixture.isRunning = true; - - fixture.terminate(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB - } - - /** * Perform pre-test initialization. * * @throws Exception @@ -535,9 +152,10 @@ public class AutoClientUEBTest { // add set up code here List<String> urlList = new LinkedList<String>(); urlList.add("test2.com"); - AutoClientUEB client = new AutoClientUEB("test.com", urlList, "testKey", "testSecret"); + @SuppressWarnings("unused") + AutoClientUEB client = new AutoClientUEB("test.com", urlList, "testKey", "testSecret"); NotificationHandler handler = null; - client.setAuto(NotificationScheme.AUTO_ALL_NOTIFICATIONS, handler); + AutoClientUEB.setAuto(NotificationScheme.AUTO_ALL_NOTIFICATIONS, handler); } /** diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/ActionPolicyApiTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/ActionPolicyApiTest.java index a66256432..ae971b405 100644 --- a/PolicyEngineAPI/src/test/java/org/onap/policy/test/ActionPolicyApiTest.java +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/ActionPolicyApiTest.java @@ -51,7 +51,7 @@ public class ActionPolicyApiTest extends TestCase { PolicyParameters policyParameters = new PolicyParameters(); @Before - protected void setUp() throws Exception { + public void setUp() throws Exception { try { policyEngine = new PolicyEngine("Test/config_pass.properties"); } catch (PolicyEngineException e) { @@ -80,7 +80,7 @@ public class ActionPolicyApiTest extends TestCase { policyParameters.setRequestID(UUID.randomUUID()); } - protected void tearDown() throws Exception { + public void tearDown() throws Exception { super.tearDown(); } diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/ConfigBasePolicyTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/ConfigBasePolicyTest.java index 5d5a076ae..b5fb75c42 100644 --- a/PolicyEngineAPI/src/test/java/org/onap/policy/test/ConfigBasePolicyTest.java +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/ConfigBasePolicyTest.java @@ -64,7 +64,7 @@ public class ConfigBasePolicyTest extends TestCase { * * @see TestCase#setUp() */ - protected void setUp() throws Exception { + public void setUp() throws Exception { try { policyEngine = new PolicyEngine("Test/config_pass.properties"); } catch (PolicyEngineException e) { @@ -102,7 +102,7 @@ public class ConfigBasePolicyTest extends TestCase { * * @see TestCase#tearDown() */ - protected void tearDown() throws Exception { + public void tearDown() throws Exception { super.tearDown(); // Add additional tear down code here } diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/ConfigFirewallPolicyTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/ConfigFirewallPolicyTest.java index 78ae2493b..c50b3de47 100644 --- a/PolicyEngineAPI/src/test/java/org/onap/policy/test/ConfigFirewallPolicyTest.java +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/ConfigFirewallPolicyTest.java @@ -59,7 +59,7 @@ public class ConfigFirewallPolicyTest extends TestCase { * * @see TestCase#setUp() */ - protected void setUp() throws Exception { + public void setUp() throws Exception { try { policyEngine = new PolicyEngine("Test/config_pass.properties"); } catch (PolicyEngineException e) { @@ -101,7 +101,7 @@ public class ConfigFirewallPolicyTest extends TestCase { * * @see TestCase#tearDown() */ - protected void tearDown() throws Exception { + public void tearDown() throws Exception { super.tearDown(); // Add additional tear down code here } diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/DecisionPolicyApiTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/DecisionPolicyApiTest.java index a80093470..7c9eb3e10 100644 --- a/PolicyEngineAPI/src/test/java/org/onap/policy/test/DecisionPolicyApiTest.java +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/DecisionPolicyApiTest.java @@ -63,7 +63,7 @@ public class DecisionPolicyApiTest extends TestCase { * * @see TestCase#setUp() */ - protected void setUp() throws Exception { + public void setUp() throws Exception { try { policyEngine = new PolicyEngine("Test/config_pass.properties"); } catch (PolicyEngineException e) { @@ -106,7 +106,7 @@ public class DecisionPolicyApiTest extends TestCase { * * @see TestCase#tearDown() */ - protected void tearDown() throws Exception { + public void tearDown() throws Exception { super.tearDown(); // Add additional tear down code here } diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyEngineInterfaceTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyEngineInterfaceTest.java index be9e0e7e8..2adf3b0bf 100644 --- a/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyEngineInterfaceTest.java +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyEngineInterfaceTest.java @@ -104,7 +104,7 @@ public class PolicyEngineInterfaceTest extends TestCase { * * @see TestCase#setUp() */ - protected void setUp() throws Exception { + public void setUp() throws Exception { try { policyEngine = new PolicyEngine("Test/config_pass.properties"); } catch (PolicyEngineException e) { @@ -126,7 +126,7 @@ public class PolicyEngineInterfaceTest extends TestCase { * * @see TestCase#tearDown() */ - protected void tearDown() throws Exception { + public void tearDown() throws Exception { super.tearDown(); // Add additional tear down code here } diff --git a/PolicyEngineClient/pom.xml b/PolicyEngineClient/pom.xml index 04be78565..8e0e5f4ec 100644 --- a/PolicyEngineClient/pom.xml +++ b/PolicyEngineClient/pom.xml @@ -40,9 +40,9 @@ <version>1.1</version> </dependency> <dependency> - <groupId>org.apache.httpcomponents</groupId> - <artifactId>httpclient</artifactId> - <version>4.5</version> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpclient</artifactId> + <version>4.5</version> </dependency> </dependencies> <build> diff --git a/PolicyEngineClient/src/main/java/org/onap/policyEngine/ActionPolicyClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/ActionPolicyClient.java index fa04668ca..94c6043c5 100644 --- a/PolicyEngineClient/src/main/java/org/onap/policyEngine/ActionPolicyClient.java +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/ActionPolicyClient.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.policyEngine; +package org.onap.policyengine; import java.util.Arrays; import java.util.HashMap; diff --git a/PolicyEngineClient/src/main/java/org/onap/policyEngine/BrmsParamPolicyClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/BrmsParamPolicyClient.java index 04cfdb84a..33ceedf7f 100644 --- a/PolicyEngineClient/src/main/java/org/onap/policyEngine/BrmsParamPolicyClient.java +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/BrmsParamPolicyClient.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.policyEngine; +package org.onap.policyengine; import java.text.SimpleDateFormat; import java.util.Date; diff --git a/PolicyEngineClient/src/main/java/org/onap/policyEngine/BrmsRawPolicyClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/BrmsRawPolicyClient.java index bf8fea59f..18d404dc2 100644 --- a/PolicyEngineClient/src/main/java/org/onap/policyEngine/BrmsRawPolicyClient.java +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/BrmsRawPolicyClient.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.policyEngine; +package org.onap.policyengine; import java.io.BufferedReader; import java.io.File; diff --git a/PolicyEngineClient/src/main/java/org/onap/policyEngine/ClosedLoopPolicyClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/ClosedLoopPolicyClient.java index 2240f0b73..29a0f4363 100644 --- a/PolicyEngineClient/src/main/java/org/onap/policyEngine/ClosedLoopPolicyClient.java +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/ClosedLoopPolicyClient.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.policyEngine; +package org.onap.policyengine; import java.io.File; import java.io.FileInputStream; diff --git a/PolicyEngineClient/src/main/java/org/onap/policyEngine/ClosedLoopPolicyPerformanceMetricClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/ClosedLoopPolicyPerformanceMetricClient.java index e3b5fde60..eaee2a325 100644 --- a/PolicyEngineClient/src/main/java/org/onap/policyEngine/ClosedLoopPolicyPerformanceMetricClient.java +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/ClosedLoopPolicyPerformanceMetricClient.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.policyEngine; +package org.onap.policyengine; import java.io.File; import java.io.FileInputStream; diff --git a/PolicyEngineClient/src/main/java/org/onap/policyEngine/ConfigBasePolicyClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/ConfigBasePolicyClient.java index 20a5bd359..b8dfdc1f6 100644 --- a/PolicyEngineClient/src/main/java/org/onap/policyEngine/ConfigBasePolicyClient.java +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/ConfigBasePolicyClient.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.policyEngine; +package org.onap.policyengine; import java.text.SimpleDateFormat; import java.util.Date; diff --git a/PolicyEngineClient/src/main/java/org/onap/policyEngine/ConfigFirewallPolicyClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/ConfigFirewallPolicyClient.java index a261761f5..37ec9fabd 100644 --- a/PolicyEngineClient/src/main/java/org/onap/policyEngine/ConfigFirewallPolicyClient.java +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/ConfigFirewallPolicyClient.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.policyEngine; +package org.onap.policyengine; import java.io.File; import java.io.FileInputStream; diff --git a/PolicyEngineClient/src/main/java/org/onap/policyEngine/DecisionPolicyClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/DecisionPolicyClient.java index 8c16e0e40..2ef2d3b1a 100644 --- a/PolicyEngineClient/src/main/java/org/onap/policyEngine/DecisionPolicyClient.java +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/DecisionPolicyClient.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.policyEngine; +package org.onap.policyengine; import java.util.Arrays; import java.util.HashMap; diff --git a/PolicyEngineClient/src/main/java/org/onap/policyEngine/DeletePolicyClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/DeletePolicyClient.java index ec4959550..c66067942 100644 --- a/PolicyEngineClient/src/main/java/org/onap/policyEngine/DeletePolicyClient.java +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/DeletePolicyClient.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.policyEngine; +package org.onap.policyengine; import org.onap.policy.api.DeletePolicyCondition; import org.onap.policy.api.DeletePolicyParameters; diff --git a/PolicyEngineClient/src/main/java/org/onap/policyEngine/GeneralTestClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/GeneralTestClient.java index 423ade2c2..e81939be6 100644 --- a/PolicyEngineClient/src/main/java/org/onap/policyEngine/GeneralTestClient.java +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/GeneralTestClient.java @@ -28,7 +28,7 @@ * Unpublished and Not for Publication * All Rights Reserved */ -package org.onap.policyEngine; +package org.onap.policyengine; import java.io.FileNotFoundException; import java.io.FileReader; diff --git a/PolicyEngineClient/src/main/java/org/onap/policyEngine/GetConfigSample.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/GetConfigSample.java index 59225ce6f..94cc69fd7 100644 --- a/PolicyEngineClient/src/main/java/org/onap/policyEngine/GetConfigSample.java +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/GetConfigSample.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.policyEngine; +package org.onap.policyengine; import java.util.Collection; diff --git a/PolicyEngineClient/src/main/java/org/onap/policyEngine/Handler.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/Handler.java index 4a78db615..12fca6e93 100644 --- a/PolicyEngineClient/src/main/java/org/onap/policyEngine/Handler.java +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/Handler.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.policyEngine; +package org.onap.policyengine; import java.util.Collection; diff --git a/PolicyEngineClient/src/main/java/org/onap/policyEngine/ImportBRMSTemplate.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/ImportBRMSTemplate.java index 053c524b6..ef9ec3136 100644 --- a/PolicyEngineClient/src/main/java/org/onap/policyEngine/ImportBRMSTemplate.java +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/ImportBRMSTemplate.java @@ -1,4 +1,4 @@ -package org.onap.policyEngine; +package org.onap.policyengine; import java.io.File; import java.util.UUID; diff --git a/PolicyEngineClient/src/main/java/org/onap/policyEngine/ImportMicroServiceClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/ImportMicroServiceClient.java index 671eb6c80..86439583a 100644 --- a/PolicyEngineClient/src/main/java/org/onap/policyEngine/ImportMicroServiceClient.java +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/ImportMicroServiceClient.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.policyEngine; +package org.onap.policyengine; import java.util.UUID; diff --git a/PolicyEngineClient/src/main/java/org/onap/policyEngine/ListConfigPoliciesClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/ListConfigPoliciesClient.java index dd5c97ba1..9973ce70c 100644 --- a/PolicyEngineClient/src/main/java/org/onap/policyEngine/ListConfigPoliciesClient.java +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/ListConfigPoliciesClient.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.policyEngine; +package org.onap.policyengine; import java.util.Collection; import java.util.HashMap; diff --git a/PolicyEngineClient/src/main/java/org/onap/policyEngine/MainClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/MainClient.java index 0be702c13..210499ca1 100644 --- a/PolicyEngineClient/src/main/java/org/onap/policyEngine/MainClient.java +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/MainClient.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.policyEngine; +package org.onap.policyengine; import java.io.IOException; import java.io.OutputStream; diff --git a/PolicyEngineClient/src/main/java/org/onap/policyEngine/MicroServicesPolicyClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/MicroServicesPolicyClient.java index 99f9551cb..b05e44726 100644 --- a/PolicyEngineClient/src/main/java/org/onap/policyEngine/MicroServicesPolicyClient.java +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/MicroServicesPolicyClient.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.policyEngine; +package org.onap.policyengine; import java.io.File; import java.io.FileInputStream; diff --git a/PolicyEngineClient/src/main/java/org/onap/policyEngine/PolicyEngineTestClient.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/PolicyEngineTestClient.java index 4f782c8c9..39346eaea 100644 --- a/PolicyEngineClient/src/main/java/org/onap/policyEngine/PolicyEngineTestClient.java +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/PolicyEngineTestClient.java @@ -28,7 +28,7 @@ * Unpublished and Not for Publication * All Rights Reserved */ -package org.onap.policyEngine; +package org.onap.policyengine; import java.io.IOException; import java.util.ArrayList; diff --git a/PolicyEngineClient/src/main/java/org/onap/policyEngine/PushPoliciesToPDP.java b/PolicyEngineClient/src/test/java/org/onap/policyengine/PushPoliciesToPDP.java index 05d736464..880af0610 100644 --- a/PolicyEngineClient/src/main/java/org/onap/policyEngine/PushPoliciesToPDP.java +++ b/PolicyEngineClient/src/test/java/org/onap/policyengine/PushPoliciesToPDP.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.policyEngine; +package org.onap.policyengine; import org.onap.policy.api.PolicyChangeResponse; import org.onap.policy.api.PolicyEngine; 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 6fff797a6..d4f111637 100644 --- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpMonitor.java +++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpMonitor.java @@ -40,6 +40,7 @@ import org.onap.policy.jpa.BackUpMonitorEntity; import org.onap.policy.std.NotificationStore; import org.onap.policy.std.StdPDPNotification; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.github.fge.jackson.JsonLoader; import com.github.fge.jsonpatch.JsonPatch; @@ -47,376 +48,404 @@ 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. + * 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 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; + 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 - } + /* + * 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(); + 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; + // 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 BackUpMonitorException("Unable to create Entity Manger Factory"); + } + em = emf.createEntityManager(); - // Check Database if this is Master or Slave. - checkDataBase(); + // Check Database if this is Master or Slave. + checkDataBase(); - // Start thread. - Thread t = new Thread(new BMonitor()); - t.start(); - } + // 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; - } + /** + * 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 BackUpMonitorException { + 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; - } + // 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; - } - } + // 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; - } - } + /** + * 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()); - } - } - } - } + // 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(), e); + } + } + } + } - // Set Master - private static BackUpMonitorEntity setMaster(BackUpMonitorEntity bMEntity){ - bMEntity.setFlag("MASTER"); - setFlag(true); - return bMEntity; - } + // 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; - } + // 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); - } - } + // 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(); + 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.isEmpty()) { + // 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(), e); + if (et.isActive()) { + et.rollback(); + } + throw new BackUpMonitorException(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; - } - } + private static void setNotificationRecord() throws BackUpMonitorException { + try { + notificationRecord = PolicyUtils.objectToJsonString(NotificationStore.getNotificationRecord()); + } catch (JsonProcessingException e1) { + LOGGER.error("Error retrieving notification record failed. ", e1); + throw new BackUpMonitorException(e1); + } + } - /** - * 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(); - } + // 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(), e); + return null; + } + } catch (IOException e) { + LOGGER.error("Error generating Patched " + e.getMessage(), e); + return null; + } + } - // 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()); - } - } - } + /** + * 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 BackUpMonitorException { + checkDataBase(); + } - // 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); - } - } - } + // 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(), e); + } + } + } catch (IOException e) { + LOGGER.info("Error while notification Conversion " + e.getMessage(), e); + } + } + } + + // 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/onap/policy/utils/BackUpMonitorException.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpMonitorException.java new file mode 100644 index 000000000..b12e780a0 --- /dev/null +++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpMonitorException.java @@ -0,0 +1,44 @@ +/*- + * ============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; + +public class BackUpMonitorException extends Exception{ + private static final long serialVersionUID = 6778134503685443473L; + + public BackUpMonitorException() { + } + + public BackUpMonitorException(String message) { + super(message); + } + + public BackUpMonitorException(Throwable cause){ + super(cause); + } + + public BackUpMonitorException(String message, Throwable cause) { + super(message, cause); + } + + public BackUpMonitorException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} 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 bf92835c6..1b31394d0 100644 --- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusConsumer.java +++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusConsumer.java @@ -1,8 +1,30 @@ +/*- + * ============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 java.net.MalformedURLException; import java.util.List; import java.util.Properties; +import com.att.nsa.mr.client.MRClient.MRApiException; import com.att.nsa.mr.client.impl.MRConsumerImpl; import com.att.nsa.mr.test.clients.ProtocolTypeConstants; @@ -12,9 +34,9 @@ public interface BusConsumer { * fetch messages * * @return list of messages - * @throws Exception when error encountered by underlying libraries + * @throws MRApiException when error encountered by underlying libraries */ - public Iterable<String> fetch() throws Exception; + public Iterable<String> fetch() throws MRApiException; /** * close underlying library consumer @@ -48,8 +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 Exception { + int fetchTimeout, int fetchLimit) throws MalformedURLException{ this.consumer = new MRConsumerImpl(servers, topic, consumerGroup, consumerInstance, @@ -70,8 +91,12 @@ public interface BusConsumer { /** * {@inheritDoc} */ - public Iterable<String> fetch() throws Exception { - return this.consumer.fetch(); + public Iterable<String> fetch() throws MRApiException { + try { + return this.consumer.fetch(); + } catch (Exception e) { + throw new MRApiException("Error during MR consumer Fetch ",e); + } } /** 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 792c389ab..3190aa035 100644 --- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusPublisher.java +++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusPublisher.java @@ -1,3 +1,23 @@ +/*- + * ============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 java.util.ArrayList; @@ -6,6 +26,8 @@ import java.util.Properties; import java.util.concurrent.TimeUnit; import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; import com.att.nsa.mr.client.impl.MRSimplerBatchPublisher; import com.att.nsa.mr.test.clients.ProtocolTypeConstants; @@ -31,6 +53,7 @@ public interface BusPublisher { * DmaapClient library wrapper */ public static class DmaapPublisherWrapper implements BusPublisher { + private static Logger logger = FlexLogger.getLogger(DmaapPublisherWrapper.class); /** * MR based Publisher */ @@ -74,16 +97,16 @@ public interface BusPublisher { */ @Override public void close() { - if (PolicyLogger.isInfoEnabled()) - PolicyLogger.info(DmaapPublisherWrapper.class.getName(), + if (logger.isInfoEnabled()) + logger.info(DmaapPublisherWrapper.class.getName()+ "CREATION: " + this); try { this.publisher.close(1, TimeUnit.SECONDS); } catch (Exception e) { - PolicyLogger.warn(DmaapPublisherWrapper.class.getName(), + logger.warn(DmaapPublisherWrapper.class.getName()+ "CLOSE: " + this + " because of " + - e.getMessage()); + e.getMessage(), e); } } 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 82340c13c..8bc83dcb8 100644 --- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PolicyUtils.java +++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PolicyUtils.java @@ -70,7 +70,7 @@ public class PolicyUtils { } } - public static String[] decodeBasicEncoding(String encodedValue) throws Exception{ + public static String[] decodeBasicEncoding(String encodedValue) throws UnsupportedEncodingException { if(encodedValue!=null && encodedValue.contains("Basic ")){ String encodedUserPassword = encodedValue.replaceFirst("Basic" + " ", ""); String usernameAndPassword = null; @@ -25,13 +25,6 @@ <project.target.version>1.8</project.target.version> <project.encoding>UTF-8</project.encoding> - <sonar.language>java</sonar.language> - <sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin> - <sonar.surefire.reportsPath>${project.build.directory}/surefire-reports</sonar.surefire.reportsPath> - <sonar.jacoco.reportPath>${project.build.directory}/coverage-reports/jacoco.exec</sonar.jacoco.reportPath> - <sonar.jacoco.itReportPath>/opt/app/policy/it-results/jacoco-it.exec</sonar.jacoco.itReportPath> - <sonar.jacoco.reportMissing.force.zero>true</sonar.jacoco.reportMissing.force.zero> - <sonar.projectVersion>${project.version}</sonar.projectVersion> <common-modules.version>1.1.0-SNAPSHOT</common-modules.version> <nexusproxy>https://nexus.onap.org</nexusproxy> <sitePath>/content/sites/site/${project.groupId}/${project.artifactId}/${project.version}</sitePath> @@ -184,28 +177,6 @@ <version>4.20</version> </plugin> <plugin> - <groupId>org.jacoco</groupId> - <artifactId>jacoco-maven-plugin</artifactId> - <version>0.7.6.201602180812</version> - <configuration> - <dumpOnExit>true</dumpOnExit> - <includes> - <include>org.onap.*</include> - </includes> - </configuration> - <executions> - <execution> - <id>jacoco-initialize-unit-tests</id> - <goals> - <goal>prepare-agent</goal> - </goals> - <configuration> - <destFile>${project.build.directory}/coverage-reports/jacoco.exec</destFile> - </configuration> - </execution> - </executions> - </plugin> - <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-site-plugin</artifactId> <version>3.6</version> |