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 Properties config = new Properties();
141 Path file = Paths.get(propertiesFile);
142 if (Files.notExists(file)) {
143 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Config File doesn't Exist in the specified Path "
145 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
146 + "Config File doesn't Exist in the specified Path " + file.toString());
148 if (file.toString().endsWith(".properties")) {
149 // Grab the Properties.
150 setProperty(file, config, handler);
155 private void setProperty(Path file, Properties config, BackUpHandler handler) throws PolicyException {
158 in = new FileInputStream(file.toFile());
160 } catch (IOException e) {
162 XACMLErrorConstants.ERROR_DATA_ISSUE + "Data/File Read Error while reading from the property file.",
164 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
165 + "Data/File Read Error while reading from the property file.");
167 LOGGER.info("Trying to set up IntegrityMonitor");
168 String resourceName = null;
170 LOGGER.info("Trying to set up IntegrityMonitor");
171 resourceName = config.getProperty("RESOURCE_NAME");
172 if (resourceName == null) {
173 LOGGER.warn("RESOURCE_NAME is missing setting default value. ");
174 resourceName = "brmsgw_pdp01";
176 resourceName = resourceName.trim();
177 setIntegrityMonitor(IntegrityMonitor.getInstance(resourceName, config));
178 } catch (Exception e) {
179 LOGGER.error("Error starting Integerity Monitor: " + e);
181 LOGGER.info("Trying to set up BackUpMonitor");
183 setBackupMonitor(BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), resourceName, config,
185 } catch (Exception e) {
186 LOGGER.error("Error starting BackUpMonitor: " + e);
188 config.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, "META-INF/persistenceBRMS.xml");
189 EntityManagerFactory emf = Persistence.createEntityManagerFactory("BRMSGW", config);
190 em = emf.createEntityManager();
191 defaultName = config.getProperty("defaultName");
192 if (defaultName == null) {
194 XACMLErrorConstants.ERROR_DATA_ISSUE + "defaultName property is missing from the property file ");
195 throw new PolicyException(
196 XACMLErrorConstants.ERROR_DATA_ISSUE + "defaultName property is missing from the property file");
198 defaultName = defaultName.trim();
199 repID = config.getProperty("repositoryID");
202 XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryID property is missing from the property file ");
203 throw new PolicyException(
204 XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryID property is missing from the property file ");
206 repID = repID.trim();
207 repName = config.getProperty("repositoryName");
208 if (repName == null) {
209 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
210 + "repositoryName property is missing from the property file ");
211 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
212 + "repositoryName property is missing from the property file ");
214 repName = repName.trim();
215 String repURL = config.getProperty("repositoryURL");
216 if (repURL == null) {
218 XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryURL property is missing from the property file ");
219 throw new PolicyException(
220 XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryURL property is missing from the property file ");
222 if (repURL.contains(",")) {
223 repURLs = new ArrayList<>(Arrays.asList(repURL.trim().split(",")));
225 repURLs = new ArrayList<>();
228 repUserName = config.getProperty("repositoryUsername");
229 repPassword = config.getProperty("repositoryPassword");
230 if (repUserName == null || repPassword == null) {
231 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
232 + "repostoryUserName and respositoryPassword properties are required.");
233 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
234 + "repostoryUserName and respositoryPassword properties are required.");
236 repUserName = repUserName.trim();
237 repPassword = repPassword.trim();
238 policyKeyID = config.getProperty("policyKeyID");
239 if (policyKeyID == null) {
241 XACMLErrorConstants.ERROR_DATA_ISSUE + "policyKeyID property is missing from the property file ");
242 throw new PolicyException(
243 XACMLErrorConstants.ERROR_DATA_ISSUE + "policyKeyID property is missing from the property file ");
245 policyKeyID = policyKeyID.trim();
246 String syncF = config.getProperty("sync", "false").trim();
247 syncFlag = Boolean.parseBoolean(syncF);
249 PolicyLogger.info("SYNC Flag is turned ON. DB will be given Priority.");
251 brmsdependencyversion = config.getProperty("brms.dependency.version");
252 if (brmsdependencyversion == null) {
253 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
254 + "brmsdependencyversion property is missing from the property file, Using default Version.");
255 brmsdependencyversion = DEFAULT_VERSION;
257 brmsdependencyversion = brmsdependencyversion.trim();
261 notificationType = config.getProperty("NOTIFICATION_TYPE");
262 if ("dmaap".equalsIgnoreCase(notificationType)) {
264 LOGGER.info("Notification Type being used is DMaaP... creating instance of BusPublisher.");
265 // Setting up the Publisher for DMaaP MR
266 String dmaapServers = config.getProperty("NOTIFICATION_SERVERS");
267 pubTopic = config.getProperty("NOTIFICATION_TOPIC");
268 String aafLogin = config.getProperty("CLIENT_ID").trim();
269 String aafPassword = config.getProperty("CLIENT_KEY").trim();
271 if (dmaapServers == null || pubTopic == null) {
273 XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file ");
274 throw new PolicyException(
275 XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file ");
278 dmaapServers = dmaapServers.trim();
279 pubTopic = pubTopic.trim();
281 if (dmaapServers.contains(",")) {
282 dmaapList = new ArrayList<>(Arrays.asList(dmaapServers.split("\\s*,\\s*")));
284 dmaapList = new ArrayList<>();
285 dmaapList.add(dmaapServers);
288 this.publisher = new BusPublisher.DmaapPublisherWrapper(this.dmaapList, this.pubTopic, aafLogin,
291 String dDelay = config.getProperty("NOTIFICATION_DELAY");
292 if (dDelay != null && !dDelay.isEmpty()) {
293 dDelay = dDelay.trim();
295 dmaapDelay = Long.parseLong(dDelay);
296 } catch (NumberFormatException e) {
297 LOGGER.error("DMAAP_DELAY not a long format number" + e);
300 LOGGER.info("DMAAP BusPublisher is created.");
303 LOGGER.info("Notification Type being used is UEB... creating instance of PublisherBuilder.");
304 // Setting up the Publisher for UEB
305 uebList = config.getProperty("NOTIFICATION_SERVERS");
306 pubTopic = config.getProperty("NOTIFICATION_TOPIC");
307 String apiKey = config.getProperty("UEB_API_KEY");
308 String apiSecret = config.getProperty("UEB_API_SECRET");
309 if (uebList == null || pubTopic == null) {
311 XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file ");
312 throw new PolicyException(
313 XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file ");
315 uebList = uebList.trim();
316 pubTopic = pubTopic.trim();
317 pubBuilder = new CambriaClientBuilders.PublisherBuilder();
318 pubBuilder.usingHosts(uebList).onTopic(pubTopic);
319 if (apiKey != null && !apiKey.isEmpty() && apiSecret != null && !apiSecret.isEmpty()) {
320 apiKey = apiKey.trim();
321 apiSecret = apiSecret.trim();
322 pubBuilder.authenticatedBy(apiKey, apiSecret);
324 String uDelay = config.getProperty("NOTIFICATION_DELAY");
325 if (uDelay != null && !uDelay.isEmpty()) {
326 uDelay = uDelay.trim();
328 uebDelay = Long.parseLong(uDelay);
329 } catch (NumberFormatException e) {
330 LOGGER.error("UEB_DELAY not a long format number" + e);
333 LOGGER.info("UEB PublisherBuilder is created.");
339 private static void setBackupMonitor(BackUpMonitor instance) {
343 private static void setIntegrityMonitor(IntegrityMonitor instance) {
348 * Will Initialize the variables required for BRMSPush.
350 public void initiate(boolean flag) {
351 resetModifiedGroups();
352 controllers = new ArrayList<>();
354 bm.updateNotification();
355 } catch (Exception e) {
356 LOGGER.error("Error while updating Notification: " + e.getMessage(), e);
362 private static void resetModifiedGroups() {
363 modifiedGroups = new HashMap<>();
367 * Will Add rules to projects. Creates necessary folders if required.
369 public void addRule(String name, String rule, Map<String, String> responseAttributes) {
370 // 1 check the response Attributes and determine if this belongs to any projects.
371 // 2 if not create folder
374 // 5 store the groups that have been updated.
375 String kSessionName = null;
376 String selectedName = null;
377 if (!responseAttributes.isEmpty()) {
378 // Pick selected Value
379 String userControllerName = null;
380 ArrayList<PEDependency> userDependencies = new ArrayList<>();
381 for (String key : responseAttributes.keySet()) {
382 if (key.equals(policyKeyID)) {
383 selectedName = responseAttributes.get(key);
385 // kmodule configurations
386 else if (key.equals("kSessionName")) {
387 kSessionName = responseAttributes.get(key);
389 // Check User Specific values.
390 if (key.equals("$controller:")) {
392 PEDependency dependency = PolicyUtils.jsonStringToObject(responseAttributes.get(key),
394 userControllerName = key.replaceFirst("$controller:", "");
395 addToGroup(userControllerName, dependency);
396 } catch (Exception e) {
397 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while resolving Controller: " + e);
400 } else if (key.equals("$dependency$")) {
401 String value = responseAttributes.get(key);
402 if (value.startsWith("[") && value.endsWith("]")) {
403 value = value.substring(1, value.length() - 1).trim();
404 List<String> dependencyStrings = Arrays.asList(value.split("},{"));
405 for (String dependencyString : dependencyStrings) {
408 .add(PolicyUtils.jsonStringToObject(dependencyString, PEDependency.class));
409 } catch (Exception e) {
410 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
411 + "Error while resolving Dependencies: " + e);
417 if (userControllerName != null) {
418 // Adding custom dependencies here.
419 ArrayList<Object> values = groupMap.get(userControllerName);
420 values.add(userDependencies);
421 groupMap.put(userControllerName, values);
422 selectedName = userControllerName;
425 // If no Match then pick Default.
426 if (selectedName == null) {
427 selectedName = defaultName;
429 if (groupMap.containsKey(selectedName)) {
430 // If the key is not got as parameters set by the user, setting the default value for kSessionName as
432 if (kSessionName == null) {
433 if (selectedName == defaultName) {
434 kSessionName = "closedloop";
436 kSessionName = "closedloop-" + selectedName;
439 // create directories if missing.
440 manageProject(selectedName, kSessionName, name, rule);
441 addModifiedGroup(selectedName, "update"); // Will check for Create Later after generating the Pom.
445 private void syncGroupInfo() {
446 // Sync DB to JMemory.
447 EntityTransaction et = em.getTransaction();
449 Query query = em.createQuery("select b from BRMSGroupInfo AS b");
450 List<?> bList = query.getResultList();
451 if (bList.size() != groupMap.size()) {
452 for (Object value : bList) {
453 BRMSGroupInfo brmsGroupInfo = (BRMSGroupInfo) value;
454 PEDependency dependency = new PEDependency();
455 dependency.setArtifactId(brmsGroupInfo.getArtifactId());
456 dependency.setGroupId(brmsGroupInfo.getGroupId());
457 dependency.setVersion(brmsGroupInfo.getVersion());
458 ArrayList<Object> values = new ArrayList<>();
459 values.add(dependency);
460 groupMap.put(brmsGroupInfo.getControllerName(), values);
463 query = em.createQuery("select g from BRMSPolicyInfo AS g");
464 bList = query.getResultList();
465 if (bList.size() != policyMap.size()) {
466 for (Object value : bList) {
467 BRMSPolicyInfo brmsPolicyInfo = (BRMSPolicyInfo) value;
468 policyMap.put(brmsPolicyInfo.getPolicyName(), brmsPolicyInfo.getControllerName().getControllerName());
472 LOGGER.info("Updated Local Memory values with values from database.");
475 private void manageProject(String selectedName, String kSessionName, String name, String rule) {
476 // Check if the Project is in Sync. If not get the latest Version.
477 syncProject(selectedName);
478 createProject(PROJECTSLOCATION + File.separator + getArtifactID(selectedName) + File.separator + "src"
479 + File.separator + "main" + File.separator + "resources", kSessionName);
480 copyDataToFile(PROJECTSLOCATION + File.separator + getArtifactID(selectedName) + File.separator + "src"
481 + File.separator + "main" + File.separator + "resources" + File.separator + "rules" + File.separator
482 + name + ".drl", rule);
483 addToPolicy(name, selectedName);
487 * Add Policy to JMemory and DataBase.
489 private void addToPolicy(String policyName, String controllerName) {
490 policyMap.put(policyName, controllerName);
491 EntityTransaction et = em.getTransaction();
493 Query query = em.createQuery("select b from BRMSPolicyInfo as b where b.policyName = :pn");
494 query.setParameter("pn", policyName);
495 List<?> pList = query.getResultList();
496 boolean createFlag = false;
497 BRMSPolicyInfo brmsPolicyInfo = new BRMSPolicyInfo();
498 if (pList.size() > 0) {
500 brmsPolicyInfo = (BRMSPolicyInfo) pList.get(0);
501 if (!brmsPolicyInfo.getControllerName().getControllerName().equals(controllerName)) {
508 query = em.createQuery("select b from BRMSGroupInfo as b where b.controllerName = :cn");
509 query.setParameter("cn", controllerName);
510 List<?> bList = query.getResultList();
511 BRMSGroupInfo brmsGroupInfo = new BRMSGroupInfo();
512 if (bList.size() > 0) {
513 brmsGroupInfo = (BRMSGroupInfo) bList.get(0);
515 brmsPolicyInfo.setPolicyName(policyName);
516 brmsPolicyInfo.setControllerName(brmsGroupInfo);
517 em.persist(brmsPolicyInfo);
523 private void syncProject(String selectedName) {
524 boolean projectExists = checkProject(selectedName);
526 String version = null;
527 version = getVersion(selectedName);
528 if (version == null) {
529 LOGGER.error("Error getting local version for the given Controller Name:" + selectedName
530 + " going with Default value");
533 String nextVersion = incrementVersion(version);
534 boolean outOfSync = checkRemoteSync(selectedName, nextVersion);
539 // We are out of Sync or Project is not Present.
540 downloadProject(selectedName);
543 private void downloadProject(String selectedName) {
544 NexusArtifact artifact = getLatestArtifactFromNexus(selectedName);
545 if (artifact == null)
547 String dirName = getDirectoryName(selectedName);
549 String fileName = "rule.jar";
551 website = new URL(artifact.getResourceURI());
552 ReadableByteChannel rbc = Channels.newChannel(website.openStream());
553 FileOutputStream fos = new FileOutputStream(fileName);
554 fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
556 extractJar(fileName, dirName);
557 new File(fileName).delete();
558 } catch (IOException e) {
559 LOGGER.error("Error while downloading the project to File System. " + e.getMessage(), e);
563 private void extractJar(String jarFileName, String artifactId) throws IOException {
564 JarFile jar = new JarFile(jarFileName);
565 Enumeration<?> enumEntries = jar.entries();
566 while (enumEntries.hasMoreElements()) {
567 JarEntry file = (JarEntry) enumEntries.nextElement();
569 String fileName = file.getName().substring(file.getName().lastIndexOf("/") + 1);
570 if (file.getName().endsWith(".drl")) {
571 String path = PROJECTSLOCATION + File.separator + artifactId + File.separator + "src" + File.separator
572 + "main" + File.separator + "resources" + File.separator + "rules";
573 new File(path).mkdirs();
574 if (syncFlag && policyMap.containsKey(fileName.replace(".drl", ""))) {
575 f = new File(path + File.separator + fileName);
577 f = new File(path + File.separator + fileName);
579 } else if (file.getName().endsWith("pom.xml")) {
580 String path = PROJECTSLOCATION + File.separator + artifactId;
581 new File(path).mkdirs();
582 f = new File(path + File.separator + fileName);
583 } else if (file.getName().endsWith("kmodule.xml")) {
584 String path = PROJECTSLOCATION + File.separator + artifactId + File.separator + "src" + File.separator
585 + "main" + File.separator + "resources" + File.separator + "META-INF";
586 new File(path).mkdirs();
587 f = new File(path + File.separator + fileName);
590 InputStream is = jar.getInputStream(file);
591 FileOutputStream fos = new FileOutputStream(f);
592 while (is.available() > 0) {
593 fos.write(is.read());
598 LOGGER.info(fileName + " Created..");
604 private NexusArtifact getLatestArtifactFromNexus(String selectedName) {
605 List<NexusArtifact> artifacts = getArtifactFromNexus(selectedName, null);
608 NexusArtifact result = null;
609 for (NexusArtifact artifact : artifacts) {
610 int majorVal = Integer.parseInt(artifact.getVersion().substring(0, artifact.getVersion().indexOf(".")));
611 int minorVal = Integer.parseInt(artifact.getVersion().substring(artifact.getVersion().indexOf(".") + 1,
612 artifact.getVersion().lastIndexOf(".")));
613 if (majorVal > bigNum) {
617 if ((bigNum == majorVal) && (minorVal > smallNum)) {
620 if (bigNum == majorVal && minorVal == smallNum) {
624 return additionalNexusLatestCheck(selectedName, result);
627 // Additional Check due to Limitations from Nexus API to check if the artifact is the latest.
628 private NexusArtifact additionalNexusLatestCheck(String selectedName, NexusArtifact result) {
629 String nextVersion = incrementVersion(result.getVersion());
630 List<NexusArtifact> artifact = getArtifactFromNexus(selectedName, nextVersion);
631 return artifact.isEmpty() ? result : additionalNexusLatestCheck(selectedName, artifact.get(0));
634 private boolean checkRemoteSync(String selectedName, String version) {
635 List<NexusArtifact> artifacts = getArtifactFromNexus(selectedName, version);
636 return (artifacts.size() == 0) ? false : true;
639 private List<NexusArtifact> getArtifactFromNexus(String selectedName, String version) {
640 final NexusClient client = new NexusRestClient();
642 boolean flag = false;
643 while (i < repURLs.size()) {
645 String repURL = repURLs.get(0);
646 client.connect(repURL.substring(0, repURL.indexOf(repURL.split(":[0-9]+\\/nexus")[1])), repUserName,
648 final NexusArtifact template = new NexusArtifact();
649 template.setGroupId(getGroupID(selectedName));
650 template.setArtifactId(getArtifactID(selectedName));
651 if (version != null) {
652 template.setVersion(version);
654 List<NexusArtifact> resultList = client.searchByGAV(template);
655 if (resultList != null) {
659 } catch (NexusClientException | NexusConnectionException | NullPointerException e) {
660 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Connection to remote Nexus has failed. "
661 + e.getMessage(), e);
665 } catch (NexusClientException | NexusConnectionException e) {
666 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "failed to disconnect Connection from Nexus."
667 + e.getMessage(), e);
670 Collections.rotate(repURLs, -1);
675 return new ArrayList<>();
678 private void setVersion(String selectedName) {
679 String newVersion = "0.1.0";
681 NexusArtifact artifact = getLatestArtifactFromNexus(selectedName);
682 if (artifact != null) {
683 newVersion = incrementVersion(artifact.getVersion());
685 if (newVersion.equals("0.1.0")) {
688 setVersion(newVersion, selectedName);
689 LOGGER.info("Controller: " + selectedName + "is on version: " + newVersion);
692 private String incrementVersion(String version) {
693 int majorVal = Integer.parseInt(version.substring(0, version.indexOf(".")));
694 int minorVal = Integer.parseInt(version.substring(version.indexOf(".") + 1, version.lastIndexOf(".")));
701 return majorVal + "." + minorVal + version.substring(version.lastIndexOf("."));
704 private boolean checkProject(String selectedName) {
705 return new File(PROJECTSLOCATION + File.separator + getDirectoryName(selectedName)).exists();
708 private String getDirectoryName(String selectedName) {
709 return getArtifactID(selectedName);
713 * Will Push policies to the PolicyRepo.
715 * @param notificationType
716 * <String> type of notification Type.
717 * @throws PolicyException
719 public void pushRules() throws PolicyException {
720 // Check how many groups have been updated.
721 // Invoke their Maven process.
723 im.startTransaction();
724 } catch (AdministrativeStateException e) {
725 LOGGER.error("Error while starting Transaction " + e);
726 } catch (Exception e) {
727 LOGGER.error("Error while starting Transaction " + e);
729 if (!modifiedGroups.isEmpty()) {
730 Boolean flag = false;
731 for (String group : modifiedGroups.keySet()) {
732 InvocationResult result = null;
734 InvocationRequest request = new DefaultInvocationRequest();
737 request.setPomFile(new File(
738 PROJECTSLOCATION + File.separator + getArtifactID(group) + File.separator + "pom.xml"));
739 request.setGoals(Arrays.asList(GOALS));
740 Invoker invoker = new DefaultInvoker();
741 result = invoker.execute(request);
742 if (result.getExecutionException() != null) {
743 LOGGER.error(result.getExecutionException());
744 } else if (result.getExitCode() != 0) {
745 LOGGER.error("Maven Invocation failure..!");
747 } catch (Exception e) {
748 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation issue for "
749 + getArtifactID(group) + e.getMessage(), e);
751 if (result != null && result.getExitCode() == 0) {
752 LOGGER.info("Build Completed..!");
754 addNotification(group, "create");
756 addNotification(group, modifiedGroups.get(group));
760 throw new PolicyException(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation failure!");
764 sendNotification(controllers);
773 * Removes a Rule from Rule Projects.
775 public void removeRule(String name) {
776 String controllerName = getGroupName(name);
777 if (controllerName == null) {
778 LOGGER.info("Error finding the controllerName for the given Policy: " + name);
781 syncProject(controllerName);
782 getNameAndSetRemove(controllerName, name);
785 private String getGroupName(String name) {
786 if (policyMap.containsKey(name)) {
787 return policyMap.get(name);
790 return (policyMap.containsKey(name)) ? policyMap.get(name) : null;
794 private void addModifiedGroup(String controllerName, String operation) {
795 if (controllerName != null) {
796 modifiedGroups.put(controllerName, operation);
800 private void addNotification(String controllerName, String operation) {
801 ControllerPOJO controllerPOJO = new ControllerPOJO();
802 controllerPOJO.setName(controllerName);
803 controllerPOJO.setOperation(operation);
804 HashMap<String, String> drools = new HashMap<>();
805 drools.put("groupId", getGroupID(controllerName));
806 drools.put("artifactId", getArtifactID(controllerName));
807 drools.put("version", getVersion(controllerName));
808 controllerPOJO.setDrools(drools);
809 controllers.add(controllerPOJO);
811 LOGGER.debug("Notification added: " + PolicyUtils.objectToJsonString(controllerPOJO));
812 } catch (JsonProcessingException e) {
813 LOGGER.error(MessageCodes.ERROR_SCHEMA_INVALID + "Json Processing Error " + e);
817 private void removedRuleModifiedGroup(String controllerName) {
818 // This will be sending Notification to PDPD directly to Lock
819 ControllerPOJO controllerPOJO = new ControllerPOJO();
820 controllerPOJO.setName(controllerName);
821 controllerPOJO.setOperation("lock");
822 List<ControllerPOJO> controllers = new ArrayList<>();
823 controllers.add(controllerPOJO);
824 sendNotification(controllers);
827 private void sendNotification(List<ControllerPOJO> controllers) {
828 NotificationPOJO notification = new NotificationPOJO();
829 String requestId = UUID.randomUUID().toString();
830 LOGGER.info("Generating notification RequestID : " + requestId);
831 notification.setRequestID(requestId);
832 notification.setEntity("controller");
833 notification.setControllers(controllers);
835 String notificationJson = PolicyUtils.objectToJsonString(notification);
836 LOGGER.info("Sending Notification :\n" + notificationJson);
837 sendMessage(notificationJson);
838 } catch (Exception e) {
839 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while sending notification to PDP-D "
840 + e.getMessage(), e);
844 private void sendMessage(String message) throws IOException, GeneralSecurityException, InterruptedException {
846 if ("dmaap".equalsIgnoreCase(notificationType)) {
847 // Sending Message through DMaaP Message Router
848 LOGGER.debug("DMAAP Publishing Message");
850 publisher.send("MyPartitionKey", message);
852 LOGGER.debug("Message Published on DMaaP :" + dmaapList.get(0) + "for Topic: " + pubTopic);
854 Thread.sleep(dmaapDelay);
857 // Sending Message through UEB interface.
858 LOGGER.debug("UEB Publishing Message");
860 CambriaBatchingPublisher pub = pubBuilder.build();
861 pub.send("MyPartitionKey", message);
863 final List<?> stuck = pub.close(uebDelay, TimeUnit.SECONDS);
864 if (stuck.size() > 0) {
865 LOGGER.error(stuck.size() + " messages unsent");
867 LOGGER.debug("Clean exit; Message Published on UEB : " + uebList + "for Topic: " + pubTopic);
873 private void createPom(String name) {
874 Model model = new Model();
875 model.setModelVersion("4.0.0");
876 model.setGroupId(getGroupID(name));
877 model.setArtifactId(getArtifactID(name));
878 model.setVersion(getVersion(name));
880 DistributionManagement distributionManagement = new DistributionManagement();
881 DeploymentRepository repository = new DeploymentRepository();
882 repository.setId(repID);
883 repository.setName(repName);
884 repository.setUrl(repURLs.get(0));
885 distributionManagement.setRepository(repository);
886 model.setDistributionManagement(distributionManagement);
887 // Dependency Management goes here.
888 List<Dependency> dependencyList = new ArrayList<>();
889 if (groupMap.get(name).size() > 1) {
890 @SuppressWarnings("unchecked")
891 ArrayList<PEDependency> dependencies = (ArrayList<PEDependency>) groupMap.get(name).get(1);
892 for (PEDependency dependency : dependencies) {
893 dependencyList.add(dependency.getDependency());
896 // Add Default dependencies.
897 dependencyList = getDependencies(name);
899 model.setDependencies(dependencyList);
900 Writer writer = null;
902 writer = WriterFactory.newXmlWriter(
903 new File(PROJECTSLOCATION + File.separator + getArtifactID(name) + File.separator + "pom.xml"));
904 MavenXpp3Writer pomWriter = new MavenXpp3Writer();
905 pomWriter.write(writer, model);
906 } catch (Exception e) {
907 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while creating POM for " + getArtifactID(name)
908 + e.getMessage(), e);
910 IOUtil.close(writer);
914 private List<Dependency> getDependencies(String controllerName) {
915 // Read the Dependency Information from property file.
916 Path file = Paths.get(DEPENDENCY_FILE);
917 if (!Files.notExists(file)) {
919 String dependencyJSON = new String(Files.readAllBytes(file), StandardCharsets.UTF_8);
920 DependencyInfo dependencyInfo = PolicyUtils.jsonStringToObject(dependencyJSON, DependencyInfo.class);
921 String controller = "default";
922 if (dependencyInfo.getDependencies().containsKey(controllerName)) {
923 controller = controllerName;
925 List<Dependency> dependencyList = new ArrayList<>();
926 for (PEDependency dependency : dependencyInfo.getDependencies().get(controller)) {
927 dependencyList.add(dependency.getDependency());
929 return dependencyList;
930 } catch (IOException | NullPointerException e) {
931 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
932 + "Error while getting dependecy Information for controller: " + controllerName
933 + e.getMessage(), e);
936 return defaultDependencies(controllerName);
939 // Default Dependency Section. Can be changed as required.
940 public List<Dependency> defaultDependencies(String controllerName) {
942 List<Dependency> dependencyList = new ArrayList<>();
943 String version = StringEscapeUtils.escapeJava(brmsdependencyversion);
945 Dependency demoDependency = new Dependency();
946 demoDependency.setGroupId("org.onap.policy.drools-applications");
947 demoDependency.setArtifactId("demo");
948 demoDependency.setVersion(version);
949 dependencyList.add(demoDependency);
951 Dependency controlloopDependency = new Dependency();
952 controlloopDependency.setGroupId("org.onap.policy.drools-applications");
953 controlloopDependency.setArtifactId("events");
954 controlloopDependency.setVersion(version);
955 dependencyList.add(controlloopDependency);
957 Dependency restDependency = new Dependency();
958 restDependency.setGroupId("org.onap.policy.drools-applications");
959 restDependency.setArtifactId("rest");
960 restDependency.setVersion(version);
961 dependencyList.add(restDependency);
963 Dependency appcDependency = new Dependency();
964 appcDependency.setGroupId("org.onap.policy.drools-applications");
965 appcDependency.setArtifactId("appc");
966 appcDependency.setVersion(version);
967 dependencyList.add(appcDependency);
969 Dependency aaiDependency = new Dependency();
970 aaiDependency.setGroupId("org.onap.policy.drools-applications");
971 aaiDependency.setArtifactId("aai");
972 aaiDependency.setVersion(version);
973 dependencyList.add(aaiDependency);
975 Dependency msoDependency = new Dependency();
976 msoDependency.setGroupId("org.onap.policy.drools-applications");
977 msoDependency.setArtifactId("mso");
978 msoDependency.setVersion(version);
979 dependencyList.add(msoDependency);
981 Dependency trafficgeneratorDependency = new Dependency();
982 trafficgeneratorDependency.setGroupId("org.onap.policy.drools-applications");
983 trafficgeneratorDependency.setArtifactId("trafficgenerator");
984 trafficgeneratorDependency.setVersion(version);
985 dependencyList.add(trafficgeneratorDependency);
986 return dependencyList;
989 private void createProject(String path, String ksessionName) {
990 new File(path + File.separator + "rules").mkdirs();
991 new File(path + File.separator + "META-INF").mkdirs();
992 if (!Files.exists(Paths.get(path + File.separator + "META-INF" + File.separator + "kmodule.xml"))) {
993 // Hard coding XML for PDP Drools to accept our Rules.
994 String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "\n"
995 + "<kmodule xmlns=\"http://jboss.org/kie/6.0.0/kmodule\">" + "\n"
996 + "<kbase name=\"rules\" packages=\"rules\">" + "\n" + "<ksession name=\"" + ksessionName + "\"/>"
997 + "\n" + "</kbase></kmodule>";
998 copyDataToFile(path + File.separator + "META-INF" + File.separator + "kmodule.xml", xml);
1002 private void copyDataToFile(String file, String rule) {
1004 FileUtils.writeStringToFile(new File(file), rule);
1005 } catch (Exception e) {
1007 XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while creating Rule for " + file + e.getMessage(),
1012 private void readGroups(Properties config) throws PolicyException {
1013 String[] groupNames = null;
1014 if (config.getProperty("groupNames").contains(",")) {
1015 groupNames = config.getProperty("groupNames").replaceAll(" ", "").split(",");
1017 groupNames = new String[] { config.getProperty("groupNames").replaceAll(" ", "") };
1019 if (groupNames == null || groupNames.length == 0) {
1020 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
1021 + "groupNames property is missing or empty from the property file ");
1022 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
1023 + "groupNames property is missing or empty from the property file ");
1025 groupMap = new HashMap<>();
1026 for (int counter = 0; counter < groupNames.length; counter++) {
1027 String name = groupNames[counter];
1028 String groupID = config.getProperty(name + ".groupID");
1029 if (groupID == null) {
1030 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1031 + ".groupID property is missing from the property file ");
1032 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1033 + ".groupID property is missing from the property file ");
1035 String artifactID = config.getProperty(name + ".artifactID");
1036 if (artifactID == null) {
1037 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1038 + ".artifactID property is missing from the property file ");
1039 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1040 + ".artifactID property is missing from the property file ");
1042 PEDependency dependency = new PEDependency();
1043 dependency.setArtifactId(artifactID);
1044 dependency.setGroupId(groupID);
1045 // Add to list if we got all
1046 addToGroup(name, dependency);
1050 private void addToGroup(String name, PEDependency dependency) {
1051 ArrayList<Object> values = new ArrayList<>();
1052 values.add(dependency);
1053 groupMap.put(name, values);
1054 EntityTransaction et = em.getTransaction();
1056 Query query = em.createQuery("select b from BRMSGroupInfo as b where b.controllerName = :cn");
1057 query.setParameter("cn", name);
1058 List<?> groupList = query.getResultList();
1059 BRMSGroupInfo brmsGroupInfo = null;
1060 if (groupList.size() > 0) {
1061 LOGGER.info("Controller name already Existing in DB. Will be updating the DB Values" + name);
1062 brmsGroupInfo = (BRMSGroupInfo) groupList.get(0);
1064 if (brmsGroupInfo == null) {
1065 brmsGroupInfo = new BRMSGroupInfo();
1067 brmsGroupInfo.setControllerName(name);
1068 brmsGroupInfo.setGroupId(dependency.getGroupId());
1069 brmsGroupInfo.setArtifactId(dependency.getArtifactId());
1070 brmsGroupInfo.setVersion(dependency.getVersion());
1071 em.persist(brmsGroupInfo);
1076 private String getArtifactID(String name) {
1077 return ((PEDependency) groupMap.get(name).get(0)).getArtifactId();
1080 private String getGroupID(String name) {
1081 return ((PEDependency) groupMap.get(name).get(0)).getGroupId();
1084 private String getVersion(String name) {
1085 return ((PEDependency) groupMap.get(name).get(0)).getVersion();
1088 private void getNameAndSetRemove(String controllerName, String policyName) {
1089 String artifactName = getArtifactID(controllerName);
1090 String ruleFolder = PROJECTSLOCATION + File.separator + artifactName + File.separator + "src" + File.separator
1091 + "main" + File.separator + "resources" + File.separator + "rules";
1092 File file = new File(ruleFolder + File.separator + policyName + ".drl");
1093 if (file.delete()) {
1094 LOGGER.info("Deleted File.. " + file.getAbsolutePath());
1095 removePolicyFromGroup(policyName, controllerName);
1097 if (new File(ruleFolder).listFiles().length == 0) {
1098 removedRuleModifiedGroup(controllerName);
1100 // This is an update in terms of PDPD.
1101 addModifiedGroup(controllerName, "update");
1105 // Removes Policy from Memory and Database.
1106 private void removePolicyFromGroup(String policyName, String controllerName) {
1107 policyMap.remove(policyName);
1108 EntityTransaction et = em.getTransaction();
1110 Query query = em.createQuery("select b from BRMSPolicyInfo as b where b.policyName = :pn");
1111 query.setParameter("pn", policyName);
1112 List<?> pList = query.getResultList();
1113 BRMSPolicyInfo brmsPolicyInfo = new BRMSPolicyInfo();
1114 if (pList.size() > 0) {
1116 brmsPolicyInfo = (BRMSPolicyInfo) pList.get(0);
1117 if (brmsPolicyInfo.getControllerName().getControllerName().equals(controllerName)) {
1118 em.remove(brmsPolicyInfo);
1125 private void setVersion(String newVersion, String controllerName) {
1126 PEDependency userController = (PEDependency) groupMap.get(controllerName).get(0);
1127 userController.setVersion(newVersion);
1128 groupMap.get(controllerName).set(0, userController);
1131 // Return BackUpMonitor
1132 public static BackUpMonitor getBackUpMonitor() {
1136 public void rotateURLs() {
1137 if (repURLs != null) {
1138 Collections.rotate(repURLs, -1);
1142 public int URLListSize() {
1143 if (repURLs != null) {
1144 return repURLs.size();