From d4b467daed74656582045f4561e6c7745cf7bf6f Mon Sep 17 00:00:00 2001 From: "waqas.ikram" Date: Wed, 28 Mar 2018 12:56:15 +0100 Subject: Removed checkstyle warnings Change-Id: I0701333d2b36a0796b592ce92b8015c1a56f8258 Issue-ID: POLICY-711 Signed-off-by: waqas.ikram --- BRMSGateway/pom.xml | 292 ++--- .../java/org/onap/policy/brms/api/BrmsGateway.java | 86 ++ .../java/org/onap/policy/brms/api/BrmsHandler.java | 200 ++++ .../java/org/onap/policy/brms/api/BrmsPush.java | 1207 ++++++++++++++++++++ .../org/onap/policy/brms/api/ControllerPojo.java | 57 + .../org/onap/policy/brms/api/NotificationPojo.java | 58 + .../org/onap/policy/brms/entity/BrmsGroupInfo.java | 76 ++ .../onap/policy/brms/entity/BrmsPolicyInfo.java | 57 + .../onap/policy/brms/entity/DependencyInfo.java | 40 + .../org/onap/policy/brmsInterface/BRMSGateway.java | 85 -- .../org/onap/policy/brmsInterface/BRMSHandler.java | 189 --- .../org/onap/policy/brmsInterface/BRMSPush.java | 1183 ------------------- .../onap/policy/brmsInterface/ControllerPOJO.java | 52 - .../policy/brmsInterface/NotificationPOJO.java | 52 - .../policy/brmsInterface/jpa/BRMSGroupInfo.java | 75 -- .../policy/brmsInterface/jpa/BRMSPolicyInfo.java | 56 - .../policy/brmsInterface/jpa/DependencyInfo.java | 38 - .../main/resources/META-INF/persistenceBRMS.xml | 16 +- .../java/org/onap/brmsgw/test/BRMSJpaTest.java | 71 -- .../java/org/onap/brmsgw/test/BRMSPushTest.java | 234 ---- .../java/org/onap/brmsgw/test/BrmsJpaTest.java | 73 ++ .../java/org/onap/brmsgw/test/BrmsPushTest.java | 235 ++++ .../org/onap/brmsgw/test/ControllerPOJOTest.java | 45 - .../org/onap/brmsgw/test/ControllerPojoTest.java | 47 + .../org/onap/brmsgw/test/NotificationPOJOTest.java | 46 - .../org/onap/brmsgw/test/NotificationPojoTest.java | 48 + .../org/onap/policy/brms/api/BrmsGatewayTest.java | 61 + .../org/onap/policy/brms/api/BrmsHandlerTest.java | 94 ++ .../org/onap/policy/brms/api/BrmsPushTest.java | 125 ++ .../onap/policy/brmsInterface/BRMSGatewayTest.java | 61 - .../onap/policy/brmsInterface/BRMSHandlerTest.java | 93 -- .../onap/policy/brmsInterface/BRMSPushTest.java | 125 -- .../resources/META-INF/persistenceBRMStest.xml | 4 +- 33 files changed, 2636 insertions(+), 2545 deletions(-) create mode 100644 BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsGateway.java create mode 100644 BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsHandler.java create mode 100644 BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsPush.java create mode 100644 BRMSGateway/src/main/java/org/onap/policy/brms/api/ControllerPojo.java create mode 100644 BRMSGateway/src/main/java/org/onap/policy/brms/api/NotificationPojo.java create mode 100644 BRMSGateway/src/main/java/org/onap/policy/brms/entity/BrmsGroupInfo.java create mode 100644 BRMSGateway/src/main/java/org/onap/policy/brms/entity/BrmsPolicyInfo.java create mode 100644 BRMSGateway/src/main/java/org/onap/policy/brms/entity/DependencyInfo.java delete mode 100644 BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSGateway.java delete mode 100644 BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSHandler.java delete mode 100644 BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSPush.java delete mode 100644 BRMSGateway/src/main/java/org/onap/policy/brmsInterface/ControllerPOJO.java delete mode 100644 BRMSGateway/src/main/java/org/onap/policy/brmsInterface/NotificationPOJO.java delete mode 100644 BRMSGateway/src/main/java/org/onap/policy/brmsInterface/jpa/BRMSGroupInfo.java delete mode 100644 BRMSGateway/src/main/java/org/onap/policy/brmsInterface/jpa/BRMSPolicyInfo.java delete mode 100644 BRMSGateway/src/main/java/org/onap/policy/brmsInterface/jpa/DependencyInfo.java delete mode 100644 BRMSGateway/src/test/java/org/onap/brmsgw/test/BRMSJpaTest.java delete mode 100644 BRMSGateway/src/test/java/org/onap/brmsgw/test/BRMSPushTest.java create mode 100644 BRMSGateway/src/test/java/org/onap/brmsgw/test/BrmsJpaTest.java create mode 100644 BRMSGateway/src/test/java/org/onap/brmsgw/test/BrmsPushTest.java delete mode 100644 BRMSGateway/src/test/java/org/onap/brmsgw/test/ControllerPOJOTest.java create mode 100644 BRMSGateway/src/test/java/org/onap/brmsgw/test/ControllerPojoTest.java delete mode 100644 BRMSGateway/src/test/java/org/onap/brmsgw/test/NotificationPOJOTest.java create mode 100644 BRMSGateway/src/test/java/org/onap/brmsgw/test/NotificationPojoTest.java create mode 100644 BRMSGateway/src/test/java/org/onap/policy/brms/api/BrmsGatewayTest.java create mode 100644 BRMSGateway/src/test/java/org/onap/policy/brms/api/BrmsHandlerTest.java create mode 100644 BRMSGateway/src/test/java/org/onap/policy/brms/api/BrmsPushTest.java delete mode 100644 BRMSGateway/src/test/java/org/onap/policy/brmsInterface/BRMSGatewayTest.java delete mode 100644 BRMSGateway/src/test/java/org/onap/policy/brmsInterface/BRMSHandlerTest.java delete mode 100644 BRMSGateway/src/test/java/org/onap/policy/brmsInterface/BRMSPushTest.java diff --git a/BRMSGateway/pom.xml b/BRMSGateway/pom.xml index 2f4612aba..9be5c30c7 100644 --- a/BRMSGateway/pom.xml +++ b/BRMSGateway/pom.xml @@ -19,134 +19,166 @@ --> - 4.0.0 - - org.onap.policy.engine - PolicyEngineSuite - 1.2.0-SNAPSHOT - - BRMSGateway - This application will take in BRMS rules and acts as interface between PR and PDP XACML - - - com.h2database - h2 - test - - - org.onap.policy.engine - PolicyEngineAPI - ${project.version} - - - com.att.nsa - cambriaClient - - - - - org.apache.maven - maven-model - 3.5.3 - - - org.apache.maven.shared - maven-invoker - 3.0.0 - - - org.onap.policy.common - integrity-monitor - ${project.version} - - - - commons-collections - commons-collections - 3.2.2 - - - org.sonatype.nexus - nexus-rest-client-java - 2.3.1-01 - - - commons-collections - commons-collections - - - - - com.thoughtworks.xstream - xstream - 1.4.10 - - - com.att.nsa - cambriaClient - 0.0.1 - - - org.slf4j - slf4j-log4j12 - - - - - org.onap.dmaap.messagerouter.dmaapclient - dmaapClient - ${dmaap.version} - - - org.slf4j - slf4j-log4j12 - - - com.att.aft - dme2 - - - - - org.apache.httpcomponents - httpclient - ${httpclient.version} - - - - - - - org.apache.maven.plugins - maven-assembly-plugin - 2.2 - - - - true - lib/ - org.onap.policy.brmsInterface.BRMSGateway - - - - jar-with-dependencies - - - - - make-assembly - package - - single - - - - - - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + + org.onap.policy.engine + PolicyEngineSuite + 1.2.0-SNAPSHOT + + BRMSGateway + This application will take in BRMS rules and acts as interface between PR and PDP XACML + + + com.h2database + h2 + test + + + org.onap.policy.engine + PolicyEngineAPI + ${project.version} + + + com.att.nsa + cambriaClient + + + + + org.apache.maven + maven-model + 3.5.3 + + + org.apache.maven.shared + maven-invoker + 3.0.0 + + + org.onap.policy.common + integrity-monitor + ${project.version} + + + + commons-collections + commons-collections + 3.2.2 + + + org.sonatype.nexus + nexus-rest-client-java + 2.3.1-01 + + + commons-collections + commons-collections + + + + + com.thoughtworks.xstream + xstream + 1.4.10 + + + com.att.nsa + cambriaClient + 0.0.1 + + + org.slf4j + slf4j-log4j12 + + + + + org.onap.dmaap.messagerouter.dmaapclient + dmaapClient + ${dmaap.version} + + + org.slf4j + slf4j-log4j12 + + + com.att.aft + dme2 + + + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + + + + + + maven-checkstyle-plugin + + + onap-java-style + + check + + process-sources + + + onap-checkstyle/onap-java-style.xml + + ${project.build.sourceDirectory} + true + true + true + true + true + warning + + + + + + org.onap.oparent + checkstyle + 0.1.1 + compile + + + + + + org.apache.maven.plugins + maven-assembly-plugin + 2.2 + + + + true + lib/ + org.onap.policy.brmsInterface.BRMSGateway + + + + jar-with-dependencies + + + + + make-assembly + package + + single + + + + + + diff --git a/BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsGateway.java b/BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsGateway.java new file mode 100644 index 000000000..d12178319 --- /dev/null +++ b/BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsGateway.java @@ -0,0 +1,86 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * 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.brms.api; + +import org.onap.policy.api.NotificationScheme; +import org.onap.policy.api.PolicyEngine; +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. + * + * @version 0.1 + */ +class BrmsGateway { + + private static final Logger logger = FlexLogger.getLogger(BrmsGateway.class); + private static final String CONFIGFILE = "config.properties"; + + private static PolicyEngine policyEngine = null; + + private BrmsGateway() { + // Default private constructor + } + + public static void main(final String[] args) throws Exception { + // Initialize Handler. + logger.info("Initializing BRMS Handler"); + BrmsHandler brmsHandler = null; + try { + brmsHandler = new BrmsHandler(CONFIGFILE); + } catch (final 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 (final Exception e) { + logger.error(XACMLErrorConstants.ERROR_UNKNOWN + "Error while Initializing Policy Engine " + e.getMessage(), + e); + } + + // Keep Running.... + final Runnable runnable = () -> { + while (true) { + try { + Thread.sleep(30000); + } catch (final InterruptedException e) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Thread Exception " + e.getMessage()); + Thread.currentThread().interrupt(); + } + } + }; + final Thread thread = new Thread(runnable); + thread.start(); + } + + public static PolicyEngine getPolicyEngine() { + return policyEngine; + } +} diff --git a/BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsHandler.java b/BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsHandler.java new file mode 100644 index 000000000..0f686feec --- /dev/null +++ b/BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsHandler.java @@ -0,0 +1,200 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017-2018 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.brms.api; + +import java.util.ArrayList; +import java.util.Collection; + +import org.onap.policy.api.ConfigRequestParameters; +import org.onap.policy.api.LoadedPolicy; +import org.onap.policy.api.NotificationType; +import org.onap.policy.api.PDPNotification; +import org.onap.policy.api.PolicyConfig; +import org.onap.policy.api.PolicyConfigStatus; +import org.onap.policy.api.PolicyEngine; +import org.onap.policy.api.PolicyException; +import org.onap.policy.api.RemovedPolicy; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.utils.BackUpHandler; +import org.onap.policy.xacml.api.XACMLErrorConstants; + +/** + * BRMSHandler: Notification Handler which listens for PDP Notifications. Take action only for BRMS + * policies. + * + * @version 0.3 + */ +public class BrmsHandler implements BackUpHandler { + + private static final Logger logger = FlexLogger.getLogger(BrmsHandler.class.getName()); + + private BrmsPush brmsPush = null; + + public BrmsHandler(final String propertiesFile) throws PolicyException { + setBrmsPush(new BrmsPush(propertiesFile, this)); + } + + public void setBrmsPush(final BrmsPush brmsPush) { + this.brmsPush = brmsPush; + } + + /* + * This Method is executed upon notification by the Policy Engine API Notification. + * (non-Javadoc) + * + * @see + * org.onap.policy.utils.BackUpHandler#notificationReceived(org.onap.policy.api.PDPNotification) + */ + @Override + public void notificationReceived(final PDPNotification notification) { + logger.info("Notification Recieved"); + logger.info(notification.getNotificationType().toString()); + final Boolean flag = BrmsPush.getBackUpMonitor().getFlag(); + brmsPush.initiate(flag); + if (flag) { + logger.info("Master Application performing on Notification "); + runOnNotification(notification); + } else { + logger.info("Slave application Skipping Notification.. "); + } + } + + /* + * Executed when a policy is removed from PDP. + */ + private void removedPolicies(final Collection removedPolicies) { + Boolean removed = false; + logger.info("Removed Policies"); + for (final RemovedPolicy removedPolicy : removedPolicies) { + logger.info(removedPolicy.getPolicyName()); + logger.info(removedPolicy.getVersionNo()); + if (removedPolicy.getPolicyName().contains("_BRMS_")) { + try { + logger.info("Policy Removed with this policy Name : " + removedPolicy.getPolicyName()); + brmsPush.removeRule(removedPolicy.getPolicyName()); + removed = true; + } catch (final Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Rertriving policy failed " + e.getMessage(), + e); + } + } + } + Boolean failureFlag; + int index = 0; + do { + failureFlag = false; + if (removed) { + try { + brmsPush.pushRules(); + } catch (final PolicyException e) { + // Upon Notification failure + failureFlag = true; + brmsPush.rotateUrls(); + logger.error("Failure during Push Operation ", e); + } + } + index++; + } + while (failureFlag && index < brmsPush.urlListSize()); + } + + /* + * This method is executed if BRMSGW is "MASTER" (non-Javadoc) + * + * @see + * org.onap.policy.utils.BackUpHandler#runOnNotification(org.onap.policy.api.PDPNotification) + */ + @Override + public void runOnNotification(final PDPNotification notification) { + // reset the BRMSPush data structures + brmsPush.resetDs(); + if (notification.getNotificationType().equals(NotificationType.REMOVE)) { + removedPolicies(notification.getRemovedPolicies()); + } else if (notification.getNotificationType().equals(NotificationType.UPDATE) + || notification.getNotificationType().equals(NotificationType.BOTH)) { + logger.info("Updated Policies: \n"); + final ArrayList brmsPolicies = addedPolicies(notification); + Boolean successFlag = false; + for (int i = 0; !successFlag && i < brmsPush.urlListSize(); i++) { + if (i != 0) { + for (final PolicyConfig policyConfig : brmsPolicies) { + logger.info("Policy Retry with this Name notified: " + policyConfig.getPolicyName()); + brmsPush.addRule(policyConfig.getPolicyName(), policyConfig.toOther(), + policyConfig.getResponseAttributes()); + } + } + try { + brmsPush.pushRules(); + successFlag = true; + } catch (final PolicyException e) { + // Upon Notification failure + successFlag = false; + brmsPush.rotateUrls(); + logger.error("Failure during Push Operation ", e); + } + } + } + } + + /* + * Executed when a policy is added to PDP. + */ + private ArrayList addedPolicies(final PDPNotification notification) { + final ArrayList result = new ArrayList<>(); + for (final LoadedPolicy updatedPolicy : notification.getLoadedPolicies()) { + logger.info("policyName : " + updatedPolicy.getPolicyName()); + logger.info("policyVersion :" + updatedPolicy.getVersionNo()); + logger.info("Matches: " + updatedPolicy.getMatches()); + // Checking the Name is correct or not. + if (updatedPolicy.getPolicyName().contains("_BRMS_")) { + try { + final PolicyEngine policyEngine = getPolicyEngine(); + if (policyEngine != null) { + final ConfigRequestParameters configRequestParameters = new ConfigRequestParameters(); + configRequestParameters.setPolicyName(updatedPolicy.getPolicyName()); + final Collection policyConfigs = policyEngine.getConfig(configRequestParameters); + for (final PolicyConfig policyConfig : policyConfigs) { + if (policyConfig.getPolicyConfigStatus().equals(PolicyConfigStatus.CONFIG_RETRIEVED)) { + logger.info( + "Policy Retrieved with this Name notified: " + policyConfig.getPolicyName()); + result.add(policyConfig); + brmsPush.addRule(policyConfig.getPolicyName(), policyConfig.toOther(), + policyConfig.getResponseAttributes()); + } else { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "Fail to retrieve policy so rule will not be pushed to PolicyRepo !!!!\n\n"); + } + } + } + } catch (final Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Rertriving policy failed " + e.getMessage(), + e); + } + } + } + return result; + } + + public PolicyEngine getPolicyEngine() { + return BrmsGateway.getPolicyEngine(); + } +} diff --git a/BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsPush.java b/BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsPush.java new file mode 100644 index 000000000..63b6d2c9a --- /dev/null +++ b/BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsPush.java @@ -0,0 +1,1207 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017-2018 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.brms.api; + +import com.att.nsa.cambria.client.CambriaBatchingPublisher; +import com.att.nsa.cambria.client.CambriaClientBuilders; +import com.att.nsa.cambria.client.CambriaClientBuilders.PublisherBuilder; +import com.fasterxml.jackson.core.JsonProcessingException; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.Writer; +import java.net.URL; +import java.nio.channels.Channels; +import java.nio.channels.ReadableByteChannel; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.regex.Pattern; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.EntityTransaction; +import javax.persistence.Persistence; +import javax.persistence.Query; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.lang.StringEscapeUtils; +import org.apache.maven.model.Dependency; +import org.apache.maven.model.DeploymentRepository; +import org.apache.maven.model.DistributionManagement; +import org.apache.maven.model.Model; +import org.apache.maven.model.io.xpp3.MavenXpp3Writer; +import org.apache.maven.shared.invoker.DefaultInvocationRequest; +import org.apache.maven.shared.invoker.DefaultInvoker; +import org.apache.maven.shared.invoker.InvocationRequest; +import org.apache.maven.shared.invoker.InvocationResult; +import org.apache.maven.shared.invoker.Invoker; +import org.codehaus.plexus.util.IOUtil; +import org.codehaus.plexus.util.WriterFactory; +import org.eclipse.persistence.config.PersistenceUnitProperties; +import org.onap.policy.api.PEDependency; +import org.onap.policy.api.PolicyException; +import org.onap.policy.brms.entity.BrmsGroupInfo; +import org.onap.policy.brms.entity.BrmsPolicyInfo; +import org.onap.policy.brms.entity.DependencyInfo; +import org.onap.policy.common.im.IntegrityMonitor; +import org.onap.policy.common.logging.eelf.MessageCodes; +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 org.onap.policy.utils.BackUpHandler; +import org.onap.policy.utils.BackUpMonitor; +import org.onap.policy.utils.BusPublisher; +import org.onap.policy.utils.PolicyUtils; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.sonatype.nexus.client.NexusClient; +import org.sonatype.nexus.client.NexusClientException; +import org.sonatype.nexus.client.NexusConnectionException; +import org.sonatype.nexus.client.rest.NexusRestClient; +import org.sonatype.nexus.rest.model.NexusArtifact; + +/** + * BRMSPush: Application responsible to push policies to the BRMS PDP Policy Repository (PR). + * Mavenize and push policy to PR + * + * @version 1.0 + */ + +@SuppressWarnings("deprecation") +public class BrmsPush { + private static final String GROUP_NAMES = "groupNames"; + private static final String DROOLS_APPS_TEMPLATE_GROUP = + "org.onap.policy.drools-applications.controlloop.templates"; + private static final String DROOLS_APPS_MODEL_GROUP = + "org.onap.policy.drools-applications.controlloop.common.model-impl"; + private static final String META_INF = "META-INF"; + private static final String KMODULE_XML_FILE = "kmodule.xml"; + private static final String POM_XML_FILE = "pom.xml"; + private static final String VERSION_0_1_0 = "0.1.0"; + private static final String RULES = "rules"; + private static final String RESOURCES = "resources"; + 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.2.0-SNAPSHOT"; + private static final String DEPENDENCY_FILE = "dependency.json"; + private static final String BRMSPERSISTENCE = "brmsEclipselink.persistencexml"; + + private static Map modifiedGroups = new HashMap<>(); + private static IntegrityMonitor im; + private static BackUpMonitor bm; + private String defaultName = null; + private String repId = null; + private String repName = null; + private List repUrlList = null; + private String repUserName = null; + private String repPassword = null; + private String policyKeyId = null; + private boolean createFlag = false; + private String uebList = null; + private List 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 List controllers; + private Map> groupMap = new HashMap<>(); + private final Map policyMap = new HashMap<>(); + private String brmsdependencyversion; + private EntityManager em; + private boolean syncFlag = false; + + /** + * Responsible to push policies to the BRMS PDP Policy Repository (PR). + * + * @param propertiesFile the properties file + * @param handler the {@link BackUpHandler} + * @throws PolicyException PolicyException related to the operation + */ + public BrmsPush(final String propertiesFile, final BackUpHandler handler) throws PolicyException { + if (propertiesFile == null || handler == null) { + throw new PolicyException("Error no propertiesFile or handler"); + } + final Properties config = new Properties(); + final 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(final Path file, final Properties config, final BackUpHandler handler) + throws PolicyException { + InputStream in; + try { + in = new FileInputStream(file.toFile()); + config.load(in); + } catch (final 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 (final 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 (final Exception e) { + LOGGER.error("Error starting BackUpMonitor: " + e); + } + if (!config.containsKey(BRMSPERSISTENCE)) { + config.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, "META-INF/persistenceBRMS.xml"); + } else { + config.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, + config.getProperty(BRMSPERSISTENCE, "META-INF/persistenceBRMS.xml")); + } + final 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(); + final 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(",")) { + repUrlList = new ArrayList<>(Arrays.asList(repUrl.trim().split(","))); + } else { + repUrlList = new ArrayList<>(); + repUrlList.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(); + final 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"); + final String aafLogin = config.getProperty("CLIENT_ID").trim(); + final 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 notificationDelay = config.getProperty("NOTIFICATION_DELAY"); + if (notificationDelay != null && !notificationDelay.isEmpty()) { + notificationDelay = notificationDelay.trim(); + try { + dmaapDelay = Long.parseLong(notificationDelay); + } catch (final 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"); + 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); + String apiKey = config.getProperty("UEB_API_KEY"); + String apiSecret = config.getProperty("UEB_API_SECRET"); + if (apiKey != null && !apiKey.isEmpty() && apiSecret != null && !apiSecret.isEmpty()) { + apiKey = apiKey.trim(); + apiSecret = apiSecret.trim(); + pubBuilder.authenticatedBy(apiKey, apiSecret); + } + String notificationDelay = config.getProperty("NOTIFICATION_DELAY"); + if (notificationDelay != null && !notificationDelay.isEmpty()) { + notificationDelay = notificationDelay.trim(); + try { + uebDelay = Long.parseLong(notificationDelay); + } catch (final NumberFormatException e) { + LOGGER.error("UEB_DELAY not a long format number" + e); + } + } + LOGGER.info("UEB PublisherBuilder is created."); + + } + + } + + private static void setBackupMonitor(final BackUpMonitor instance) { + bm = instance; + } + + private static void setIntegrityMonitor(final IntegrityMonitor instance) { + im = instance; + } + + /** + * Will Initialize the variables required for BRMSPush. + */ + public void initiate(final boolean flag) { + resetModifiedGroups(); + controllers = new ArrayList<>(); + try { + bm.updateNotification(); + } catch (final Exception e) { + LOGGER.error("Error while updating Notification: " + e.getMessage(), e); + } + if (flag) { + syncGroupInfo(); + } + } + + public void resetDs() { + resetModifiedGroups(); + controllers = new ArrayList<>(); + } + + private static void resetModifiedGroups() { + modifiedGroups = new HashMap<>(); + } + + /** + * Will Add rules to projects. Creates necessary folders if required. + */ + public void addRule(final String name, final String rule, final Map 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; + final ArrayList userDependencies = new ArrayList<>(); + for (final Map.Entry entry : responseAttributes.entrySet()) { + final String key = entry.getKey(); + String value = entry.getValue(); + if (key.equals(policyKeyId)) { + selectedName = value; + } + // kmodule configurations + else if ("kSessionName".equals(key)) { + ksessionName = value; + } + // Check User Specific values. + if ("$controller:".equals(key)) { + try { + final PEDependency dependency = PolicyUtils.jsonStringToObject(value, PEDependency.class); + userControllerName = key.replaceFirst("$controller:", ""); + LOGGER.info("addRule: userControllerName - " + userControllerName + ", dependency: - " + + dependency); + addToGroup(userControllerName, dependency); + } catch (final Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while resolving Controller: " + e); + } + + } else if ("$dependency$".equals(key) && value.startsWith("[") && value.endsWith("]")) { + value = value.substring(1, value.length() - 1).trim(); + final List dependencyStrings = Arrays.asList(value.split(Pattern.quote("},{"))); + for (final String dependencyString : dependencyStrings) { + try { + userDependencies.add(PolicyUtils.jsonStringToObject(dependencyString, PEDependency.class)); + } catch (final Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while resolving Dependencies: " + + e); + } + } + } + } + if (userControllerName != null) { + // Adding custom dependencies here. + final ArrayList 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) { + LOGGER.info("kSessionName is null, selectedName is : " + selectedName); + if (selectedName.equalsIgnoreCase(defaultName)) { + ksessionName = "closedloop"; + } else { + ksessionName = "closedloop-" + selectedName; + } + } + // create directories if missing. + manageProject(selectedName, ksessionName, name, rule); + + // Will check for Create Later after generating the Pom. + addModifiedGroup(selectedName, "update"); + } + } + + private void syncGroupInfo() { + // Sync DB to JMemory. + final EntityTransaction et = em.getTransaction(); + et.begin(); + Query query = em.createQuery("select b from BrmsGroupInfo AS b"); + List result = query.getResultList(); + if (result.size() != groupMap.size()) { + for (final Object value : result) { + final BrmsGroupInfo brmsGroupInfo = (BrmsGroupInfo) value; + final PEDependency dependency = new PEDependency(); + dependency.setArtifactId(brmsGroupInfo.getArtifactId()); + dependency.setGroupId(brmsGroupInfo.getGroupId()); + dependency.setVersion(brmsGroupInfo.getVersion()); + final ArrayList values = new ArrayList<>(); + values.add(dependency); + groupMap.put(brmsGroupInfo.getControllerName(), values); + } + } + query = em.createQuery("select g from BrmsPolicyInfo AS g"); + result = query.getResultList(); + if (result.size() != policyMap.size()) { + for (final Object value : result) { + final 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(final String selectedName, final String ksessionName, final String name, + final 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(final String policyName, final String controllerName) { + policyMap.put(policyName, controllerName); + final EntityTransaction et = em.getTransaction(); + et.begin(); + Query query = em.createQuery("select b from BrmsPolicyInfo as b where b.policyName = :pn"); + query.setParameter("pn", policyName); + final List pList = query.getResultList(); + boolean create = false; + BrmsPolicyInfo brmsPolicyInfo = new BrmsPolicyInfo(); + if (!pList.isEmpty()) { + // Already exists. + brmsPolicyInfo = (BrmsPolicyInfo) pList.get(0); + if (!brmsPolicyInfo.getControllerName().getControllerName().equals(controllerName)) { + create = true; + } + } else { + create = true; + } + if (create) { + query = em.createQuery("select b from BrmsGroupInfo as b where b.controllerName = :cn"); + query.setParameter("cn", controllerName); + final List bList = query.getResultList(); + BrmsGroupInfo brmsGroupInfo = new BrmsGroupInfo(); + if (!bList.isEmpty()) { + brmsGroupInfo = (BrmsGroupInfo) bList.get(0); + } + brmsPolicyInfo.setPolicyName(policyName); + brmsPolicyInfo.setControllerName(brmsGroupInfo); + em.persist(brmsPolicyInfo); + em.flush(); + } + et.commit(); + } + + private void syncProject(final String selectedName) { + final boolean projectExists = checkProject(selectedName); + if (projectExists) { + String version; + version = getVersion(selectedName); + if (version == null) { + LOGGER.error("Error getting local version for the given Controller Name:" + selectedName + + " going with Default value"); + version = VERSION_0_1_0; + } + final String nextVersion = incrementVersion(version); + final boolean outOfSync = checkRemoteSync(selectedName, nextVersion); + if (!outOfSync) { + return; + } + } + // We are out of Sync or Project is not Present. + downloadProject(selectedName); + } + + private void downloadProject(final String selectedName) { + final NexusArtifact artifact = getLatestArtifactFromNexus(selectedName); + if (artifact == null) { + return; + } + final String dirName = getDirectoryName(selectedName); + URL website; + final String fileName = "rule.jar"; + try { + website = new URL(artifact.getResourceURI()); + try (ReadableByteChannel rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(fileName)) { + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + extractJar(fileName, dirName); + new File(fileName).delete(); + } catch (final IOException e) { + LOGGER.error("Error while downloading the project to File System. " + e.getMessage(), e); + } + + } catch (final IOException e1) { + LOGGER.error("Error while retrieve the artifact. " + e1.getMessage(), e1); + } + } + + private void extractJar(final String jarFileName, final String artifactId) { + try (JarFile jar = new JarFile(jarFileName)) { + final Enumeration enumEntries = jar.entries(); + while (enumEntries.hasMoreElements()) { + final JarEntry jarEntry = (JarEntry) enumEntries.nextElement(); + File file = null; + final String fileName = jarEntry.getName().substring(jarEntry.getName().lastIndexOf("/") + 1); + if (jarEntry.getName().endsWith(".drl")) { + final 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", ""))) { + file = new File(path + File.separator + fileName); + } else { + file = new File(path + File.separator + fileName); + } + } else if (jarEntry.getName().endsWith(POM_XML_FILE)) { + final String path = PROJECTSLOCATION + File.separator + artifactId; + new File(path).mkdirs(); + file = new File(path + File.separator + fileName); + } else if (jarEntry.getName().endsWith(KMODULE_XML_FILE)) { + final String path = PROJECTSLOCATION + File.separator + artifactId + File.separator + "src" + + File.separator + "main" + File.separator + RESOURCES + File.separator + META_INF; + new File(path).mkdirs(); + file = new File(path + File.separator + fileName); + } + if (file != null) { + try (InputStream is = jar.getInputStream(jarEntry); + FileOutputStream fos = new FileOutputStream(file)) { + while (is.available() > 0) { + fos.write(is.read()); + } + LOGGER.info(fileName + " Created.."); + } catch (final IOException e) { + LOGGER.info("exception Occured" + e); + } + } + } + } catch (final IOException e) { + LOGGER.info("exception Occured" + e); + } + } + + private NexusArtifact getLatestArtifactFromNexus(final String selectedName) { + final List artifacts = getArtifactFromNexus(selectedName, null); + int bigNum = 0; + int smallNum = 0; + NexusArtifact result = null; + for (final NexusArtifact artifact : artifacts) { + final int majorVal = + Integer.parseInt(artifact.getVersion().substring(0, artifact.getVersion().indexOf("."))); + final 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)) { + smallNum = minorVal; + } + 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(final String selectedName, final NexusArtifact result) { + if (result == null) { + return result; + } + final String nextVersion = incrementVersion(result.getVersion()); + final List artifact = getArtifactFromNexus(selectedName, nextVersion); + return artifact.isEmpty() ? result : additionalNexusLatestCheck(selectedName, artifact.get(0)); + } + + private boolean checkRemoteSync(final String selectedName, final String version) { + final List artifacts = getArtifactFromNexus(selectedName, version); + return artifacts.isEmpty() ? false : true; + } + + private List getArtifactFromNexus(final String selectedName, final String version) { + final NexusClient client = new NexusRestClient(); + int index = 0; + boolean flag = false; + while (index < repUrlList.size()) { + try { + final String repUrl = repUrlList.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); + } + final List 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(repUrlList, -1); + index++; + } + } + } + return new ArrayList<>(); + } + + private String incrementVersion(final 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(final String selectedName) { + return new File(PROJECTSLOCATION + File.separator + getDirectoryName(selectedName)).exists(); + } + + private String getDirectoryName(final String selectedName) { + return getArtifactId(selectedName); + } + + /** + * Will Push policies to the PolicyRepo. + * + * @throws PolicyException PolicyException related to the operation + */ + public void pushRules() throws PolicyException { + // Check how many groups have been updated. + // Invoke their Maven process. + try { + im.startTransaction(); + } catch (final Exception e) { + LOGGER.error("Error while starting Transaction " + e); + } + if (!modifiedGroups.isEmpty()) { + Boolean flag = false; + for (final Map.Entry entry : modifiedGroups.entrySet()) { + InvocationResult result = null; + final String group = entry.getKey(); + try { + LOGGER.info("PushRules: ModifiedGroups, Key: " + group + ", Value: " + entry.getValue()); + final InvocationRequest request = new DefaultInvocationRequest(); + setVersion(group); + createPom(group); + request.setPomFile(new File( + PROJECTSLOCATION + File.separator + getArtifactId(group) + File.separator + POM_XML_FILE)); + request.setGoals(Arrays.asList(GOALS)); + final 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 (final 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, entry.getValue()); + } + 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(final String name) { + final 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(final String name) { + if (policyMap.containsKey(name)) { + return policyMap.get(name); + } else { + syncGroupInfo(); + return policyMap.containsKey(name) ? policyMap.get(name) : null; + } + } + + private void addModifiedGroup(final String controllerName, final String operation) { + if (controllerName != null) { + modifiedGroups.put(controllerName, operation); + } + } + + private void addNotification(final String controllerName, final String operation) { + final ControllerPojo controllerPojo = new ControllerPojo(); + controllerPojo.setName(controllerName); + controllerPojo.setOperation(operation); + final HashMap drools = new HashMap<>(); + drools.put("groupId", getGroupId(controllerName)); + drools.put("artifactId", getArtifactId(controllerName)); + drools.put("version", getVersion(controllerName)); + controllerPojo.setDrools(drools); + controllers.add(controllerPojo); + try { + LOGGER.debug("Notification added: " + PolicyUtils.objectToJsonString(controllerPojo)); + } catch (final JsonProcessingException e) { + LOGGER.error(MessageCodes.ERROR_SCHEMA_INVALID + "Json Processing Error " + e); + } + } + + private void removedRuleModifiedGroup(final String controllerName) { + // This will be sending Notification to PDPD directly to Lock + final ControllerPojo controllerPojo = new ControllerPojo(); + controllerPojo.setName(controllerName); + controllerPojo.setOperation("lock"); + final List controllerPojos = new ArrayList<>(); + controllerPojos.add(controllerPojo); + sendNotification(controllerPojos); + } + + private void sendNotification(final List controllers) { + final NotificationPojo notification = new NotificationPojo(); + final String requestId = UUID.randomUUID().toString(); + LOGGER.info("Generating notification RequestID : " + requestId); + notification.setRequestId(requestId); + notification.setEntity("controller"); + notification.setControllers(controllers); + try { + final String notificationJson = PolicyUtils.objectToJsonString(notification); + LOGGER.info("Sending Notification :\n" + notificationJson); + sendMessage(notificationJson); + } catch (final Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while sending notification to PDP-D " + + e.getMessage(), e); + } + } + + private void sendMessage(final 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"); + + final CambriaBatchingPublisher pub = pubBuilder.build(); + pub.send("MyPartitionKey", message); + + final List stuck = pub.close(uebDelay, TimeUnit.SECONDS); + if (!stuck.isEmpty()) { + LOGGER.error(stuck.size() + " messages unsent"); + } else { + LOGGER.debug("Clean exit; Message Published on UEB : " + uebList + "for Topic: " + pubTopic); + } + } + + } + + private void createPom(final String name) { + final Model model = new Model(); + model.setModelVersion("4.0.0"); + model.setGroupId(getGroupId(name)); + model.setArtifactId(getArtifactId(name)); + model.setVersion(getVersion(name)); + model.setName(name); + final DistributionManagement distributionManagement = new DistributionManagement(); + final DeploymentRepository repository = new DeploymentRepository(); + repository.setId(repId); + repository.setName(repName); + repository.setUrl(repUrlList.get(0)); + distributionManagement.setRepository(repository); + model.setDistributionManagement(distributionManagement); + // Dependency Management goes here. + List dependencyList = new ArrayList<>(); + if (groupMap.get(name).size() > 1) { + @SuppressWarnings("unchecked") + final ArrayList dependencies = (ArrayList) groupMap.get(name).get(1); + for (final PEDependency dependency : dependencies) { + dependencyList.add(dependency.getDependency()); + } + } 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_FILE)); + final MavenXpp3Writer pomWriter = new MavenXpp3Writer(); + pomWriter.write(writer, model); + } catch (final Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while creating POM for " + getArtifactId(name) + + e.getMessage(), e); + } finally { + IOUtil.close(writer); + } + } + + private List getDependencies(final String controllerName) { + // Read the Dependency Information from property file. + final Path file = Paths.get(DEPENDENCY_FILE); + if (!Files.notExists(file)) { + try { + final String dependencyJson = new String(Files.readAllBytes(file), StandardCharsets.UTF_8); + final DependencyInfo dependencyInfo = + PolicyUtils.jsonStringToObject(dependencyJson, DependencyInfo.class); + String controller = "default"; + if (dependencyInfo.getDependencies().containsKey(controllerName)) { + controller = controllerName; + } + final List dependencyList = new ArrayList<>(); + for (final 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); + } + } + return defaultDependencies(controllerName); + } + + /** + * Default Dependency Section. Can be changed as required. + * + * @param controllerName the controller name + * @return changed dependency list + */ + public List defaultDependencies(final String controllerName) { + + final List dependencyList = new ArrayList<>(); + final String version = StringEscapeUtils.escapeJava(brmsdependencyversion); + + final Dependency demoDependency = new Dependency(); + demoDependency.setGroupId(DROOLS_APPS_TEMPLATE_GROUP); + demoDependency.setArtifactId("template.demo"); + demoDependency.setVersion(version); + dependencyList.add(demoDependency); + + final Dependency controlloopDependency = new Dependency(); + controlloopDependency.setGroupId(DROOLS_APPS_MODEL_GROUP); + controlloopDependency.setArtifactId("events"); + controlloopDependency.setVersion(version); + dependencyList.add(controlloopDependency); + + final Dependency restDependency = new Dependency(); + restDependency.setGroupId(DROOLS_APPS_MODEL_GROUP); + restDependency.setArtifactId("controlloop.common.model-impl.rest"); + restDependency.setVersion(version); + dependencyList.add(restDependency); + + final Dependency appcDependency = new Dependency(); + appcDependency.setGroupId(DROOLS_APPS_MODEL_GROUP); + appcDependency.setArtifactId("controlloop.common.model-impl.appc"); + appcDependency.setVersion(version); + dependencyList.add(appcDependency); + + final Dependency aaiDependency = new Dependency(); + aaiDependency.setGroupId(DROOLS_APPS_MODEL_GROUP); + aaiDependency.setArtifactId("controlloop.common.model-impl.aai"); + aaiDependency.setVersion(version); + dependencyList.add(aaiDependency); + + final Dependency msoDependency = new Dependency(); + msoDependency.setGroupId(DROOLS_APPS_MODEL_GROUP); + msoDependency.setArtifactId("controlloop.common.model-impl.so"); + msoDependency.setVersion(version); + dependencyList.add(msoDependency); + + final Dependency trafficgeneratorDependency = new Dependency(); + trafficgeneratorDependency.setGroupId(DROOLS_APPS_MODEL_GROUP); + trafficgeneratorDependency.setArtifactId("controlloop.common.model-impl.trafficgenerator"); + trafficgeneratorDependency.setVersion(version); + dependencyList.add(trafficgeneratorDependency); + return dependencyList; + } + + private void createProject(final String path, final 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_FILE))) { + // Hard coding XML for PDP Drools to accept our Rules. + final String xml = "" + "\n" + + "" + "\n" + + "" + "\n" + "" + + "\n" + ""; + copyDataToFile(path + File.separator + META_INF + File.separator + KMODULE_XML_FILE, xml); + } + } + + private void copyDataToFile(final String file, final String rule) { + try { + FileUtils.writeStringToFile(new File(file), rule); + } catch (final Exception e) { + LOGGER.error( + XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while creating Rule for " + file + e.getMessage(), + e); + } + } + + private void readGroups(final Properties config) throws PolicyException { + String[] groupNames; + final String groupNamesError = "groupNames property is missing or empty from the property file "; + if (!config.containsKey(GROUP_NAMES) || config.getProperty(GROUP_NAMES) == null) { + throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + groupNamesError); + } + if (config.getProperty(GROUP_NAMES).contains(",")) { + groupNames = config.getProperty(GROUP_NAMES).replaceAll(" ", "").split(","); + } else { + groupNames = new String[] {config.getProperty(GROUP_NAMES).replaceAll(" ", "")}; + } + if (groupNames == null || groupNames.length == 0) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + groupNamesError); + throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + groupNamesError); + } + groupMap = new HashMap<>(); + for (int counter = 0; counter < groupNames.length; counter++) { + final String name = groupNames[counter]; + final 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 "); + } + final 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 "); + } + final PEDependency dependency = new PEDependency(); + dependency.setArtifactId(artifactId); + dependency.setGroupId(groupId); + // Add to list if we got all + addToGroup(name, dependency); + } + } + + private void addToGroup(final String name, final PEDependency dependency) { + final ArrayList values = new ArrayList<>(); + values.add(dependency); + groupMap.put(name, values); + final EntityTransaction et = em.getTransaction(); + et.begin(); + final Query query = em.createQuery("select b from BrmsGroupInfo as b where b.controllerName = :cn"); + query.setParameter("cn", name); + final List groupList = query.getResultList(); + BrmsGroupInfo brmsGroupInfo = null; + if (!groupList.isEmpty()) { + 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(final String name) { + return ((PEDependency) groupMap.get(name).get(0)).getArtifactId(); + } + + private String getGroupId(final String name) { + return ((PEDependency) groupMap.get(name).get(0)).getGroupId(); + } + + private String getVersion(final String name) { + return ((PEDependency) groupMap.get(name).get(0)).getVersion(); + } + + private void getNameAndSetRemove(final String controllerName, final String policyName) { + final String artifactName = getArtifactId(controllerName); + final String ruleFolder = PROJECTSLOCATION + File.separator + artifactName + File.separator + "src" + + File.separator + "main" + File.separator + RESOURCES + File.separator + RULES; + final 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) { + removedRuleModifiedGroup(controllerName); + } else { + // This is an update in terms of PDPD. + addModifiedGroup(controllerName, "update"); + } + } + + // Removes Policy from Memory and Database. + private void removePolicyFromGroup(final String policyName, final String controllerName) { + policyMap.remove(policyName); + final EntityTransaction et = em.getTransaction(); + et.begin(); + final Query query = em.createQuery("select b from BrmsPolicyInfo as b where b.policyName = :pn"); + query.setParameter("pn", policyName); + final List pList = query.getResultList(); + BrmsPolicyInfo brmsPolicyInfo; + if (!pList.isEmpty()) { + // Already exists. + brmsPolicyInfo = (BrmsPolicyInfo) pList.get(0); + if (brmsPolicyInfo.getControllerName().getControllerName().equals(controllerName)) { + em.remove(brmsPolicyInfo); + em.flush(); + } + } + et.commit(); + } + + private void setVersion(final String selectedName) { + String newVersion = VERSION_0_1_0; + createFlag = false; + final NexusArtifact artifact = getLatestArtifactFromNexus(selectedName); + if (artifact != null) { + newVersion = incrementVersion(artifact.getVersion()); + } + if (VERSION_0_1_0.equals(newVersion)) { + createFlag = true; + } + setVersion(newVersion, selectedName); + LOGGER.info("Controller: " + selectedName + "is on version: " + newVersion); + } + + private void setVersion(final String newVersion, final String controllerName) { + final 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; + } + + /** + * Rotate URLs list. + */ + public void rotateUrls() { + if (repUrlList != null) { + Collections.rotate(repUrlList, -1); + } + } + + /** + * Get URL List Size. + * + * @return URL list size + */ + public int urlListSize() { + return repUrlList != null ? repUrlList.size() : 0; + } +} diff --git a/BRMSGateway/src/main/java/org/onap/policy/brms/api/ControllerPojo.java b/BRMSGateway/src/main/java/org/onap/policy/brms/api/ControllerPojo.java new file mode 100644 index 000000000..e04a07971 --- /dev/null +++ b/BRMSGateway/src/main/java/org/onap/policy/brms/api/ControllerPojo.java @@ -0,0 +1,57 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * 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.brms.api; + +import java.util.Map; + +/** + * POJO for controller information. + * + */ +public class ControllerPojo { + private String name; + private Map drools; + private String operation; + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public Map getDrools() { + return drools; + } + + public void setDrools(final Map drools) { + this.drools = drools; + } + + public String getOperation() { + return operation; + } + + public void setOperation(final String operation) { + this.operation = operation; + } +} diff --git a/BRMSGateway/src/main/java/org/onap/policy/brms/api/NotificationPojo.java b/BRMSGateway/src/main/java/org/onap/policy/brms/api/NotificationPojo.java new file mode 100644 index 000000000..788cbf7fd --- /dev/null +++ b/BRMSGateway/src/main/java/org/onap/policy/brms/api/NotificationPojo.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * 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.brms.api; + +import java.util.List; + +/** + * This POJO will be transformed to JSON for Notification Purposes. + * + */ +public class NotificationPojo { + private String requestId; + private String entity; + private List controllers; + + public String getRequestId() { + return requestId; + } + + public void setRequestId(final String requestId) { + this.requestId = requestId; + } + + public String getEntity() { + return entity; + } + + public void setEntity(final String entity) { + this.entity = entity; + } + + public List getControllers() { + return controllers; + } + + public void setControllers(final List controllers) { + this.controllers = controllers; + } + +} diff --git a/BRMSGateway/src/main/java/org/onap/policy/brms/entity/BrmsGroupInfo.java b/BRMSGateway/src/main/java/org/onap/policy/brms/entity/BrmsGroupInfo.java new file mode 100644 index 000000000..f710b41d8 --- /dev/null +++ b/BRMSGateway/src/main/java/org/onap/policy/brms/entity/BrmsGroupInfo.java @@ -0,0 +1,76 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * 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.brms.entity; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "brmsgroup_info") +public class BrmsGroupInfo { + + @Id + @Column(name = "controllerName", nullable = false, length = 255) + private String controllerName; + + @Column(name = "groupId", nullable = false, length = 255) + private String groupId; + + @Column(name = "artifactId", nullable = false, length = 255) + private String artifactId; + + @Column(name = "version", length = 255) + private String version; + + public String getControllerName() { + return controllerName; + } + + public void setControllerName(final String controllerName) { + this.controllerName = controllerName; + } + + public String getGroupId() { + return groupId; + } + + public void setGroupId(final String groupId) { + this.groupId = groupId; + } + + public String getArtifactId() { + return artifactId; + } + + public void setArtifactId(final String artifactId) { + this.artifactId = artifactId; + } + + public String getVersion() { + return version; + } + + public void setVersion(final String version) { + this.version = version; + } +} diff --git a/BRMSGateway/src/main/java/org/onap/policy/brms/entity/BrmsPolicyInfo.java b/BRMSGateway/src/main/java/org/onap/policy/brms/entity/BrmsPolicyInfo.java new file mode 100644 index 000000000..4d7287f83 --- /dev/null +++ b/BRMSGateway/src/main/java/org/onap/policy/brms/entity/BrmsPolicyInfo.java @@ -0,0 +1,57 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * 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.brms.entity; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Table; + +@Entity +@Table(name = "brmsgroup_policy") +public class BrmsPolicyInfo { + + @Id + @Column(name = "policyName") + private String policyName; + + @ManyToOne + @JoinColumn(name = "controllerName") + private BrmsGroupInfo controllerName; + + public String getPolicyName() { + return policyName; + } + + public void setPolicyName(final String policyName) { + this.policyName = policyName; + } + + public BrmsGroupInfo getControllerName() { + return controllerName; + } + + public void setControllerName(final BrmsGroupInfo controllerName) { + this.controllerName = controllerName; + } +} diff --git a/BRMSGateway/src/main/java/org/onap/policy/brms/entity/DependencyInfo.java b/BRMSGateway/src/main/java/org/onap/policy/brms/entity/DependencyInfo.java new file mode 100644 index 000000000..04a3730b1 --- /dev/null +++ b/BRMSGateway/src/main/java/org/onap/policy/brms/entity/DependencyInfo.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * 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.brms.entity; + +import java.util.List; +import java.util.Map; + +import org.onap.policy.api.PEDependency; + +public class DependencyInfo { + + private Map> dependencies; + + public Map> getDependencies() { + return dependencies; + } + + public void setDependencies(final Map> dependencies) { + this.dependencies = dependencies; + } + +} diff --git a/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSGateway.java b/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSGateway.java deleted file mode 100644 index 98c49ce23..000000000 --- a/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSGateway.java +++ /dev/null @@ -1,85 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * 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.brmsInterface; - -import org.onap.policy.api.NotificationScheme; -import org.onap.policy.api.PolicyEngine; -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. - * - * @version 0.1 - */ -class BRMSGateway { - - private static final Logger logger = FlexLogger.getLogger(BRMSGateway.class); - private static final String CONFIGFILE = "config.properties"; - - private static PolicyEngine policyEngine = null; - - private BRMSGateway() { - // Default private constructor - } - - 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 deleted file mode 100644 index b460fb87b..000000000 --- a/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSHandler.java +++ /dev/null @@ -1,189 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017-2018 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.brmsInterface; - -import java.util.ArrayList; -import java.util.Collection; - -import org.onap.policy.api.ConfigRequestParameters; -import org.onap.policy.api.LoadedPolicy; -import org.onap.policy.api.NotificationType; -import org.onap.policy.api.PDPNotification; -import org.onap.policy.api.PolicyConfig; -import org.onap.policy.api.PolicyConfigStatus; -import org.onap.policy.api.PolicyEngine; -import org.onap.policy.api.PolicyException; -import org.onap.policy.api.RemovedPolicy; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.utils.BackUpHandler; -import org.onap.policy.xacml.api.XACMLErrorConstants; - -/** - * BRMSHandler: Notification Handler which listens for PDP Notifications. - * Take action only for BRMS policies. - * - * @version 0.3 - */ -public class BRMSHandler implements BackUpHandler{ - - private static final Logger logger = FlexLogger.getLogger(BRMSHandler.class.getName()); - - private BRMSPush bRMSPush = null; - - public BRMSHandler(String propertiesFile) throws PolicyException{ - setBRMSPush(new BRMSPush(propertiesFile, this)); - } - - public void setBRMSPush(BRMSPush brmsPush) { - this.bRMSPush = brmsPush; - } - - /* - * This Method is executed upon notification by the Policy Engine API Notification. - * (non-Javadoc) - * @see org.onap.policy.utils.BackUpHandler#notificationReceived(org.onap.policy.api.PDPNotification) - */ - @Override - public void notificationReceived(PDPNotification notification) { - logger.info("Notification Recieved"); - logger.info(notification.getNotificationType().toString()); - Boolean flag = BRMSPush.getBackUpMonitor().getFlag(); - bRMSPush.initiate(flag); - if(flag){ - logger.info("Master Application performing on Notification "); - runOnNotification(notification); - }else{ - logger.info("Slave application Skipping Notification.. "); - } - } - - /* - * Executed when a policy is removed from PDP. - */ - private void removedPolicies(Collection removedPolicies){ - Boolean removed = false; - logger.info("Removed Policies"); - for(RemovedPolicy removedPolicy: removedPolicies){ - logger.info(removedPolicy.getPolicyName()); - logger.info(removedPolicy.getVersionNo()); - if(removedPolicy.getPolicyName().contains("_BRMS_")){ - try{ - logger.info("Policy Removed with this policy Name : " + removedPolicy.getPolicyName()); - bRMSPush.removeRule(removedPolicy.getPolicyName()); - removed = true; - }catch(Exception e){ - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Rertriving policy failed " + e.getMessage(), e); - } - } - } - Boolean failureFlag; - int i = 0; - do{ - failureFlag = false; - if(removed){ - try{ - bRMSPush.pushRules(); - }catch(PolicyException e){ - //Upon Notification failure - failureFlag = true; - bRMSPush.rotateURLs(); - logger.error("Failure during Push Operation " , e); - } - } - i++; - }while(failureFlag && i< bRMSPush.urlListSize()); - } - - /* - * This method is executed if BRMSGW is "MASTER" - * (non-Javadoc) - * @see org.onap.policy.utils.BackUpHandler#runOnNotification(org.onap.policy.api.PDPNotification) - */ - @Override - public void runOnNotification(PDPNotification notification){ - // reset the BRMSPush data structures - bRMSPush.resetDS(); - if(notification.getNotificationType().equals(NotificationType.REMOVE)){ - removedPolicies(notification.getRemovedPolicies()); - }else if(notification.getNotificationType().equals(NotificationType.UPDATE)|| notification.getNotificationType().equals(NotificationType.BOTH)){ - logger.info("Updated Policies: \n"); - ArrayList brmsPolicies = addedPolicies(notification); - Boolean successFlag = false; - for(int i=0; !successFlag && i< bRMSPush.urlListSize(); i++){ - if(i!=0){ - for(PolicyConfig policyConfig: brmsPolicies){ - logger.info("Policy Retry with this Name notified: " + policyConfig.getPolicyName()); - bRMSPush.addRule(policyConfig.getPolicyName(),policyConfig.toOther(),policyConfig.getResponseAttributes()); - } - } - try{ - bRMSPush.pushRules(); - successFlag = true; - }catch(PolicyException e){ - //Upon Notification failure - successFlag = false; - bRMSPush.rotateURLs(); - logger.error("Failure during Push Operation " , e); - } - } - } - } - - /* - * Executed when a policy is added to PDP. - */ - private ArrayList addedPolicies(PDPNotification notification) { - ArrayList result = new ArrayList<>(); - for(LoadedPolicy updatedPolicy: notification.getLoadedPolicies()){ - logger.info("policyName : " + updatedPolicy.getPolicyName()); - logger.info("policyVersion :" + updatedPolicy.getVersionNo()); - logger.info("Matches: " + updatedPolicy.getMatches()); - // Checking the Name is correct or not. - if(updatedPolicy.getPolicyName().contains("_BRMS_")){ - try{ - PolicyEngine policyEngine = getPolicyEngine(); - if(policyEngine!=null){ - ConfigRequestParameters configRequestParameters = new ConfigRequestParameters(); - configRequestParameters.setPolicyName(updatedPolicy.getPolicyName()); - Collection policyConfigs = policyEngine.getConfig(configRequestParameters); - for(PolicyConfig policyConfig: policyConfigs){ - if(policyConfig.getPolicyConfigStatus().equals(PolicyConfigStatus.CONFIG_RETRIEVED)){ - logger.info("Policy Retrieved with this Name notified: " + policyConfig.getPolicyName()); - result.add(policyConfig); - bRMSPush.addRule(policyConfig.getPolicyName(),policyConfig.toOther(),policyConfig.getResponseAttributes()); - }else{ - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Fail to retrieve policy so rule will not be pushed to PolicyRepo !!!!\n\n"); - } - } - } - }catch(Exception e){ - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Rertriving policy failed " + e.getMessage(), e); - } - } - } - return result; - } - - public PolicyEngine getPolicyEngine() { - return BRMSGateway.getPolicyEngine(); - } -} diff --git a/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSPush.java b/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSPush.java deleted file mode 100644 index 86cd066b8..000000000 --- a/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSPush.java +++ /dev/null @@ -1,1183 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2017-2018 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.brmsInterface; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.Writer; -import java.net.URL; -import java.nio.channels.Channels; -import java.nio.channels.ReadableByteChannel; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.security.GeneralSecurityException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.UUID; -import java.util.concurrent.TimeUnit; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; -import java.util.regex.Pattern; - -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.EntityTransaction; -import javax.persistence.Persistence; -import javax.persistence.Query; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.lang.StringEscapeUtils; -import org.apache.maven.model.Dependency; -import org.apache.maven.model.DeploymentRepository; -import org.apache.maven.model.DistributionManagement; -import org.apache.maven.model.Model; -import org.apache.maven.model.io.xpp3.MavenXpp3Writer; -import org.apache.maven.shared.invoker.DefaultInvocationRequest; -import org.apache.maven.shared.invoker.DefaultInvoker; -import org.apache.maven.shared.invoker.InvocationRequest; -import org.apache.maven.shared.invoker.InvocationResult; -import org.apache.maven.shared.invoker.Invoker; -import org.codehaus.plexus.util.IOUtil; -import org.codehaus.plexus.util.WriterFactory; -import org.eclipse.persistence.config.PersistenceUnitProperties; -import org.onap.policy.api.PEDependency; -import org.onap.policy.api.PolicyException; -import org.onap.policy.brmsInterface.jpa.BRMSGroupInfo; -import org.onap.policy.brmsInterface.jpa.BRMSPolicyInfo; -import org.onap.policy.brmsInterface.jpa.DependencyInfo; -import org.onap.policy.common.im.IntegrityMonitor; -import org.onap.policy.common.logging.eelf.MessageCodes; -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 org.onap.policy.utils.BackUpHandler; -import org.onap.policy.utils.BackUpMonitor; -import org.onap.policy.utils.BusPublisher; -import org.onap.policy.utils.PolicyUtils; -import org.onap.policy.xacml.api.XACMLErrorConstants; -import org.sonatype.nexus.client.NexusClient; -import org.sonatype.nexus.client.NexusClientException; -import org.sonatype.nexus.client.NexusConnectionException; -import org.sonatype.nexus.client.rest.NexusRestClient; -import org.sonatype.nexus.rest.model.NexusArtifact; - -import com.att.nsa.cambria.client.CambriaBatchingPublisher; -import com.att.nsa.cambria.client.CambriaClientBuilders; -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 - * - * @version 1.0 - */ - -@SuppressWarnings("deprecation") -public class BRMSPush { - private static final String GROUP_NAMES = "groupNames"; - private static final String DROOLS_APPS_TEMPLATE_GROUP = "org.onap.policy.drools-applications.controlloop.templates"; - private static final String DROOLS_APPS_MODEL_GROUP = "org.onap.policy.drools-applications.controlloop.common.model-impl"; - private static final String META_INF = "META-INF"; - private static final String KMODULE_XML_FILE = "kmodule.xml"; - private static final String POM_XML_FILE = "pom.xml"; - private static final String VERSION_0_1_0 = "0.1.0"; - private static final String RULES = "rules"; - private static final String RESOURCES = "resources"; - 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.2.0-SNAPSHOT"; - private static final String DEPENDENCY_FILE = "dependency.json"; - private static final String BRMSPERSISTENCE = "brmsEclipselink.persistencexml"; - - private static Map 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 repURLs = null; - private String repUserName = null; - private String repPassword = null; - private String policyKeyID = null; - private boolean createFlag = false; - private String uebList = null; - private List 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 controllers; - private HashMap> groupMap = new HashMap<>(); - private Map policyMap = new HashMap<>(); - private String brmsdependencyversion; - private EntityManager em; - private boolean syncFlag = false; - - public BRMSPush(String propertiesFile, BackUpHandler handler) throws PolicyException { - if(propertiesFile==null || handler==null){ - throw new PolicyException("Error no propertiesFile or handler"); - } - 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); - } - if(!config.containsKey(BRMSPERSISTENCE)){ - config.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, "META-INF/persistenceBRMS.xml"); - } else { - config.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, config.getProperty(BRMSPERSISTENCE,"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(); - } - - public void resetDS(){ - resetModifiedGroups(); - controllers = new ArrayList<>(); - } - - 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 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 userDependencies = new ArrayList<>(); - for (Map.Entry entry: responseAttributes.entrySet()) { - String key = entry.getKey(); - String value = entry.getValue(); - if (key.equals(policyKeyID)) { - selectedName = value; - } - // kmodule configurations - else if ("kSessionName".equals(key)) { - kSessionName = value; - } - // Check User Specific values. - if ("$controller:".equals(key)) { - try { - PEDependency dependency = PolicyUtils.jsonStringToObject(value, - PEDependency.class); - userControllerName = key.replaceFirst("$controller:", ""); - LOGGER.info("addRule: userControllerName - " + userControllerName + ", dependency: - " + dependency); - addToGroup(userControllerName, dependency); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while resolving Controller: " + e); - } - - } else if ("$dependency$".equals(key) && value.startsWith("[") && value.endsWith("]")) { - value = value.substring(1, value.length() - 1).trim(); - List dependencyStrings = Arrays.asList(value.split(Pattern.quote("},{"))); - for (String dependencyString : dependencyStrings) { - try { - userDependencies - .add(PolicyUtils.jsonStringToObject(dependencyString, PEDependency.class)); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error while resolving Dependencies: " + e); - } - } - } - } - if (userControllerName != null) { - // Adding custom dependencies here. - ArrayList 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) { - LOGGER.info("kSessionName is null, selectedName is : " + selectedName ); - if (selectedName.equalsIgnoreCase(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 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 create = false; - BRMSPolicyInfo brmsPolicyInfo = new BRMSPolicyInfo(); - if (!pList.isEmpty()) { - // Already exists. - brmsPolicyInfo = (BRMSPolicyInfo) pList.get(0); - if (!brmsPolicyInfo.getControllerName().getControllerName().equals(controllerName)) { - create = true; - } - } else { - create = true; - } - if (create) { - 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.isEmpty()) { - 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; - version = getVersion(selectedName); - if (version == null) { - LOGGER.error("Error getting local version for the given Controller Name:" + selectedName - + " going with Default value"); - version = 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()); - try( ReadableByteChannel rbc = Channels.newChannel(website.openStream()); - FileOutputStream fos = new FileOutputStream(fileName)){ - fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); - extractJar(fileName, dirName); - new File(fileName).delete(); - }catch (IOException e) { - LOGGER.error("Error while downloading the project to File System. " + e.getMessage(), e); - } - - } catch (IOException e1) { - LOGGER.error("Error while retrieve the artifact. " + e1.getMessage(), e1); - } - } - -private void extractJar(String jarFileName, String artifactId){ - try (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_FILE)) { - String path = PROJECTSLOCATION + File.separator + artifactId; - new File(path).mkdirs(); - f = new File(path + File.separator + fileName); - } else if (file.getName().endsWith(KMODULE_XML_FILE)) { - 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) { - try (InputStream is = jar.getInputStream(file); FileOutputStream fos = new FileOutputStream(f)) { - while (is.available() > 0) { - fos.write(is.read()); - } - LOGGER.info(fileName + " Created.."); - } catch (IOException e) { - LOGGER.info("exception Occured" + e); - } - } - } - } catch (IOException e) { - LOGGER.info("exception Occured" + e); - } - } - - private NexusArtifact getLatestArtifactFromNexus(String selectedName) { - List 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) { - bigNum = majorVal; - smallNum = minorVal; - } - if ((bigNum == majorVal) && (minorVal > smallNum)) { - smallNum = minorVal; - } - 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) { - if(result==null){ - return result; - } - String nextVersion = incrementVersion(result.getVersion()); - List artifact = getArtifactFromNexus(selectedName, nextVersion); - return artifact.isEmpty() ? result : additionalNexusLatestCheck(selectedName, artifact.get(0)); - } - - private boolean checkRemoteSync(String selectedName, String version) { - List artifacts = getArtifactFromNexus(selectedName, version); - return artifacts.isEmpty() ? false : true; - } - - private List 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 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 = VERSION_0_1_0; - createFlag = false; - NexusArtifact artifact = getLatestArtifactFromNexus(selectedName); - if (artifact != null) { - newVersion = incrementVersion(artifact.getVersion()); - } - if (VERSION_0_1_0.equals(newVersion)) { - 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) { - 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 - * 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 (Exception e) { - LOGGER.error("Error while starting Transaction " + e); - } - if (!modifiedGroups.isEmpty()) { - Boolean flag = false; - for (Map.Entry entry : modifiedGroups.entrySet()) { - InvocationResult result = null; - String group = entry.getKey(); - try { - LOGGER.info("PushRules: ModifiedGroups, Key: " + group + ", Value: " + entry.getValue()); - InvocationRequest request = new DefaultInvocationRequest(); - setVersion(group); - createPom(group); - request.setPomFile(new File( - PROJECTSLOCATION + File.separator + getArtifactID(group) + File.separator + POM_XML_FILE)); - 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, entry.getValue()); - } - 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) { - ControllerPOJO controllerPOJO = new ControllerPOJO(); - controllerPOJO.setName(controllerName); - controllerPOJO.setOperation(operation); - HashMap drools = new HashMap<>(); - drools.put("groupId", getGroupID(controllerName)); - drools.put("artifactId", getArtifactID(controllerName)); - drools.put("version", getVersion(controllerName)); - controllerPOJO.setDrools(drools); - controllers.add(controllerPOJO); - try { - LOGGER.debug("Notification added: " + PolicyUtils.objectToJsonString(controllerPOJO)); - } catch (JsonProcessingException 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 controllerPojos = new ArrayList<>(); - controllerPojos.add(controllerPOJO); - sendNotification(controllerPojos); - } - - private void sendNotification(List 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.isEmpty()) { - 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 dependencyList = new ArrayList<>(); - if (groupMap.get(name).size() > 1) { - @SuppressWarnings("unchecked") - ArrayList dependencies = (ArrayList) groupMap.get(name).get(1); - for (PEDependency dependency : dependencies) { - dependencyList.add(dependency.getDependency()); - } - } 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_FILE)); - 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 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 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); - } - } - return defaultDependencies(controllerName); - } - - // Default Dependency Section. Can be changed as required. - public List defaultDependencies(String controllerName) { - - List dependencyList = new ArrayList<>(); - String version = StringEscapeUtils.escapeJava(brmsdependencyversion); - - Dependency demoDependency = new Dependency(); - demoDependency.setGroupId(DROOLS_APPS_TEMPLATE_GROUP); - demoDependency.setArtifactId("template.demo"); - demoDependency.setVersion(version); - dependencyList.add(demoDependency); - - Dependency controlloopDependency = new Dependency(); - controlloopDependency.setGroupId(DROOLS_APPS_MODEL_GROUP); - controlloopDependency.setArtifactId("events"); - controlloopDependency.setVersion(version); - dependencyList.add(controlloopDependency); - - Dependency restDependency = new Dependency(); - restDependency.setGroupId(DROOLS_APPS_MODEL_GROUP); - restDependency.setArtifactId("controlloop.common.model-impl.rest"); - restDependency.setVersion(version); - dependencyList.add(restDependency); - - Dependency appcDependency = new Dependency(); - appcDependency.setGroupId(DROOLS_APPS_MODEL_GROUP); - appcDependency.setArtifactId("controlloop.common.model-impl.appc"); - appcDependency.setVersion(version); - dependencyList.add(appcDependency); - - Dependency aaiDependency = new Dependency(); - aaiDependency.setGroupId(DROOLS_APPS_MODEL_GROUP); - aaiDependency.setArtifactId("controlloop.common.model-impl.aai"); - aaiDependency.setVersion(version); - dependencyList.add(aaiDependency); - - Dependency msoDependency = new Dependency(); - msoDependency.setGroupId(DROOLS_APPS_MODEL_GROUP); - msoDependency.setArtifactId("controlloop.common.model-impl.so"); - msoDependency.setVersion(version); - dependencyList.add(msoDependency); - - Dependency trafficgeneratorDependency = new Dependency(); - trafficgeneratorDependency.setGroupId(DROOLS_APPS_MODEL_GROUP); - trafficgeneratorDependency.setArtifactId("controlloop.common.model-impl.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_FILE))) { - // Hard coding XML for PDP Drools to accept our Rules. - String xml = "" + "\n" - + "" + "\n" - + "" + "\n" + "" - + "\n" + ""; - copyDataToFile(path + File.separator + META_INF + File.separator + KMODULE_XML_FILE, 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; - String groupNamesError = "groupNames property is missing or empty from the property file "; - if (!config.containsKey(GROUP_NAMES) || config.getProperty(GROUP_NAMES)==null){ - throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE - + groupNamesError); - } - if (config.getProperty(GROUP_NAMES).contains(",")) { - groupNames = config.getProperty(GROUP_NAMES).replaceAll(" ", "").split(","); - } else { - groupNames = new String[] { config.getProperty(GROUP_NAMES).replaceAll(" ", "") }; - } - if (groupNames == null || groupNames.length == 0) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE - + groupNamesError); - throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE - + groupNamesError); - } - 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 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.isEmpty()) { - 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) { - return ((PEDependency) groupMap.get(name).get(0)).getGroupId(); - } - - 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); - } - 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; - if (!pList.isEmpty()) { - // 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; - } -} diff --git a/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/ControllerPOJO.java b/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/ControllerPOJO.java deleted file mode 100644 index 5a0679c29..000000000 --- a/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/ControllerPOJO.java +++ /dev/null @@ -1,52 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * 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.brmsInterface; - -import java.util.Map; - -/** - * POJO for controller information. - * - */ -public class ControllerPOJO { - private String name; - private Map drools; - private String operation; - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public Map getDrools() { - return drools; - } - public void setDrools(Map drools) { - this.drools = drools; - } - public String getOperation() { - return operation; - } - public void setOperation(String operation) { - this.operation = operation; - } -} - diff --git a/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/NotificationPOJO.java b/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/NotificationPOJO.java deleted file mode 100644 index 75bbe8a4e..000000000 --- a/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/NotificationPOJO.java +++ /dev/null @@ -1,52 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * 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.brmsInterface; - -import java.util.List; - -/** - * This POJO will be transformed to JSON for Notification Purposes. - * - */ -public class NotificationPOJO { - private String requestID; - private String entity; - private List controllers; - public String getRequestID() { - return requestID; - } - public void setRequestID(String requestID) { - this.requestID = requestID; - } - public String getEntity() { - return entity; - } - public void setEntity(String entity) { - this.entity = entity; - } - public List getControllers() { - return controllers; - } - public void setControllers(List controllers) { - this.controllers = controllers; - } - -} diff --git a/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/jpa/BRMSGroupInfo.java b/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/jpa/BRMSGroupInfo.java deleted file mode 100644 index 6b4a2bf85..000000000 --- a/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/jpa/BRMSGroupInfo.java +++ /dev/null @@ -1,75 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * 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.brmsInterface.jpa; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name="brmsgroup_info") -public class BRMSGroupInfo{ - - @Id - @Column(name = "controllerName", nullable=false, length=255) - private String controllerName; - - @Column(name = "groupId", nullable=false, length=255) - private String groupId; - - @Column(name = "artifactId", nullable=false, length=255) - private String artifactId; - - @Column(name = "version", length=255) - private String version; - - public String getControllerName() { - return controllerName; - } - - public void setControllerName(String controllerName) { - this.controllerName = controllerName; - } - - public String getGroupId() { - return groupId; - } - - public void setGroupId(String groupId) { - this.groupId = groupId; - } - - public String getArtifactId() { - return artifactId; - } - - public void setArtifactId(String artifactId) { - this.artifactId = artifactId; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } -} diff --git a/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/jpa/BRMSPolicyInfo.java b/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/jpa/BRMSPolicyInfo.java deleted file mode 100644 index c269e295a..000000000 --- a/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/jpa/BRMSPolicyInfo.java +++ /dev/null @@ -1,56 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * 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.brmsInterface.jpa; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; - -@Entity -@Table(name="brmsgroup_policy") -public class BRMSPolicyInfo { - - @Id - @Column(name="policyName") - private String policyName; - - @ManyToOne - @JoinColumn(name="controllerName") - private BRMSGroupInfo controllerName; - - public String getPolicyName() { - return policyName; - } - - public void setPolicyName(String policyName) { - this.policyName = policyName; - } - - public BRMSGroupInfo getControllerName() { - return controllerName; - } - - public void setControllerName(BRMSGroupInfo controllerName) { - this.controllerName = controllerName; - } -} diff --git a/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/jpa/DependencyInfo.java b/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/jpa/DependencyInfo.java deleted file mode 100644 index 753de5219..000000000 --- a/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/jpa/DependencyInfo.java +++ /dev/null @@ -1,38 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * 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.brmsInterface.jpa; - -import java.util.List; -import java.util.Map; - -import org.onap.policy.api.PEDependency; - -public class DependencyInfo { - private Map> dependencies; - - public Map> getDependencies() { - return dependencies; - } - - public void setDependencies(Map> dependencies) { - this.dependencies = dependencies; - } - -} diff --git a/BRMSGateway/src/main/resources/META-INF/persistenceBRMS.xml b/BRMSGateway/src/main/resources/META-INF/persistenceBRMS.xml index 99e6b92c9..f4902187b 100644 --- a/BRMSGateway/src/main/resources/META-INF/persistenceBRMS.xml +++ b/BRMSGateway/src/main/resources/META-INF/persistenceBRMS.xml @@ -3,7 +3,7 @@ ============LICENSE_START======================================================= PolicyEngineUtils ================================================================================ - Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. ================================================================================ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -20,11 +20,11 @@ --> - - org.eclipse.persistence.jpa.PersistenceProvider - org.onap.policy.brmsInterface.jpa.BRMSGroupInfo - org.onap.policy.brmsInterface.jpa.BRMSPolicyInfo - + xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> + + org.eclipse.persistence.jpa.PersistenceProvider + org.onap.policy.brms.entity.BrmsGroupInfo + org.onap.policy.brms.entity.BrmsPolicyInfo + \ No newline at end of file diff --git a/BRMSGateway/src/test/java/org/onap/brmsgw/test/BRMSJpaTest.java b/BRMSGateway/src/test/java/org/onap/brmsgw/test/BRMSJpaTest.java deleted file mode 100644 index ffcc2e379..000000000 --- a/BRMSGateway/src/test/java/org/onap/brmsgw/test/BRMSJpaTest.java +++ /dev/null @@ -1,71 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2018 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.brmsgw.test; - -import static org.junit.Assert.assertEquals; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.junit.Test; -import org.onap.policy.api.PEDependency; -import org.onap.policy.brmsInterface.jpa.BRMSGroupInfo; -import org.onap.policy.brmsInterface.jpa.BRMSPolicyInfo; -import org.onap.policy.brmsInterface.jpa.DependencyInfo; - -public class BRMSJpaTest { - @Test - public void testJpa() { - String testVal = "testVal"; - BRMSGroupInfo groupInfo = new BRMSGroupInfo(); - - // Test group info - groupInfo.setControllerName(testVal); - assertEquals(groupInfo.getControllerName(), testVal); - groupInfo.setGroupId(testVal); - assertEquals(groupInfo.getGroupId(), testVal); - groupInfo.setArtifactId(testVal); - assertEquals(groupInfo.getArtifactId(), testVal); - groupInfo.setVersion(testVal); - assertEquals(groupInfo.getVersion(), testVal); - - // Test policy info - BRMSPolicyInfo policyInfo = new BRMSPolicyInfo(); - policyInfo.setPolicyName(testVal); - assertEquals(policyInfo.getPolicyName(), testVal); - policyInfo.setControllerName(groupInfo); - assertEquals(policyInfo.getControllerName(), groupInfo); - } - - @Test - public void testDependencyInfo() { - String testKey = "testKey"; - PEDependency dependency = new PEDependency(); - List list = new ArrayList(); - list.add(dependency); - Map> map = new HashMap>(); - map.put(testKey, list); - DependencyInfo info = new DependencyInfo(); - - info.setDependencies(map); - assertEquals(info.getDependencies(), map); - } -} diff --git a/BRMSGateway/src/test/java/org/onap/brmsgw/test/BRMSPushTest.java b/BRMSGateway/src/test/java/org/onap/brmsgw/test/BRMSPushTest.java deleted file mode 100644 index aa2574401..000000000 --- a/BRMSGateway/src/test/java/org/onap/brmsgw/test/BRMSPushTest.java +++ /dev/null @@ -1,234 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * 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.brmsgw.test; - -import static org.junit.Assert.assertNotNull; - -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; - -import org.junit.Test; -import org.onap.policy.api.PolicyException; -import org.onap.policy.brmsInterface.BRMSHandler; - -public class BRMSPushTest { - - private final String VALIDFILE = "src/test/resources/config.properties"; - private final String INVALIDFILE = "src/test/resources/failure.properties"; - - @Test (expected = PolicyException.class) - public void bRMSHandlerFailTest() throws PolicyException { - new BRMSHandler(null); - } - - @Test (expected = PolicyException.class) - public void bRMSHandlerFailTest1() throws PolicyException { - new BRMSHandler("src/test/resources/filenotexists.txt"); - } - - @Test (expected = PolicyException.class) - public void bRMSHandlerFailTest2() throws PolicyException { - PropertyChange prop = new PropertyChange(); - prop.key = "defaultName"; - prop.remove = true; - List props = new LinkedList<>(); - props.add(prop); - setFailureProperties(props); - new BRMSHandler(INVALIDFILE); - } - - @Test (expected = PolicyException.class) - public void bRMSHandlerFailTest3() throws PolicyException { - PropertyChange prop = new PropertyChange(); - prop.key = "repositoryID"; - prop.remove = true; - List props = new LinkedList<>(); - props.add(prop); - prop = new PropertyChange(); - prop.key = "RESOURCE_NAME"; - prop.remove = true; - props.add(prop); - setFailureProperties(props); - new BRMSHandler(INVALIDFILE); - } - - @Test (expected = PolicyException.class) - public void bRMSHandlerFailTest4() throws PolicyException { - PropertyChange prop = new PropertyChange(); - prop.key = "repositoryURL"; - prop.remove = true; - List props = new LinkedList<>(); - props.add(prop); - setFailureProperties(props); - new BRMSHandler(INVALIDFILE); - } - - @Test (expected = PolicyException.class) - public void bRMSHandlerFailTest5() throws PolicyException { - PropertyChange prop = new PropertyChange(); - prop.key = "repositoryName"; - prop.remove = true; - List props = new LinkedList<>(); - props.add(prop); - setFailureProperties(props); - new BRMSHandler(INVALIDFILE); - } - - @Test (expected = PolicyException.class) - public void bRMSHandlerFailTest6() throws PolicyException { - PropertyChange prop = new PropertyChange(); - prop.key = "repositoryURL"; - prop.value = "http://nexus:8081/nexus/content/repositories/releases, http://nexus:8081/nexus/content/repositories/releases"; - prop.remove = false; - List props = new LinkedList<>(); - props.add(prop); - prop = new PropertyChange(); - prop.key = "repositoryUsername"; - prop.remove = true; - props.add(prop); - setFailureProperties(props); - new BRMSHandler(INVALIDFILE); - } - - @Test (expected = PolicyException.class) - public void bRMSHandlerFailTest7() throws PolicyException { - PropertyChange prop = new PropertyChange(); - prop.key = "repositoryPassword"; - prop.remove = true; - List props = new LinkedList<>(); - props.add(prop); - setFailureProperties(props); - new BRMSHandler(INVALIDFILE); - } - - @Test (expected = PolicyException.class) - public void bRMSHandlerFailTest8() throws PolicyException { - PropertyChange prop = new PropertyChange(); - prop.key = "policyKeyID"; - prop.remove = true; - List props = new LinkedList<>(); - props.add(prop); - setFailureProperties(props); - new BRMSHandler(INVALIDFILE); - } - - @Test (expected = PolicyException.class) - public void bRMSHandlerFailTest9() throws PolicyException { - PropertyChange prop = new PropertyChange(); - prop.key = "sync"; - prop.value = "true"; - prop.remove = false; - List props = new LinkedList<>(); - props.add(prop); - prop = new PropertyChange(); - prop.key = "brms.dependency.version"; - prop.remove = true; - props.add(prop); - prop = new PropertyChange(); - prop.key = "groupNames"; - prop.remove = true; - props.add(prop); - setFailureProperties(props); - new BRMSHandler(INVALIDFILE); - } - - @Test (expected = PolicyException.class) - public void bRMSHandlerFailTest10() throws PolicyException { - PropertyChange prop = new PropertyChange(); - prop.key = "groupNames"; - prop.value = ""; - prop.remove = false; - List props = new LinkedList<>(); - props.add(prop); - setFailureProperties(props); - new BRMSHandler(INVALIDFILE); - } - - @Test (expected = PolicyException.class) - public void bRMSHandlerFailTest11() throws PolicyException { - PropertyChange prop = new PropertyChange(); - prop.key = "default.groupID"; - prop.remove = true; - List props = new LinkedList<>(); - props.add(prop); - setFailureProperties(props); - new BRMSHandler(INVALIDFILE); - } - - @Test (expected = PolicyException.class) - public void bRMSHandlerFailTest12() throws PolicyException { - PropertyChange prop = new PropertyChange(); - prop.key = "default.artifactID"; - prop.remove = true; - List props = new LinkedList<>(); - props.add(prop); - setFailureProperties(props); - new BRMSHandler(INVALIDFILE); - } - - @Test (expected = PolicyException.class) - public void bRMSHandlerFailTest13() throws PolicyException { - PropertyChange prop = new PropertyChange(); - prop.key = "NOTIFICATION_TYPE"; - prop.value = "dmaap"; - prop.remove = false; - List props = new LinkedList<>(); - props.add(prop); - prop = new PropertyChange(); - prop.key = "NOTIFICATION_SERVERS"; - prop.remove = true; - props.add(prop); - setFailureProperties(props); - new BRMSHandler(INVALIDFILE); - } - - @Test - public void BRMSHandlerTest() throws PolicyException { - assertNotNull(new BRMSHandler(VALIDFILE)); - } - - private void setFailureProperties(List properties) throws PolicyException { - Properties validProp = new Properties(); - try { - validProp.load(new FileInputStream(VALIDFILE)); - for (PropertyChange prop: properties) { - if(prop.remove) { - validProp.remove(prop.key); - }else { - validProp.setProperty(prop.key, prop.value); - } - } - validProp.store(new FileOutputStream(INVALIDFILE), null); - } catch (IOException e) { - throw new PolicyException(e); - } - } - - class PropertyChange { - public String key = null; - public String value = null; - public Boolean remove = false; - } -} diff --git a/BRMSGateway/src/test/java/org/onap/brmsgw/test/BrmsJpaTest.java b/BRMSGateway/src/test/java/org/onap/brmsgw/test/BrmsJpaTest.java new file mode 100644 index 000000000..32ed314d5 --- /dev/null +++ b/BRMSGateway/src/test/java/org/onap/brmsgw/test/BrmsJpaTest.java @@ -0,0 +1,73 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2018 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.brmsgw.test; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Test; +import org.onap.policy.api.PEDependency; +import org.onap.policy.brms.entity.BrmsGroupInfo; +import org.onap.policy.brms.entity.BrmsPolicyInfo; +import org.onap.policy.brms.entity.DependencyInfo; + +public class BrmsJpaTest { + @Test + public void testJpa() { + final String testVal = "testVal"; + final BrmsGroupInfo groupInfo = new BrmsGroupInfo(); + + // Test group info + groupInfo.setControllerName(testVal); + assertEquals(groupInfo.getControllerName(), testVal); + groupInfo.setGroupId(testVal); + assertEquals(groupInfo.getGroupId(), testVal); + groupInfo.setArtifactId(testVal); + assertEquals(groupInfo.getArtifactId(), testVal); + groupInfo.setVersion(testVal); + assertEquals(groupInfo.getVersion(), testVal); + + // Test policy info + final BrmsPolicyInfo policyInfo = new BrmsPolicyInfo(); + policyInfo.setPolicyName(testVal); + assertEquals(policyInfo.getPolicyName(), testVal); + policyInfo.setControllerName(groupInfo); + assertEquals(policyInfo.getControllerName(), groupInfo); + } + + @Test + public void testDependencyInfo() { + final String testKey = "testKey"; + final PEDependency dependency = new PEDependency(); + final List list = new ArrayList(); + list.add(dependency); + final Map> map = new HashMap>(); + map.put(testKey, list); + final DependencyInfo info = new DependencyInfo(); + + info.setDependencies(map); + assertEquals(info.getDependencies(), map); + } +} diff --git a/BRMSGateway/src/test/java/org/onap/brmsgw/test/BrmsPushTest.java b/BRMSGateway/src/test/java/org/onap/brmsgw/test/BrmsPushTest.java new file mode 100644 index 000000000..36e633638 --- /dev/null +++ b/BRMSGateway/src/test/java/org/onap/brmsgw/test/BrmsPushTest.java @@ -0,0 +1,235 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * 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.brmsgw.test; + +import static org.junit.Assert.assertNotNull; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.LinkedList; +import java.util.List; +import java.util.Properties; + +import org.junit.Test; +import org.onap.policy.api.PolicyException; +import org.onap.policy.brms.api.BrmsHandler; + +public class BrmsPushTest { + + private static final String VALID_FILE = "src/test/resources/config.properties"; + private static final String INVALID_FILE = "src/test/resources/failure.properties"; + + @Test(expected = PolicyException.class) + public void brmsHandlerFailTest() throws PolicyException { + new BrmsHandler(null); + } + + @Test(expected = PolicyException.class) + public void brmsHandlerFailTest1() throws PolicyException { + new BrmsHandler("src/test/resources/filenotexists.txt"); + } + + @Test(expected = PolicyException.class) + public void brmsHandlerFailTest2() throws PolicyException { + final PropertyChange prop = new PropertyChange(); + prop.key = "defaultName"; + prop.remove = true; + final List props = new LinkedList<>(); + props.add(prop); + setFailureProperties(props); + new BrmsHandler(INVALID_FILE); + } + + @Test(expected = PolicyException.class) + public void brmsHandlerFailTest3() throws PolicyException { + PropertyChange prop = new PropertyChange(); + prop.key = "repositoryID"; + prop.remove = true; + final List props = new LinkedList<>(); + props.add(prop); + prop = new PropertyChange(); + prop.key = "RESOURCE_NAME"; + prop.remove = true; + props.add(prop); + setFailureProperties(props); + new BrmsHandler(INVALID_FILE); + } + + @Test(expected = PolicyException.class) + public void brmsHandlerFailTest4() throws PolicyException { + final PropertyChange prop = new PropertyChange(); + prop.key = "repositoryURL"; + prop.remove = true; + final List props = new LinkedList<>(); + props.add(prop); + setFailureProperties(props); + new BrmsHandler(INVALID_FILE); + } + + @Test(expected = PolicyException.class) + public void brmsHandlerFailTest5() throws PolicyException { + final PropertyChange prop = new PropertyChange(); + prop.key = "repositoryName"; + prop.remove = true; + final List props = new LinkedList<>(); + props.add(prop); + setFailureProperties(props); + new BrmsHandler(INVALID_FILE); + } + + @Test(expected = PolicyException.class) + public void brmsHandlerFailTest6() throws PolicyException { + PropertyChange prop = new PropertyChange(); + prop.key = "repositoryURL"; + prop.value = + "http://nexus:8081/nexus/content/repositories/releases, http://nexus:8081/nexus/content/repositories/releases"; + prop.remove = false; + final List props = new LinkedList<>(); + props.add(prop); + prop = new PropertyChange(); + prop.key = "repositoryUsername"; + prop.remove = true; + props.add(prop); + setFailureProperties(props); + new BrmsHandler(INVALID_FILE); + } + + @Test(expected = PolicyException.class) + public void brmsHandlerFailTest7() throws PolicyException { + final PropertyChange prop = new PropertyChange(); + prop.key = "repositoryPassword"; + prop.remove = true; + final List props = new LinkedList<>(); + props.add(prop); + setFailureProperties(props); + new BrmsHandler(INVALID_FILE); + } + + @Test(expected = PolicyException.class) + public void brmsHandlerFailTest8() throws PolicyException { + final PropertyChange prop = new PropertyChange(); + prop.key = "policyKeyID"; + prop.remove = true; + final List props = new LinkedList<>(); + props.add(prop); + setFailureProperties(props); + new BrmsHandler(INVALID_FILE); + } + + @Test(expected = PolicyException.class) + public void brmsHandlerFailTest9() throws PolicyException { + PropertyChange prop = new PropertyChange(); + prop.key = "sync"; + prop.value = "true"; + prop.remove = false; + final List props = new LinkedList<>(); + props.add(prop); + prop = new PropertyChange(); + prop.key = "brms.dependency.version"; + prop.remove = true; + props.add(prop); + prop = new PropertyChange(); + prop.key = "groupNames"; + prop.remove = true; + props.add(prop); + setFailureProperties(props); + new BrmsHandler(INVALID_FILE); + } + + @Test(expected = PolicyException.class) + public void brmsHandlerFailTest10() throws PolicyException { + final PropertyChange prop = new PropertyChange(); + prop.key = "groupNames"; + prop.value = ""; + prop.remove = false; + final List props = new LinkedList<>(); + props.add(prop); + setFailureProperties(props); + new BrmsHandler(INVALID_FILE); + } + + @Test(expected = PolicyException.class) + public void brmsHandlerFailTest11() throws PolicyException { + final PropertyChange prop = new PropertyChange(); + prop.key = "default.groupID"; + prop.remove = true; + final List props = new LinkedList<>(); + props.add(prop); + setFailureProperties(props); + new BrmsHandler(INVALID_FILE); + } + + @Test(expected = PolicyException.class) + public void brmsHandlerFailTest12() throws PolicyException { + final PropertyChange prop = new PropertyChange(); + prop.key = "default.artifactID"; + prop.remove = true; + final List props = new LinkedList<>(); + props.add(prop); + setFailureProperties(props); + new BrmsHandler(INVALID_FILE); + } + + @Test(expected = PolicyException.class) + public void brmsHandlerFailTest13() throws PolicyException { + PropertyChange prop = new PropertyChange(); + prop.key = "NOTIFICATION_TYPE"; + prop.value = "dmaap"; + prop.remove = false; + final List props = new LinkedList<>(); + props.add(prop); + prop = new PropertyChange(); + prop.key = "NOTIFICATION_SERVERS"; + prop.remove = true; + props.add(prop); + setFailureProperties(props); + new BrmsHandler(INVALID_FILE); + } + + @Test + public void brmsHandlerTest() throws PolicyException { + assertNotNull(new BrmsHandler(VALID_FILE)); + } + + private void setFailureProperties(final List properties) throws PolicyException { + final Properties validProp = new Properties(); + try { + validProp.load(new FileInputStream(VALID_FILE)); + for (final PropertyChange prop : properties) { + if (prop.remove) { + validProp.remove(prop.key); + } else { + validProp.setProperty(prop.key, prop.value); + } + } + validProp.store(new FileOutputStream(INVALID_FILE), null); + } catch (final IOException e) { + throw new PolicyException(e); + } + } + + class PropertyChange { + public String key = null; + public String value = null; + public Boolean remove = false; + } +} diff --git a/BRMSGateway/src/test/java/org/onap/brmsgw/test/ControllerPOJOTest.java b/BRMSGateway/src/test/java/org/onap/brmsgw/test/ControllerPOJOTest.java deleted file mode 100644 index 5d736f61d..000000000 --- a/BRMSGateway/src/test/java/org/onap/brmsgw/test/ControllerPOJOTest.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2018 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.brmsgw.test; - -import static org.junit.Assert.assertEquals; -import java.util.HashMap; -import java.util.Map; -import org.junit.Test; -import org.onap.policy.brmsInterface.ControllerPOJO; - -public class ControllerPOJOTest { - @Test - public void testPojo() { - String testKey = "testKey"; - String testVal = "testVal"; - Map testMap = new HashMap(); - testMap.put(testKey, testVal); - ControllerPOJO pojo = new ControllerPOJO(); - - pojo.setName(testVal); - assertEquals(pojo.getName(), testVal); - pojo.setDrools(testMap); - assertEquals(pojo.getDrools(), testMap); - pojo.setOperation(testVal); - assertEquals(pojo.getOperation(), testVal); - } -} diff --git a/BRMSGateway/src/test/java/org/onap/brmsgw/test/ControllerPojoTest.java b/BRMSGateway/src/test/java/org/onap/brmsgw/test/ControllerPojoTest.java new file mode 100644 index 000000000..21534ddcd --- /dev/null +++ b/BRMSGateway/src/test/java/org/onap/brmsgw/test/ControllerPojoTest.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2018 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.brmsgw.test; + +import static org.junit.Assert.assertEquals; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.onap.policy.brms.api.ControllerPojo; + +public class ControllerPojoTest { + @Test + public void testPojo() { + final String testKey = "testKey"; + final String testVal = "testVal"; + final Map testMap = new HashMap(); + testMap.put(testKey, testVal); + final ControllerPojo pojo = new ControllerPojo(); + + pojo.setName(testVal); + assertEquals(pojo.getName(), testVal); + pojo.setDrools(testMap); + assertEquals(pojo.getDrools(), testMap); + pojo.setOperation(testVal); + assertEquals(pojo.getOperation(), testVal); + } +} diff --git a/BRMSGateway/src/test/java/org/onap/brmsgw/test/NotificationPOJOTest.java b/BRMSGateway/src/test/java/org/onap/brmsgw/test/NotificationPOJOTest.java deleted file mode 100644 index ef6585f5d..000000000 --- a/BRMSGateway/src/test/java/org/onap/brmsgw/test/NotificationPOJOTest.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2018 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.brmsgw.test; - -import static org.junit.Assert.assertEquals; -import java.util.ArrayList; -import java.util.List; -import org.junit.Test; -import org.onap.policy.brmsInterface.ControllerPOJO; -import org.onap.policy.brmsInterface.NotificationPOJO; - -public class NotificationPOJOTest { - @Test - public void testPojo() { - String testVal = "testVal"; - ControllerPOJO ctrlPojo = new ControllerPOJO(); - List controllers = new ArrayList(); - controllers.add(ctrlPojo); - NotificationPOJO pojo = new NotificationPOJO(); - - pojo.setRequestID(testVal); - assertEquals(pojo.getRequestID(), testVal); - pojo.setEntity(testVal); - assertEquals(pojo.getEntity(), testVal); - pojo.setControllers(controllers); - assertEquals(pojo.getControllers(), controllers); - } -} diff --git a/BRMSGateway/src/test/java/org/onap/brmsgw/test/NotificationPojoTest.java b/BRMSGateway/src/test/java/org/onap/brmsgw/test/NotificationPojoTest.java new file mode 100644 index 000000000..f83b749f7 --- /dev/null +++ b/BRMSGateway/src/test/java/org/onap/brmsgw/test/NotificationPojoTest.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2018 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.brmsgw.test; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; +import org.onap.policy.brms.api.ControllerPojo; +import org.onap.policy.brms.api.NotificationPojo; + +public class NotificationPojoTest { + @Test + public void testPojo() { + final String testVal = "testVal"; + final ControllerPojo ctrlPojo = new ControllerPojo(); + final List controllers = new ArrayList(); + controllers.add(ctrlPojo); + final NotificationPojo pojo = new NotificationPojo(); + + pojo.setRequestId(testVal); + assertEquals(pojo.getRequestId(), testVal); + pojo.setEntity(testVal); + assertEquals(pojo.getEntity(), testVal); + pojo.setControllers(controllers); + assertEquals(pojo.getControllers(), controllers); + } +} diff --git a/BRMSGateway/src/test/java/org/onap/policy/brms/api/BrmsGatewayTest.java b/BRMSGateway/src/test/java/org/onap/policy/brms/api/BrmsGatewayTest.java new file mode 100644 index 000000000..b3f836fc5 --- /dev/null +++ b/BRMSGateway/src/test/java/org/onap/policy/brms/api/BrmsGatewayTest.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2018 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.brms.api; + +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.any; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +public class BrmsGatewayTest { + @Test + public void testGet() { + assertNull(BrmsGateway.getPolicyEngine()); + } + + @PrepareForTest({Thread.class, BrmsGateway.class}) + @Test + public void testMain() throws Exception { + // Mock Thread + PowerMockito.spy(Thread.class); + PowerMockito.doNothing().when(Thread.class); + Thread.sleep(1000); + + // Mock handler + final BrmsHandler handler = Mockito.mock(BrmsHandler.class); + PowerMockito.whenNew(BrmsHandler.class).withArguments(any()).thenReturn(handler); + + // Run app + try { + final String[] args = null; + BrmsGateway.main(args); + } catch (final Exception ex) { + fail("Not expected an exception: " + ex); + } + } +} diff --git a/BRMSGateway/src/test/java/org/onap/policy/brms/api/BrmsHandlerTest.java b/BRMSGateway/src/test/java/org/onap/policy/brms/api/BrmsHandlerTest.java new file mode 100644 index 000000000..58bacef13 --- /dev/null +++ b/BRMSGateway/src/test/java/org/onap/policy/brms/api/BrmsHandlerTest.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2018 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.brms.api; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.any; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.EntityTransaction; +import javax.persistence.Persistence; +import javax.persistence.Query; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.onap.policy.api.NotificationType; +import org.onap.policy.std.StdPDPNotification; +import org.onap.policy.utils.BackUpMonitor; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +public class BrmsHandlerTest { + @PrepareForTest({Persistence.class, BackUpMonitor.class}) + @Test + public void negativeTestNotifications() throws Exception { + // Mock emf, persistence, and query + final EntityManagerFactory emf = Mockito.mock(EntityManagerFactory.class); + final EntityManager em = Mockito.mock(EntityManager.class); + Mockito.when(emf.createEntityManager()).thenReturn(em); + PowerMockito.mockStatic(Persistence.class); + PowerMockito.when(Persistence.createEntityManagerFactory(any(), any())).thenReturn(emf); + final EntityTransaction et = Mockito.mock(EntityTransaction.class); + Mockito.when(em.getTransaction()).thenReturn(et); + final Query query = Mockito.mock(Query.class); + Mockito.when(em.createQuery(Mockito.anyString())).thenReturn(query); + + // Mock backup monitor + PowerMockito.mockStatic(BackUpMonitor.class); + final BackUpMonitor monitor = Mockito.mock(BackUpMonitor.class); + PowerMockito.when(BackUpMonitor.getInstance(any(), any(), any(), any())).thenReturn(monitor); + + // Test constructor + final StdPDPNotification notification = new StdPDPNotification(); + final String propFile = "config.properties"; + final BrmsHandler handler = new BrmsHandler(propFile); + final BrmsPush brmsPush = new BrmsPush(propFile, handler); + handler.setBrmsPush(brmsPush); + assertNotNull(handler); + assertNotNull(brmsPush); + assertNull(handler.getPolicyEngine()); + + try { + // Test update + notification.setNotificationType(NotificationType.UPDATE); + handler.runOnNotification(notification); + handler.notificationReceived(notification); + + // Test remove + notification.setNotificationType(NotificationType.REMOVE); + handler.runOnNotification(notification); + handler.notificationReceived(notification); + + // Test both + notification.setNotificationType(NotificationType.BOTH); + handler.runOnNotification(notification); + handler.notificationReceived(notification); + } catch (final Exception ex) { + fail("Not expecting an exception: " + ex); + } + } +} diff --git a/BRMSGateway/src/test/java/org/onap/policy/brms/api/BrmsPushTest.java b/BRMSGateway/src/test/java/org/onap/policy/brms/api/BrmsPushTest.java new file mode 100644 index 000000000..2b13640d2 --- /dev/null +++ b/BRMSGateway/src/test/java/org/onap/policy/brms/api/BrmsPushTest.java @@ -0,0 +1,125 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2018 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.brms.api; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.any; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.EntityTransaction; +import javax.persistence.Persistence; +import javax.persistence.Query; + +import org.apache.maven.model.Dependency; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.onap.policy.api.PolicyException; +import org.onap.policy.utils.BackUpHandler; +import org.onap.policy.utils.BackUpMonitor; +import org.onap.policy.utils.BackUpMonitorException; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +public class BrmsPushTest { + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @PrepareForTest({Persistence.class, BackUpMonitor.class}) + @Test + public void testPush() throws BackUpMonitorException, PolicyException { + // Mock emf, persistence, and query + final EntityManagerFactory emf = Mockito.mock(EntityManagerFactory.class); + final EntityManager em = Mockito.mock(EntityManager.class); + Mockito.when(emf.createEntityManager()).thenReturn(em); + PowerMockito.mockStatic(Persistence.class); + PowerMockito.when(Persistence.createEntityManagerFactory(Mockito.any(), Mockito.any())).thenReturn(emf); + final EntityTransaction et = Mockito.mock(EntityTransaction.class); + Mockito.when(em.getTransaction()).thenReturn(et); + final Query query = Mockito.mock(Query.class); + Mockito.when(em.createQuery(Mockito.anyString())).thenReturn(query); + + // Mock backup monitor + PowerMockito.mockStatic(BackUpMonitor.class); + final BackUpMonitor monitor = Mockito.mock(BackUpMonitor.class); + PowerMockito.when(BackUpMonitor.getInstance(any(), any(), any(), any())).thenReturn(monitor); + + // Test constructor + final String propFile = "config.properties"; + final BackUpHandler handler = Mockito.mock(BackUpHandler.class); + final BrmsPush push = new BrmsPush(propFile, handler); + assertNotNull(push); + + final String name = "testName"; + try { + // Test initiate + push.initiate(true); + + // Test reset + push.resetDs(); + + // Test add + final String rule = "testRule"; + final Map responseAttributes = new HashMap(); + responseAttributes.put("$controller:", "{\n\"testKey\": \"testVal\"\n}\n"); + responseAttributes.put("$dependency$", "[a,b]"); + push.addRule(name, rule, responseAttributes); + } catch (final Exception ex) { + fail("Not expecting an exception: " + ex); + } + + try { + // Test remove + push.removeRule(name); + } catch (final Exception ex) { + fail("Not expecting an exception: " + ex); + + } + + // Test misc methods + final String controllerName = "testController"; + final List deps = push.defaultDependencies(controllerName); + assertEquals(deps.size(), 7); + assertNotNull(BrmsPush.getBackUpMonitor()); + assertEquals(push.urlListSize(), 1); + + try { + push.rotateUrls(); + } catch (final Exception ex) { + fail("Not expecting an exception: " + ex); + } + + // Test push + thrown.expect(PolicyException.class); + push.pushRules(); + } +} diff --git a/BRMSGateway/src/test/java/org/onap/policy/brmsInterface/BRMSGatewayTest.java b/BRMSGateway/src/test/java/org/onap/policy/brmsInterface/BRMSGatewayTest.java deleted file mode 100644 index e0b38b666..000000000 --- a/BRMSGateway/src/test/java/org/onap/policy/brmsInterface/BRMSGatewayTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2018 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.brmsInterface; - -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; -import static org.mockito.Matchers.any; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -@RunWith(PowerMockRunner.class) -public class BRMSGatewayTest { - @Test - public void testGet() { - assertNull(BRMSGateway.getPolicyEngine()); - } - - @PrepareForTest({Thread.class, BRMSGateway.class}) - @Test - public void testMain() throws Exception { - // Mock Thread - PowerMockito.spy(Thread.class); - PowerMockito.doNothing().when(Thread.class); - Thread.sleep(1000); - - // Mock handler - BRMSHandler handler = Mockito.mock(BRMSHandler.class); - PowerMockito.whenNew(BRMSHandler.class).withArguments(any()).thenReturn(handler); - - // Run app - try { - String[] args = null; - BRMSGateway.main(args); - } - catch (Exception ex) { - fail("Not expected an exception: " + ex); - } - } -} diff --git a/BRMSGateway/src/test/java/org/onap/policy/brmsInterface/BRMSHandlerTest.java b/BRMSGateway/src/test/java/org/onap/policy/brmsInterface/BRMSHandlerTest.java deleted file mode 100644 index 8e15cdf28..000000000 --- a/BRMSGateway/src/test/java/org/onap/policy/brmsInterface/BRMSHandlerTest.java +++ /dev/null @@ -1,93 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2018 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.brmsInterface; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; -import static org.mockito.Matchers.any; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.EntityTransaction; -import javax.persistence.Persistence; -import javax.persistence.Query; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.onap.policy.api.NotificationType; -import org.onap.policy.std.StdPDPNotification; -import org.onap.policy.utils.BackUpMonitor; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -@RunWith(PowerMockRunner.class) -public class BRMSHandlerTest { - @PrepareForTest({Persistence.class, BackUpMonitor.class}) - @Test - public void negativeTestNotifications() throws Exception { - // Mock emf, persistence, and query - EntityManagerFactory emf = Mockito.mock(EntityManagerFactory.class); - EntityManager em = Mockito.mock(EntityManager.class); - Mockito.when(emf.createEntityManager()).thenReturn(em); - PowerMockito.mockStatic(Persistence.class); - PowerMockito.when(Persistence.createEntityManagerFactory(any(), any())).thenReturn(emf); - EntityTransaction et = Mockito.mock(EntityTransaction.class); - Mockito.when(em.getTransaction()).thenReturn(et); - Query query = Mockito.mock(Query.class); - Mockito.when(em.createQuery(Mockito.anyString())).thenReturn(query); - - // Mock backup monitor - PowerMockito.mockStatic(BackUpMonitor.class); - BackUpMonitor monitor = Mockito.mock(BackUpMonitor.class); - PowerMockito.when(BackUpMonitor.getInstance(any(), any(), any(), any())).thenReturn(monitor); - - // Test constructor - StdPDPNotification notification = new StdPDPNotification(); - String propFile = "config.properties"; - BRMSHandler handler = new BRMSHandler(propFile); - BRMSPush brmsPush = new BRMSPush(propFile, handler); - handler.setBRMSPush(brmsPush); - assertNotNull(handler); - assertNotNull(brmsPush); - assertNull(handler.getPolicyEngine()); - - try { - // Test update - notification.setNotificationType(NotificationType.UPDATE); - handler.runOnNotification(notification); - handler.notificationReceived(notification); - - // Test remove - notification.setNotificationType(NotificationType.REMOVE); - handler.runOnNotification(notification); - handler.notificationReceived(notification); - - // Test both - notification.setNotificationType(NotificationType.BOTH); - handler.runOnNotification(notification); - handler.notificationReceived(notification); - } - catch (Exception ex) { - fail("Not expecting an exception: " + ex); - } - } -} diff --git a/BRMSGateway/src/test/java/org/onap/policy/brmsInterface/BRMSPushTest.java b/BRMSGateway/src/test/java/org/onap/policy/brmsInterface/BRMSPushTest.java deleted file mode 100644 index 5ca2b309c..000000000 --- a/BRMSGateway/src/test/java/org/onap/policy/brmsInterface/BRMSPushTest.java +++ /dev/null @@ -1,125 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy Engine - * ================================================================================ - * Copyright (C) 2018 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.brmsInterface; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; -import static org.mockito.Matchers.any; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.EntityTransaction; -import javax.persistence.Persistence; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.onap.policy.api.PolicyException; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.onap.policy.utils.BackUpHandler; -import org.onap.policy.utils.BackUpMonitor; -import org.onap.policy.utils.BackUpMonitorException; -import org.apache.maven.model.Dependency; -import javax.persistence.Query; - -@RunWith(PowerMockRunner.class) -public class BRMSPushTest { - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @PrepareForTest({Persistence.class, BackUpMonitor.class}) - @Test - public void testPush() throws BackUpMonitorException, PolicyException { - // Mock emf, persistence, and query - EntityManagerFactory emf = Mockito.mock(EntityManagerFactory.class); - EntityManager em = Mockito.mock(EntityManager.class); - Mockito.when(emf.createEntityManager()).thenReturn(em); - PowerMockito.mockStatic(Persistence.class); - PowerMockito.when(Persistence.createEntityManagerFactory(Mockito.any(), Mockito.any())).thenReturn(emf); - EntityTransaction et = Mockito.mock(EntityTransaction.class); - Mockito.when(em.getTransaction()).thenReturn(et); - Query query = Mockito.mock(Query.class); - Mockito.when(em.createQuery(Mockito.anyString())).thenReturn(query); - - // Mock backup monitor - PowerMockito.mockStatic(BackUpMonitor.class); - BackUpMonitor monitor = Mockito.mock(BackUpMonitor.class); - PowerMockito.when(BackUpMonitor.getInstance(any(), any(), any(), any())).thenReturn(monitor); - - // Test constructor - String propFile = "config.properties"; - BackUpHandler handler = Mockito.mock(BackUpHandler.class); - BRMSPush push = new BRMSPush(propFile, handler); - assertNotNull(push); - - String name = "testName"; - try { - // Test initiate - push.initiate(true); - - // Test reset - push.resetDS(); - - // Test add - String rule = "testRule"; - Map responseAttributes = new HashMap(); - responseAttributes.put("$controller:", "{\n\"testKey\": \"testVal\"\n}\n"); - responseAttributes.put("$dependency$", "[a,b]"); - push.addRule(name, rule, responseAttributes); - } - catch (Exception ex) { - fail("Not expecting an exception: " + ex); - } - - try { - // Test remove - push.removeRule(name); - } - catch (Exception ex) { - fail("Not expecting an exception: " + ex); - - } - - // Test misc methods - String controllerName = "testController"; - List deps = push.defaultDependencies(controllerName); - assertEquals(deps.size(), 7); - assertNotNull(BRMSPush.getBackUpMonitor()); - assertEquals(push.urlListSize(), 1); - - try { - push.rotateURLs(); - } - catch (Exception ex) { - fail("Not expecting an exception: " + ex); - } - - // Test push - thrown.expect(PolicyException.class); - push.pushRules(); - } -} diff --git a/BRMSGateway/src/test/resources/META-INF/persistenceBRMStest.xml b/BRMSGateway/src/test/resources/META-INF/persistenceBRMStest.xml index f757aca86..62ae4d058 100644 --- a/BRMSGateway/src/test/resources/META-INF/persistenceBRMStest.xml +++ b/BRMSGateway/src/test/resources/META-INF/persistenceBRMStest.xml @@ -24,8 +24,8 @@ xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> org.eclipse.persistence.jpa.PersistenceProvider - org.onap.policy.brmsInterface.jpa.BRMSGroupInfo - org.onap.policy.brmsInterface.jpa.BRMSPolicyInfo + org.onap.policy.brms.entity.BrmsGroupInfo + org.onap.policy.brms.entity.BrmsPolicyInfo