2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.brmsInterface;
24 import java.io.FileInputStream;
25 import java.io.FileOutputStream;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.Writer;
30 import java.nio.channels.Channels;
31 import java.nio.channels.ReadableByteChannel;
32 import java.nio.charset.StandardCharsets;
33 import java.nio.file.Files;
34 import java.nio.file.Path;
35 import java.nio.file.Paths;
36 import java.security.GeneralSecurityException;
37 import java.util.ArrayList;
38 import java.util.Arrays;
39 import java.util.Collections;
40 import java.util.Enumeration;
41 import java.util.HashMap;
42 import java.util.List;
44 import java.util.Properties;
45 import java.util.UUID;
46 import java.util.concurrent.TimeUnit;
47 import java.util.jar.JarEntry;
48 import java.util.jar.JarFile;
50 import javax.persistence.EntityManager;
51 import javax.persistence.EntityManagerFactory;
52 import javax.persistence.EntityTransaction;
53 import javax.persistence.Persistence;
54 import javax.persistence.Query;
56 import org.apache.commons.io.FileUtils;
57 import org.apache.commons.lang.StringEscapeUtils;
58 import org.apache.maven.model.Dependency;
59 import org.apache.maven.model.DeploymentRepository;
60 import org.apache.maven.model.DistributionManagement;
61 import org.apache.maven.model.Model;
62 import org.apache.maven.model.io.xpp3.MavenXpp3Writer;
63 import org.apache.maven.shared.invoker.DefaultInvocationRequest;
64 import org.apache.maven.shared.invoker.DefaultInvoker;
65 import org.apache.maven.shared.invoker.InvocationRequest;
66 import org.apache.maven.shared.invoker.InvocationResult;
67 import org.apache.maven.shared.invoker.Invoker;
68 import org.codehaus.plexus.util.IOUtil;
69 import org.codehaus.plexus.util.WriterFactory;
70 import org.eclipse.persistence.config.PersistenceUnitProperties;
71 import org.onap.policy.api.PEDependency;
72 import org.onap.policy.api.PolicyException;
73 import org.onap.policy.brmsInterface.jpa.BRMSGroupInfo;
74 import org.onap.policy.brmsInterface.jpa.BRMSPolicyInfo;
75 import org.onap.policy.brmsInterface.jpa.DependencyInfo;
76 import org.onap.policy.common.im.AdministrativeStateException;
77 import org.onap.policy.common.im.IntegrityMonitor;
78 import org.onap.policy.common.logging.eelf.MessageCodes;
79 import org.onap.policy.common.logging.eelf.PolicyLogger;
80 import org.onap.policy.common.logging.flexlogger.FlexLogger;
81 import org.onap.policy.common.logging.flexlogger.Logger;
82 import org.onap.policy.utils.BackUpHandler;
83 import org.onap.policy.utils.BackUpMonitor;
84 import org.onap.policy.utils.BusPublisher;
85 import org.onap.policy.utils.PolicyUtils;
86 import org.onap.policy.xacml.api.XACMLErrorConstants;
87 import org.sonatype.nexus.client.NexusClient;
88 import org.sonatype.nexus.client.NexusClientException;
89 import org.sonatype.nexus.client.NexusConnectionException;
90 import org.sonatype.nexus.client.rest.NexusRestClient;
91 import org.sonatype.nexus.rest.model.NexusArtifact;
93 import com.att.nsa.cambria.client.CambriaBatchingPublisher;
94 import com.att.nsa.cambria.client.CambriaClientBuilders;
95 import com.att.nsa.cambria.client.CambriaClientBuilders.PublisherBuilder;
96 import com.fasterxml.jackson.core.JsonProcessingException;
99 * BRMSPush: Application responsible to push policies to the BRMS PDP Policy Repository (PR). Mavenize and push policy
105 @SuppressWarnings("deprecation")
106 public class BRMSPush {
107 private static final Logger LOGGER = FlexLogger.getLogger(BRMSPush.class.getName());
108 private static final String PROJECTSLOCATION = "RuleProjects";
109 private static final String[] GOALS = { "clean", "deploy" };
110 private static final String DEFAULT_VERSION = "1.1.0-SNAPSHOT";
111 private static final String DEPENDENCY_FILE = "dependency.json";
113 private static Map<String, String> modifiedGroups = new HashMap<>();
114 private static IntegrityMonitor im;
115 private static BackUpMonitor bm;
116 private String defaultName = null;
117 private String repID = null;
118 private String repName = null;
119 private ArrayList<String> repURLs = null;
120 private String repUserName = null;
121 private String repPassword = null;
122 private String policyKeyID = null;
123 private boolean createFlag = false;
124 private String uebList = null;
125 private List<String> dmaapList = null;
126 private String pubTopic = null;
127 private PublisherBuilder pubBuilder = null;
128 protected BusPublisher publisher = null;
129 private Long uebDelay = Long.parseLong("20");
130 private Long dmaapDelay = Long.parseLong("5000");
131 private String notificationType = null;
132 private ArrayList<ControllerPOJO> controllers;
133 private HashMap<String, ArrayList<Object>> groupMap = new HashMap<>();
134 private Map<String, String> policyMap = new HashMap<>();
135 private String brmsdependencyversion;
136 private EntityManager em;
137 private boolean syncFlag = false;
139 public BRMSPush(String propertiesFile, BackUpHandler handler) throws PolicyException {
140 if(propertiesFile==null || handler==null){
141 throw new PolicyException("Error no propertiesFile or handler");
143 Properties config = new Properties();
144 Path file = Paths.get(propertiesFile);
145 if (Files.notExists(file)) {
146 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Config File doesn't Exist in the specified Path "
148 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
149 + "Config File doesn't Exist in the specified Path " + file.toString());
151 if (file.toString().endsWith(".properties")) {
152 // Grab the Properties.
153 setProperty(file, config, handler);
158 private void setProperty(Path file, Properties config, BackUpHandler handler) throws PolicyException {
161 in = new FileInputStream(file.toFile());
163 } catch (IOException e) {
165 XACMLErrorConstants.ERROR_DATA_ISSUE + "Data/File Read Error while reading from the property file.",
167 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
168 + "Data/File Read Error while reading from the property file.");
170 LOGGER.info("Trying to set up IntegrityMonitor");
171 String resourceName = null;
173 LOGGER.info("Trying to set up IntegrityMonitor");
174 resourceName = config.getProperty("RESOURCE_NAME");
175 if (resourceName == null) {
176 LOGGER.warn("RESOURCE_NAME is missing setting default value. ");
177 resourceName = "brmsgw_pdp01";
179 resourceName = resourceName.trim();
180 setIntegrityMonitor(IntegrityMonitor.getInstance(resourceName, config));
181 } catch (Exception e) {
182 LOGGER.error("Error starting Integerity Monitor: " + e);
184 LOGGER.info("Trying to set up BackUpMonitor");
186 setBackupMonitor(BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), resourceName, config,
188 } catch (Exception e) {
189 LOGGER.error("Error starting BackUpMonitor: " + e);
191 if(!config.containsKey(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML)){
192 config.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, "META-INF/persistenceBRMS.xml");
194 EntityManagerFactory emf = Persistence.createEntityManagerFactory("BRMSGW", config);
195 em = emf.createEntityManager();
196 defaultName = config.getProperty("defaultName");
197 if (defaultName == null) {
199 XACMLErrorConstants.ERROR_DATA_ISSUE + "defaultName property is missing from the property file ");
200 throw new PolicyException(
201 XACMLErrorConstants.ERROR_DATA_ISSUE + "defaultName property is missing from the property file");
203 defaultName = defaultName.trim();
204 repID = config.getProperty("repositoryID");
207 XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryID property is missing from the property file ");
208 throw new PolicyException(
209 XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryID property is missing from the property file ");
211 repID = repID.trim();
212 repName = config.getProperty("repositoryName");
213 if (repName == null) {
214 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
215 + "repositoryName property is missing from the property file ");
216 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
217 + "repositoryName property is missing from the property file ");
219 repName = repName.trim();
220 String repURL = config.getProperty("repositoryURL");
221 if (repURL == null) {
223 XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryURL property is missing from the property file ");
224 throw new PolicyException(
225 XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryURL property is missing from the property file ");
227 if (repURL.contains(",")) {
228 repURLs = new ArrayList<>(Arrays.asList(repURL.trim().split(",")));
230 repURLs = new ArrayList<>();
233 repUserName = config.getProperty("repositoryUsername");
234 repPassword = config.getProperty("repositoryPassword");
235 if (repUserName == null || repPassword == null) {
236 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
237 + "repostoryUserName and respositoryPassword properties are required.");
238 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
239 + "repostoryUserName and respositoryPassword properties are required.");
241 repUserName = repUserName.trim();
242 repPassword = repPassword.trim();
243 policyKeyID = config.getProperty("policyKeyID");
244 if (policyKeyID == null) {
246 XACMLErrorConstants.ERROR_DATA_ISSUE + "policyKeyID property is missing from the property file ");
247 throw new PolicyException(
248 XACMLErrorConstants.ERROR_DATA_ISSUE + "policyKeyID property is missing from the property file ");
250 policyKeyID = policyKeyID.trim();
251 String syncF = config.getProperty("sync", "false").trim();
252 syncFlag = Boolean.parseBoolean(syncF);
254 PolicyLogger.info("SYNC Flag is turned ON. DB will be given Priority.");
256 brmsdependencyversion = config.getProperty("brms.dependency.version");
257 if (brmsdependencyversion == null) {
258 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
259 + "brmsdependencyversion property is missing from the property file, Using default Version.");
260 brmsdependencyversion = DEFAULT_VERSION;
262 brmsdependencyversion = brmsdependencyversion.trim();
266 notificationType = config.getProperty("NOTIFICATION_TYPE");
267 if ("dmaap".equalsIgnoreCase(notificationType)) {
269 LOGGER.info("Notification Type being used is DMaaP... creating instance of BusPublisher.");
270 // Setting up the Publisher for DMaaP MR
271 String dmaapServers = config.getProperty("NOTIFICATION_SERVERS");
272 pubTopic = config.getProperty("NOTIFICATION_TOPIC");
273 String aafLogin = config.getProperty("CLIENT_ID").trim();
274 String aafPassword = config.getProperty("CLIENT_KEY").trim();
276 if (dmaapServers == null || pubTopic == null) {
278 XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file ");
279 throw new PolicyException(
280 XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file ");
283 dmaapServers = dmaapServers.trim();
284 pubTopic = pubTopic.trim();
286 if (dmaapServers.contains(",")) {
287 dmaapList = new ArrayList<>(Arrays.asList(dmaapServers.split("\\s*,\\s*")));
289 dmaapList = new ArrayList<>();
290 dmaapList.add(dmaapServers);
293 this.publisher = new BusPublisher.DmaapPublisherWrapper(this.dmaapList, this.pubTopic, aafLogin,
296 String dDelay = config.getProperty("NOTIFICATION_DELAY");
297 if (dDelay != null && !dDelay.isEmpty()) {
298 dDelay = dDelay.trim();
300 dmaapDelay = Long.parseLong(dDelay);
301 } catch (NumberFormatException e) {
302 LOGGER.error("DMAAP_DELAY not a long format number" + e);
305 LOGGER.info("DMAAP BusPublisher is created.");
308 LOGGER.info("Notification Type being used is UEB... creating instance of PublisherBuilder.");
309 // Setting up the Publisher for UEB
310 uebList = config.getProperty("NOTIFICATION_SERVERS");
311 pubTopic = config.getProperty("NOTIFICATION_TOPIC");
312 String apiKey = config.getProperty("UEB_API_KEY");
313 String apiSecret = config.getProperty("UEB_API_SECRET");
314 if (uebList == null || pubTopic == null) {
316 XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file ");
317 throw new PolicyException(
318 XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file ");
320 uebList = uebList.trim();
321 pubTopic = pubTopic.trim();
322 pubBuilder = new CambriaClientBuilders.PublisherBuilder();
323 pubBuilder.usingHosts(uebList).onTopic(pubTopic);
324 if (apiKey != null && !apiKey.isEmpty() && apiSecret != null && !apiSecret.isEmpty()) {
325 apiKey = apiKey.trim();
326 apiSecret = apiSecret.trim();
327 pubBuilder.authenticatedBy(apiKey, apiSecret);
329 String uDelay = config.getProperty("NOTIFICATION_DELAY");
330 if (uDelay != null && !uDelay.isEmpty()) {
331 uDelay = uDelay.trim();
333 uebDelay = Long.parseLong(uDelay);
334 } catch (NumberFormatException e) {
335 LOGGER.error("UEB_DELAY not a long format number" + e);
338 LOGGER.info("UEB PublisherBuilder is created.");
344 private static void setBackupMonitor(BackUpMonitor instance) {
348 private static void setIntegrityMonitor(IntegrityMonitor instance) {
353 * Will Initialize the variables required for BRMSPush.
355 public void initiate(boolean flag) {
356 resetModifiedGroups();
357 controllers = new ArrayList<>();
359 bm.updateNotification();
360 } catch (Exception e) {
361 LOGGER.error("Error while updating Notification: " + e.getMessage(), e);
367 private static void resetModifiedGroups() {
368 modifiedGroups = new HashMap<>();
372 * Will Add rules to projects. Creates necessary folders if required.
374 public void addRule(String name, String rule, Map<String, String> responseAttributes) {
375 // 1 check the response Attributes and determine if this belongs to any projects.
376 // 2 if not create folder
379 // 5 store the groups that have been updated.
380 String kSessionName = null;
381 String selectedName = null;
382 if (!responseAttributes.isEmpty()) {
383 // Pick selected Value
384 String userControllerName = null;
385 ArrayList<PEDependency> userDependencies = new ArrayList<>();
386 for (String key : responseAttributes.keySet()) {
387 if (key.equals(policyKeyID)) {
388 selectedName = responseAttributes.get(key);
390 // kmodule configurations
391 else if (key.equals("kSessionName")) {
392 kSessionName = responseAttributes.get(key);
394 // Check User Specific values.
395 if (key.equals("$controller:")) {
397 PEDependency dependency = PolicyUtils.jsonStringToObject(responseAttributes.get(key),
399 userControllerName = key.replaceFirst("$controller:", "");
400 addToGroup(userControllerName, dependency);
401 } catch (Exception e) {
402 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while resolving Controller: " + e);
405 } else if (key.equals("$dependency$")) {
406 String value = responseAttributes.get(key);
407 if (value.startsWith("[") && value.endsWith("]")) {
408 value = value.substring(1, value.length() - 1).trim();
409 List<String> dependencyStrings = Arrays.asList(value.split("},{"));
410 for (String dependencyString : dependencyStrings) {
413 .add(PolicyUtils.jsonStringToObject(dependencyString, PEDependency.class));
414 } catch (Exception e) {
415 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
416 + "Error while resolving Dependencies: " + e);
422 if (userControllerName != null) {
423 // Adding custom dependencies here.
424 ArrayList<Object> values = groupMap.get(userControllerName);
425 values.add(userDependencies);
426 groupMap.put(userControllerName, values);
427 selectedName = userControllerName;
430 // If no Match then pick Default.
431 if (selectedName == null) {
432 selectedName = defaultName;
434 if (groupMap.containsKey(selectedName)) {
435 // If the key is not got as parameters set by the user, setting the default value for kSessionName as
437 if (kSessionName == null) {
438 if (selectedName == defaultName) {
439 kSessionName = "closedloop";
441 kSessionName = "closedloop-" + selectedName;
444 // create directories if missing.
445 manageProject(selectedName, kSessionName, name, rule);
446 addModifiedGroup(selectedName, "update"); // Will check for Create Later after generating the Pom.
450 private void syncGroupInfo() {
451 // Sync DB to JMemory.
452 EntityTransaction et = em.getTransaction();
454 Query query = em.createQuery("select b from BRMSGroupInfo AS b");
455 List<?> bList = query.getResultList();
456 if (bList.size() != groupMap.size()) {
457 for (Object value : bList) {
458 BRMSGroupInfo brmsGroupInfo = (BRMSGroupInfo) value;
459 PEDependency dependency = new PEDependency();
460 dependency.setArtifactId(brmsGroupInfo.getArtifactId());
461 dependency.setGroupId(brmsGroupInfo.getGroupId());
462 dependency.setVersion(brmsGroupInfo.getVersion());
463 ArrayList<Object> values = new ArrayList<>();
464 values.add(dependency);
465 groupMap.put(brmsGroupInfo.getControllerName(), values);
468 query = em.createQuery("select g from BRMSPolicyInfo AS g");
469 bList = query.getResultList();
470 if (bList.size() != policyMap.size()) {
471 for (Object value : bList) {
472 BRMSPolicyInfo brmsPolicyInfo = (BRMSPolicyInfo) value;
473 policyMap.put(brmsPolicyInfo.getPolicyName(), brmsPolicyInfo.getControllerName().getControllerName());
477 LOGGER.info("Updated Local Memory values with values from database.");
480 private void manageProject(String selectedName, String kSessionName, String name, String rule) {
481 // Check if the Project is in Sync. If not get the latest Version.
482 syncProject(selectedName);
483 createProject(PROJECTSLOCATION + File.separator + getArtifactID(selectedName) + File.separator + "src"
484 + File.separator + "main" + File.separator + "resources", kSessionName);
485 copyDataToFile(PROJECTSLOCATION + File.separator + getArtifactID(selectedName) + File.separator + "src"
486 + File.separator + "main" + File.separator + "resources" + File.separator + "rules" + File.separator
487 + name + ".drl", rule);
488 addToPolicy(name, selectedName);
492 * Add Policy to JMemory and DataBase.
494 private void addToPolicy(String policyName, String controllerName) {
495 policyMap.put(policyName, controllerName);
496 EntityTransaction et = em.getTransaction();
498 Query query = em.createQuery("select b from BRMSPolicyInfo as b where b.policyName = :pn");
499 query.setParameter("pn", policyName);
500 List<?> pList = query.getResultList();
501 boolean createFlag = false;
502 BRMSPolicyInfo brmsPolicyInfo = new BRMSPolicyInfo();
503 if (pList.size() > 0) {
505 brmsPolicyInfo = (BRMSPolicyInfo) pList.get(0);
506 if (!brmsPolicyInfo.getControllerName().getControllerName().equals(controllerName)) {
513 query = em.createQuery("select b from BRMSGroupInfo as b where b.controllerName = :cn");
514 query.setParameter("cn", controllerName);
515 List<?> bList = query.getResultList();
516 BRMSGroupInfo brmsGroupInfo = new BRMSGroupInfo();
517 if (bList.size() > 0) {
518 brmsGroupInfo = (BRMSGroupInfo) bList.get(0);
520 brmsPolicyInfo.setPolicyName(policyName);
521 brmsPolicyInfo.setControllerName(brmsGroupInfo);
522 em.persist(brmsPolicyInfo);
528 private void syncProject(String selectedName) {
529 boolean projectExists = checkProject(selectedName);
531 String version = null;
532 version = getVersion(selectedName);
533 if (version == null) {
534 LOGGER.error("Error getting local version for the given Controller Name:" + selectedName
535 + " going with Default value");
538 String nextVersion = incrementVersion(version);
539 boolean outOfSync = checkRemoteSync(selectedName, nextVersion);
544 // We are out of Sync or Project is not Present.
545 downloadProject(selectedName);
548 private void downloadProject(String selectedName) {
549 NexusArtifact artifact = getLatestArtifactFromNexus(selectedName);
550 if (artifact == null)
552 String dirName = getDirectoryName(selectedName);
554 String fileName = "rule.jar";
556 website = new URL(artifact.getResourceURI());
557 ReadableByteChannel rbc = Channels.newChannel(website.openStream());
558 FileOutputStream fos = new FileOutputStream(fileName);
559 fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
561 extractJar(fileName, dirName);
562 new File(fileName).delete();
563 } catch (IOException e) {
564 LOGGER.error("Error while downloading the project to File System. " + e.getMessage(), e);
568 private void extractJar(String jarFileName, String artifactId) throws IOException {
569 JarFile jar = new JarFile(jarFileName);
570 Enumeration<?> enumEntries = jar.entries();
571 while (enumEntries.hasMoreElements()) {
572 JarEntry file = (JarEntry) enumEntries.nextElement();
574 String fileName = file.getName().substring(file.getName().lastIndexOf("/") + 1);
575 if (file.getName().endsWith(".drl")) {
576 String path = PROJECTSLOCATION + File.separator + artifactId + File.separator + "src" + File.separator
577 + "main" + File.separator + "resources" + File.separator + "rules";
578 new File(path).mkdirs();
579 if (syncFlag && policyMap.containsKey(fileName.replace(".drl", ""))) {
580 f = new File(path + File.separator + fileName);
582 f = new File(path + File.separator + fileName);
584 } else if (file.getName().endsWith("pom.xml")) {
585 String path = PROJECTSLOCATION + File.separator + artifactId;
586 new File(path).mkdirs();
587 f = new File(path + File.separator + fileName);
588 } else if (file.getName().endsWith("kmodule.xml")) {
589 String path = PROJECTSLOCATION + File.separator + artifactId + File.separator + "src" + File.separator
590 + "main" + File.separator + "resources" + File.separator + "META-INF";
591 new File(path).mkdirs();
592 f = new File(path + File.separator + fileName);
595 InputStream is = jar.getInputStream(file);
596 FileOutputStream fos = new FileOutputStream(f);
597 while (is.available() > 0) {
598 fos.write(is.read());
603 LOGGER.info(fileName + " Created..");
609 private NexusArtifact getLatestArtifactFromNexus(String selectedName) {
610 List<NexusArtifact> artifacts = getArtifactFromNexus(selectedName, null);
613 NexusArtifact result = null;
614 for (NexusArtifact artifact : artifacts) {
615 int majorVal = Integer.parseInt(artifact.getVersion().substring(0, artifact.getVersion().indexOf(".")));
616 int minorVal = Integer.parseInt(artifact.getVersion().substring(artifact.getVersion().indexOf(".") + 1,
617 artifact.getVersion().lastIndexOf(".")));
618 if (majorVal > bigNum) {
622 if ((bigNum == majorVal) && (minorVal > smallNum)) {
625 if (bigNum == majorVal && minorVal == smallNum) {
629 return additionalNexusLatestCheck(selectedName, result);
632 // Additional Check due to Limitations from Nexus API to check if the artifact is the latest.
633 private NexusArtifact additionalNexusLatestCheck(String selectedName, NexusArtifact result) {
637 String nextVersion = incrementVersion(result.getVersion());
638 List<NexusArtifact> artifact = getArtifactFromNexus(selectedName, nextVersion);
639 return artifact.isEmpty() ? result : additionalNexusLatestCheck(selectedName, artifact.get(0));
642 private boolean checkRemoteSync(String selectedName, String version) {
643 List<NexusArtifact> artifacts = getArtifactFromNexus(selectedName, version);
644 return (artifacts.size() == 0) ? false : true;
647 private List<NexusArtifact> getArtifactFromNexus(String selectedName, String version) {
648 final NexusClient client = new NexusRestClient();
650 boolean flag = false;
651 while (i < repURLs.size()) {
653 String repURL = repURLs.get(0);
654 client.connect(repURL.substring(0, repURL.indexOf(repURL.split(":[0-9]+\\/nexus")[1])), repUserName,
656 final NexusArtifact template = new NexusArtifact();
657 template.setGroupId(getGroupID(selectedName));
658 template.setArtifactId(getArtifactID(selectedName));
659 if (version != null) {
660 template.setVersion(version);
662 List<NexusArtifact> resultList = client.searchByGAV(template);
663 if (resultList != null) {
667 } catch (NexusClientException | NexusConnectionException | NullPointerException e) {
668 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Connection to remote Nexus has failed. "
669 + e.getMessage(), e);
673 } catch (NexusClientException | NexusConnectionException e) {
674 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "failed to disconnect Connection from Nexus."
675 + e.getMessage(), e);
678 Collections.rotate(repURLs, -1);
683 return new ArrayList<>();
686 private void setVersion(String selectedName) {
687 String newVersion = "0.1.0";
689 NexusArtifact artifact = getLatestArtifactFromNexus(selectedName);
690 if (artifact != null) {
691 newVersion = incrementVersion(artifact.getVersion());
693 if (newVersion.equals("0.1.0")) {
696 setVersion(newVersion, selectedName);
697 LOGGER.info("Controller: " + selectedName + "is on version: " + newVersion);
700 private String incrementVersion(String version) {
701 int majorVal = Integer.parseInt(version.substring(0, version.indexOf(".")));
702 int minorVal = Integer.parseInt(version.substring(version.indexOf(".") + 1, version.lastIndexOf(".")));
709 return majorVal + "." + minorVal + version.substring(version.lastIndexOf("."));
712 private boolean checkProject(String selectedName) {
713 return new File(PROJECTSLOCATION + File.separator + getDirectoryName(selectedName)).exists();
716 private String getDirectoryName(String selectedName) {
717 return getArtifactID(selectedName);
721 * Will Push policies to the PolicyRepo.
723 * @param notificationType
724 * <String> type of notification Type.
725 * @throws PolicyException
727 public void pushRules() throws PolicyException {
728 // Check how many groups have been updated.
729 // Invoke their Maven process.
731 im.startTransaction();
732 } catch (AdministrativeStateException e) {
733 LOGGER.error("Error while starting Transaction " + e);
734 } catch (Exception e) {
735 LOGGER.error("Error while starting Transaction " + e);
737 if (!modifiedGroups.isEmpty()) {
738 Boolean flag = false;
739 for (String group : modifiedGroups.keySet()) {
740 InvocationResult result = null;
742 InvocationRequest request = new DefaultInvocationRequest();
745 request.setPomFile(new File(
746 PROJECTSLOCATION + File.separator + getArtifactID(group) + File.separator + "pom.xml"));
747 request.setGoals(Arrays.asList(GOALS));
748 Invoker invoker = new DefaultInvoker();
749 result = invoker.execute(request);
750 if (result.getExecutionException() != null) {
751 LOGGER.error(result.getExecutionException());
752 } else if (result.getExitCode() != 0) {
753 LOGGER.error("Maven Invocation failure..!");
755 } catch (Exception e) {
756 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation issue for "
757 + getArtifactID(group) + e.getMessage(), e);
759 if (result != null && result.getExitCode() == 0) {
760 LOGGER.info("Build Completed..!");
762 addNotification(group, "create");
764 addNotification(group, modifiedGroups.get(group));
768 throw new PolicyException(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation failure!");
772 sendNotification(controllers);
781 * Removes a Rule from Rule Projects.
783 public void removeRule(String name) {
784 String controllerName = getGroupName(name);
785 if (controllerName == null) {
786 LOGGER.info("Error finding the controllerName for the given Policy: " + name);
789 syncProject(controllerName);
790 getNameAndSetRemove(controllerName, name);
793 private String getGroupName(String name) {
794 if (policyMap.containsKey(name)) {
795 return policyMap.get(name);
798 return (policyMap.containsKey(name)) ? policyMap.get(name) : null;
802 private void addModifiedGroup(String controllerName, String operation) {
803 if (controllerName != null) {
804 modifiedGroups.put(controllerName, operation);
808 private void addNotification(String controllerName, String operation) {
809 ControllerPOJO controllerPOJO = new ControllerPOJO();
810 controllerPOJO.setName(controllerName);
811 controllerPOJO.setOperation(operation);
812 HashMap<String, String> drools = new HashMap<>();
813 drools.put("groupId", getGroupID(controllerName));
814 drools.put("artifactId", getArtifactID(controllerName));
815 drools.put("version", getVersion(controllerName));
816 controllerPOJO.setDrools(drools);
817 controllers.add(controllerPOJO);
819 LOGGER.debug("Notification added: " + PolicyUtils.objectToJsonString(controllerPOJO));
820 } catch (JsonProcessingException e) {
821 LOGGER.error(MessageCodes.ERROR_SCHEMA_INVALID + "Json Processing Error " + e);
825 private void removedRuleModifiedGroup(String controllerName) {
826 // This will be sending Notification to PDPD directly to Lock
827 ControllerPOJO controllerPOJO = new ControllerPOJO();
828 controllerPOJO.setName(controllerName);
829 controllerPOJO.setOperation("lock");
830 List<ControllerPOJO> controllers = new ArrayList<>();
831 controllers.add(controllerPOJO);
832 sendNotification(controllers);
835 private void sendNotification(List<ControllerPOJO> controllers) {
836 NotificationPOJO notification = new NotificationPOJO();
837 String requestId = UUID.randomUUID().toString();
838 LOGGER.info("Generating notification RequestID : " + requestId);
839 notification.setRequestID(requestId);
840 notification.setEntity("controller");
841 notification.setControllers(controllers);
843 String notificationJson = PolicyUtils.objectToJsonString(notification);
844 LOGGER.info("Sending Notification :\n" + notificationJson);
845 sendMessage(notificationJson);
846 } catch (Exception e) {
847 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while sending notification to PDP-D "
848 + e.getMessage(), e);
852 private void sendMessage(String message) throws IOException, GeneralSecurityException, InterruptedException {
854 if ("dmaap".equalsIgnoreCase(notificationType)) {
855 // Sending Message through DMaaP Message Router
856 LOGGER.debug("DMAAP Publishing Message");
858 publisher.send("MyPartitionKey", message);
860 LOGGER.debug("Message Published on DMaaP :" + dmaapList.get(0) + "for Topic: " + pubTopic);
862 Thread.sleep(dmaapDelay);
865 // Sending Message through UEB interface.
866 LOGGER.debug("UEB Publishing Message");
868 CambriaBatchingPublisher pub = pubBuilder.build();
869 pub.send("MyPartitionKey", message);
871 final List<?> stuck = pub.close(uebDelay, TimeUnit.SECONDS);
872 if (stuck.size() > 0) {
873 LOGGER.error(stuck.size() + " messages unsent");
875 LOGGER.debug("Clean exit; Message Published on UEB : " + uebList + "for Topic: " + pubTopic);
881 private void createPom(String name) {
882 Model model = new Model();
883 model.setModelVersion("4.0.0");
884 model.setGroupId(getGroupID(name));
885 model.setArtifactId(getArtifactID(name));
886 model.setVersion(getVersion(name));
888 DistributionManagement distributionManagement = new DistributionManagement();
889 DeploymentRepository repository = new DeploymentRepository();
890 repository.setId(repID);
891 repository.setName(repName);
892 repository.setUrl(repURLs.get(0));
893 distributionManagement.setRepository(repository);
894 model.setDistributionManagement(distributionManagement);
895 // Dependency Management goes here.
896 List<Dependency> dependencyList = new ArrayList<>();
897 if (groupMap.get(name).size() > 1) {
898 @SuppressWarnings("unchecked")
899 ArrayList<PEDependency> dependencies = (ArrayList<PEDependency>) groupMap.get(name).get(1);
900 for (PEDependency dependency : dependencies) {
901 dependencyList.add(dependency.getDependency());
904 // Add Default dependencies.
905 dependencyList = getDependencies(name);
907 model.setDependencies(dependencyList);
908 Writer writer = null;
910 writer = WriterFactory.newXmlWriter(
911 new File(PROJECTSLOCATION + File.separator + getArtifactID(name) + File.separator + "pom.xml"));
912 MavenXpp3Writer pomWriter = new MavenXpp3Writer();
913 pomWriter.write(writer, model);
914 } catch (Exception e) {
915 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while creating POM for " + getArtifactID(name)
916 + e.getMessage(), e);
918 IOUtil.close(writer);
922 private List<Dependency> getDependencies(String controllerName) {
923 // Read the Dependency Information from property file.
924 Path file = Paths.get(DEPENDENCY_FILE);
925 if (!Files.notExists(file)) {
927 String dependencyJSON = new String(Files.readAllBytes(file), StandardCharsets.UTF_8);
928 DependencyInfo dependencyInfo = PolicyUtils.jsonStringToObject(dependencyJSON, DependencyInfo.class);
929 String controller = "default";
930 if (dependencyInfo.getDependencies().containsKey(controllerName)) {
931 controller = controllerName;
933 List<Dependency> dependencyList = new ArrayList<>();
934 for (PEDependency dependency : dependencyInfo.getDependencies().get(controller)) {
935 dependencyList.add(dependency.getDependency());
937 return dependencyList;
938 } catch (IOException | NullPointerException e) {
939 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
940 + "Error while getting dependecy Information for controller: " + controllerName
941 + e.getMessage(), e);
944 return defaultDependencies(controllerName);
947 // Default Dependency Section. Can be changed as required.
948 public List<Dependency> defaultDependencies(String controllerName) {
950 List<Dependency> dependencyList = new ArrayList<>();
951 String version = StringEscapeUtils.escapeJava(brmsdependencyversion);
953 Dependency demoDependency = new Dependency();
954 demoDependency.setGroupId("org.onap.policy.drools-applications");
955 demoDependency.setArtifactId("demo");
956 demoDependency.setVersion(version);
957 dependencyList.add(demoDependency);
959 Dependency controlloopDependency = new Dependency();
960 controlloopDependency.setGroupId("org.onap.policy.drools-applications");
961 controlloopDependency.setArtifactId("events");
962 controlloopDependency.setVersion(version);
963 dependencyList.add(controlloopDependency);
965 Dependency restDependency = new Dependency();
966 restDependency.setGroupId("org.onap.policy.drools-applications");
967 restDependency.setArtifactId("rest");
968 restDependency.setVersion(version);
969 dependencyList.add(restDependency);
971 Dependency appcDependency = new Dependency();
972 appcDependency.setGroupId("org.onap.policy.drools-applications");
973 appcDependency.setArtifactId("appc");
974 appcDependency.setVersion(version);
975 dependencyList.add(appcDependency);
977 Dependency aaiDependency = new Dependency();
978 aaiDependency.setGroupId("org.onap.policy.drools-applications");
979 aaiDependency.setArtifactId("aai");
980 aaiDependency.setVersion(version);
981 dependencyList.add(aaiDependency);
983 Dependency msoDependency = new Dependency();
984 msoDependency.setGroupId("org.onap.policy.drools-applications");
985 msoDependency.setArtifactId("mso");
986 msoDependency.setVersion(version);
987 dependencyList.add(msoDependency);
989 Dependency trafficgeneratorDependency = new Dependency();
990 trafficgeneratorDependency.setGroupId("org.onap.policy.drools-applications");
991 trafficgeneratorDependency.setArtifactId("trafficgenerator");
992 trafficgeneratorDependency.setVersion(version);
993 dependencyList.add(trafficgeneratorDependency);
994 return dependencyList;
997 private void createProject(String path, String ksessionName) {
998 new File(path + File.separator + "rules").mkdirs();
999 new File(path + File.separator + "META-INF").mkdirs();
1000 if (!Files.exists(Paths.get(path + File.separator + "META-INF" + File.separator + "kmodule.xml"))) {
1001 // Hard coding XML for PDP Drools to accept our Rules.
1002 String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "\n"
1003 + "<kmodule xmlns=\"http://jboss.org/kie/6.0.0/kmodule\">" + "\n"
1004 + "<kbase name=\"rules\" packages=\"rules\">" + "\n" + "<ksession name=\"" + ksessionName + "\"/>"
1005 + "\n" + "</kbase></kmodule>";
1006 copyDataToFile(path + File.separator + "META-INF" + File.separator + "kmodule.xml", xml);
1010 private void copyDataToFile(String file, String rule) {
1012 FileUtils.writeStringToFile(new File(file), rule);
1013 } catch (Exception e) {
1015 XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while creating Rule for " + file + e.getMessage(),
1020 private void readGroups(Properties config) throws PolicyException {
1021 String[] groupNames = null;
1022 if (!config.containsKey("groupNames") || config.getProperty("groupNames")==null){
1023 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
1024 + "groupNames property is missing or empty from the property file ");
1026 if (config.getProperty("groupNames").contains(",")) {
1027 groupNames = config.getProperty("groupNames").replaceAll(" ", "").split(",");
1029 groupNames = new String[] { config.getProperty("groupNames").replaceAll(" ", "") };
1031 if (groupNames == null || groupNames.length == 0) {
1032 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
1033 + "groupNames property is missing or empty from the property file ");
1034 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
1035 + "groupNames property is missing or empty from the property file ");
1037 groupMap = new HashMap<>();
1038 for (int counter = 0; counter < groupNames.length; counter++) {
1039 String name = groupNames[counter];
1040 String groupID = config.getProperty(name + ".groupID");
1041 if (groupID == null) {
1042 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1043 + ".groupID property is missing from the property file ");
1044 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1045 + ".groupID property is missing from the property file ");
1047 String artifactID = config.getProperty(name + ".artifactID");
1048 if (artifactID == null) {
1049 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1050 + ".artifactID property is missing from the property file ");
1051 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1052 + ".artifactID property is missing from the property file ");
1054 PEDependency dependency = new PEDependency();
1055 dependency.setArtifactId(artifactID);
1056 dependency.setGroupId(groupID);
1057 // Add to list if we got all
1058 addToGroup(name, dependency);
1062 private void addToGroup(String name, PEDependency dependency) {
1063 ArrayList<Object> values = new ArrayList<>();
1064 values.add(dependency);
1065 groupMap.put(name, values);
1066 EntityTransaction et = em.getTransaction();
1068 Query query = em.createQuery("select b from BRMSGroupInfo as b where b.controllerName = :cn");
1069 query.setParameter("cn", name);
1070 List<?> groupList = query.getResultList();
1071 BRMSGroupInfo brmsGroupInfo = null;
1072 if (groupList.size() > 0) {
1073 LOGGER.info("Controller name already Existing in DB. Will be updating the DB Values" + name);
1074 brmsGroupInfo = (BRMSGroupInfo) groupList.get(0);
1076 if (brmsGroupInfo == null) {
1077 brmsGroupInfo = new BRMSGroupInfo();
1079 brmsGroupInfo.setControllerName(name);
1080 brmsGroupInfo.setGroupId(dependency.getGroupId());
1081 brmsGroupInfo.setArtifactId(dependency.getArtifactId());
1082 brmsGroupInfo.setVersion(dependency.getVersion());
1083 em.persist(brmsGroupInfo);
1088 private String getArtifactID(String name) {
1089 return ((PEDependency) groupMap.get(name).get(0)).getArtifactId();
1092 private String getGroupID(String name) {
1093 return ((PEDependency) groupMap.get(name).get(0)).getGroupId();
1096 private String getVersion(String name) {
1097 return ((PEDependency) groupMap.get(name).get(0)).getVersion();
1100 private void getNameAndSetRemove(String controllerName, String policyName) {
1101 String artifactName = getArtifactID(controllerName);
1102 String ruleFolder = PROJECTSLOCATION + File.separator + artifactName + File.separator + "src" + File.separator
1103 + "main" + File.separator + "resources" + File.separator + "rules";
1104 File file = new File(ruleFolder + File.separator + policyName + ".drl");
1105 if (file.delete()) {
1106 LOGGER.info("Deleted File.. " + file.getAbsolutePath());
1107 removePolicyFromGroup(policyName, controllerName);
1109 if (new File(ruleFolder).listFiles().length == 0) {
1110 removedRuleModifiedGroup(controllerName);
1112 // This is an update in terms of PDPD.
1113 addModifiedGroup(controllerName, "update");
1117 // Removes Policy from Memory and Database.
1118 private void removePolicyFromGroup(String policyName, String controllerName) {
1119 policyMap.remove(policyName);
1120 EntityTransaction et = em.getTransaction();
1122 Query query = em.createQuery("select b from BRMSPolicyInfo as b where b.policyName = :pn");
1123 query.setParameter("pn", policyName);
1124 List<?> pList = query.getResultList();
1125 BRMSPolicyInfo brmsPolicyInfo = new BRMSPolicyInfo();
1126 if (pList.size() > 0) {
1128 brmsPolicyInfo = (BRMSPolicyInfo) pList.get(0);
1129 if (brmsPolicyInfo.getControllerName().getControllerName().equals(controllerName)) {
1130 em.remove(brmsPolicyInfo);
1137 private void setVersion(String newVersion, String controllerName) {
1138 PEDependency userController = (PEDependency) groupMap.get(controllerName).get(0);
1139 userController.setVersion(newVersion);
1140 groupMap.get(controllerName).set(0, userController);
1143 // Return BackUpMonitor
1144 public static BackUpMonitor getBackUpMonitor() {
1148 public void rotateURLs() {
1149 if (repURLs != null) {
1150 Collections.rotate(repURLs, -1);
1154 public int URLListSize() {
1155 if (repURLs != null) {
1156 return repURLs.size();