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.IntegrityMonitor;
77 import org.onap.policy.common.logging.eelf.MessageCodes;
78 import org.onap.policy.common.logging.eelf.PolicyLogger;
79 import org.onap.policy.common.logging.flexlogger.FlexLogger;
80 import org.onap.policy.common.logging.flexlogger.Logger;
81 import org.onap.policy.utils.BackUpHandler;
82 import org.onap.policy.utils.BackUpMonitor;
83 import org.onap.policy.utils.BusPublisher;
84 import org.onap.policy.utils.PolicyUtils;
85 import org.onap.policy.xacml.api.XACMLErrorConstants;
86 import org.sonatype.nexus.client.NexusClient;
87 import org.sonatype.nexus.client.NexusClientException;
88 import org.sonatype.nexus.client.NexusConnectionException;
89 import org.sonatype.nexus.client.rest.NexusRestClient;
90 import org.sonatype.nexus.rest.model.NexusArtifact;
92 import com.att.nsa.cambria.client.CambriaBatchingPublisher;
93 import com.att.nsa.cambria.client.CambriaClientBuilders;
94 import com.att.nsa.cambria.client.CambriaClientBuilders.PublisherBuilder;
95 import com.fasterxml.jackson.core.JsonProcessingException;
98 * BRMSPush: Application responsible to push policies to the BRMS PDP Policy Repository (PR). Mavenize and push policy
104 @SuppressWarnings("deprecation")
105 public class BRMSPush {
106 private static final String GROUP_NAMES = "groupNames";
107 private static final String DROOLS_APPS_PACKAGE = "org.onap.policy.drools-applications";
108 private static final String META_INF = "META-INF";
109 private static final String KMODULE_XML_FILE = "kmodule.xml";
110 private static final String POM_XML_FILE = "pom.xml";
111 private static final String VERSION_0_1_0 = "0.1.0";
112 private static final String RULES = "rules";
113 private static final String RESOURCES = "resources";
114 private static final Logger LOGGER = FlexLogger.getLogger(BRMSPush.class.getName());
115 private static final String PROJECTSLOCATION = "RuleProjects";
116 private static final String[] GOALS = { "clean", "deploy" };
117 private static final String DEFAULT_VERSION = "1.2.0-SNAPSHOT";
118 private static final String DEPENDENCY_FILE = "dependency.json";
119 private static final String BRMSPERSISTENCE = "brmsEclipselink.persistencexml";
121 private static Map<String, String> modifiedGroups = new HashMap<>();
122 private static IntegrityMonitor im;
123 private static BackUpMonitor bm;
124 private String defaultName = null;
125 private String repID = null;
126 private String repName = null;
127 private ArrayList<String> repURLs = null;
128 private String repUserName = null;
129 private String repPassword = null;
130 private String policyKeyID = null;
131 private boolean createFlag = false;
132 private String uebList = null;
133 private List<String> dmaapList = null;
134 private String pubTopic = null;
135 private PublisherBuilder pubBuilder = null;
136 protected BusPublisher publisher = null;
137 private Long uebDelay = Long.parseLong("20");
138 private Long dmaapDelay = Long.parseLong("5000");
139 private String notificationType = null;
140 private ArrayList<ControllerPOJO> controllers;
141 private HashMap<String, ArrayList<Object>> groupMap = new HashMap<>();
142 private Map<String, String> policyMap = new HashMap<>();
143 private String brmsdependencyversion;
144 private EntityManager em;
145 private boolean syncFlag = false;
147 public BRMSPush(String propertiesFile, BackUpHandler handler) throws PolicyException {
148 if(propertiesFile==null || handler==null){
149 throw new PolicyException("Error no propertiesFile or handler");
151 Properties config = new Properties();
152 Path file = Paths.get(propertiesFile);
153 if (Files.notExists(file)) {
154 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Config File doesn't Exist in the specified Path "
156 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
157 + "Config File doesn't Exist in the specified Path " + file.toString());
159 if (file.toString().endsWith(".properties")) {
160 // Grab the Properties.
161 setProperty(file, config, handler);
166 private void setProperty(Path file, Properties config, BackUpHandler handler) throws PolicyException {
169 in = new FileInputStream(file.toFile());
171 } catch (IOException e) {
173 XACMLErrorConstants.ERROR_DATA_ISSUE + "Data/File Read Error while reading from the property file.",
175 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
176 + "Data/File Read Error while reading from the property file.");
178 LOGGER.info("Trying to set up IntegrityMonitor");
179 String resourceName = null;
181 LOGGER.info("Trying to set up IntegrityMonitor");
182 resourceName = config.getProperty("RESOURCE_NAME");
183 if (resourceName == null) {
184 LOGGER.warn("RESOURCE_NAME is missing setting default value. ");
185 resourceName = "brmsgw_pdp01";
187 resourceName = resourceName.trim();
188 setIntegrityMonitor(IntegrityMonitor.getInstance(resourceName, config));
189 } catch (Exception e) {
190 LOGGER.error("Error starting Integerity Monitor: " + e);
192 LOGGER.info("Trying to set up BackUpMonitor");
194 setBackupMonitor(BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), resourceName, config,
196 } catch (Exception e) {
197 LOGGER.error("Error starting BackUpMonitor: " + e);
199 if(!config.containsKey(BRMSPERSISTENCE)){
200 config.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, "META-INF/persistenceBRMS.xml");
202 config.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, config.getProperty(BRMSPERSISTENCE,"META-INF/persistenceBRMS.xml"));
204 EntityManagerFactory emf = Persistence.createEntityManagerFactory("BRMSGW", config);
205 em = emf.createEntityManager();
206 defaultName = config.getProperty("defaultName");
207 if (defaultName == null) {
209 XACMLErrorConstants.ERROR_DATA_ISSUE + "defaultName property is missing from the property file ");
210 throw new PolicyException(
211 XACMLErrorConstants.ERROR_DATA_ISSUE + "defaultName property is missing from the property file");
213 defaultName = defaultName.trim();
214 repID = config.getProperty("repositoryID");
217 XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryID property is missing from the property file ");
218 throw new PolicyException(
219 XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryID property is missing from the property file ");
221 repID = repID.trim();
222 repName = config.getProperty("repositoryName");
223 if (repName == null) {
224 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
225 + "repositoryName property is missing from the property file ");
226 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
227 + "repositoryName property is missing from the property file ");
229 repName = repName.trim();
230 String repURL = config.getProperty("repositoryURL");
231 if (repURL == null) {
233 XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryURL property is missing from the property file ");
234 throw new PolicyException(
235 XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryURL property is missing from the property file ");
237 if (repURL.contains(",")) {
238 repURLs = new ArrayList<>(Arrays.asList(repURL.trim().split(",")));
240 repURLs = new ArrayList<>();
243 repUserName = config.getProperty("repositoryUsername");
244 repPassword = config.getProperty("repositoryPassword");
245 if (repUserName == null || repPassword == null) {
246 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
247 + "repostoryUserName and respositoryPassword properties are required.");
248 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
249 + "repostoryUserName and respositoryPassword properties are required.");
251 repUserName = repUserName.trim();
252 repPassword = repPassword.trim();
253 policyKeyID = config.getProperty("policyKeyID");
254 if (policyKeyID == null) {
256 XACMLErrorConstants.ERROR_DATA_ISSUE + "policyKeyID property is missing from the property file ");
257 throw new PolicyException(
258 XACMLErrorConstants.ERROR_DATA_ISSUE + "policyKeyID property is missing from the property file ");
260 policyKeyID = policyKeyID.trim();
261 String syncF = config.getProperty("sync", "false").trim();
262 syncFlag = Boolean.parseBoolean(syncF);
264 PolicyLogger.info("SYNC Flag is turned ON. DB will be given Priority.");
266 brmsdependencyversion = config.getProperty("brms.dependency.version");
267 if (brmsdependencyversion == null) {
268 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
269 + "brmsdependencyversion property is missing from the property file, Using default Version.");
270 brmsdependencyversion = DEFAULT_VERSION;
272 brmsdependencyversion = brmsdependencyversion.trim();
276 notificationType = config.getProperty("NOTIFICATION_TYPE");
277 if ("dmaap".equalsIgnoreCase(notificationType)) {
279 LOGGER.info("Notification Type being used is DMaaP... creating instance of BusPublisher.");
280 // Setting up the Publisher for DMaaP MR
281 String dmaapServers = config.getProperty("NOTIFICATION_SERVERS");
282 pubTopic = config.getProperty("NOTIFICATION_TOPIC");
283 String aafLogin = config.getProperty("CLIENT_ID").trim();
284 String aafPassword = config.getProperty("CLIENT_KEY").trim();
286 if (dmaapServers == null || pubTopic == null) {
288 XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file ");
289 throw new PolicyException(
290 XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file ");
293 dmaapServers = dmaapServers.trim();
294 pubTopic = pubTopic.trim();
296 if (dmaapServers.contains(",")) {
297 dmaapList = new ArrayList<>(Arrays.asList(dmaapServers.split("\\s*,\\s*")));
299 dmaapList = new ArrayList<>();
300 dmaapList.add(dmaapServers);
303 this.publisher = new BusPublisher.DmaapPublisherWrapper(this.dmaapList, this.pubTopic, aafLogin,
306 String dDelay = config.getProperty("NOTIFICATION_DELAY");
307 if (dDelay != null && !dDelay.isEmpty()) {
308 dDelay = dDelay.trim();
310 dmaapDelay = Long.parseLong(dDelay);
311 } catch (NumberFormatException e) {
312 LOGGER.error("DMAAP_DELAY not a long format number" + e);
315 LOGGER.info("DMAAP BusPublisher is created.");
318 LOGGER.info("Notification Type being used is UEB... creating instance of PublisherBuilder.");
319 // Setting up the Publisher for UEB
320 uebList = config.getProperty("NOTIFICATION_SERVERS");
321 pubTopic = config.getProperty("NOTIFICATION_TOPIC");
322 String apiKey = config.getProperty("UEB_API_KEY");
323 String apiSecret = config.getProperty("UEB_API_SECRET");
324 if (uebList == null || pubTopic == null) {
326 XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file ");
327 throw new PolicyException(
328 XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file ");
330 uebList = uebList.trim();
331 pubTopic = pubTopic.trim();
332 pubBuilder = new CambriaClientBuilders.PublisherBuilder();
333 pubBuilder.usingHosts(uebList).onTopic(pubTopic);
334 if (apiKey != null && !apiKey.isEmpty() && apiSecret != null && !apiSecret.isEmpty()) {
335 apiKey = apiKey.trim();
336 apiSecret = apiSecret.trim();
337 pubBuilder.authenticatedBy(apiKey, apiSecret);
339 String uDelay = config.getProperty("NOTIFICATION_DELAY");
340 if (uDelay != null && !uDelay.isEmpty()) {
341 uDelay = uDelay.trim();
343 uebDelay = Long.parseLong(uDelay);
344 } catch (NumberFormatException e) {
345 LOGGER.error("UEB_DELAY not a long format number" + e);
348 LOGGER.info("UEB PublisherBuilder is created.");
354 private static void setBackupMonitor(BackUpMonitor instance) {
358 private static void setIntegrityMonitor(IntegrityMonitor instance) {
363 * Will Initialize the variables required for BRMSPush.
365 public void initiate(boolean flag) {
366 resetModifiedGroups();
367 controllers = new ArrayList<>();
369 bm.updateNotification();
370 } catch (Exception e) {
371 LOGGER.error("Error while updating Notification: " + e.getMessage(), e);
377 private static void resetModifiedGroups() {
378 modifiedGroups = new HashMap<>();
382 * Will Add rules to projects. Creates necessary folders if required.
384 public void addRule(String name, String rule, Map<String, String> responseAttributes) {
385 // 1 check the response Attributes and determine if this belongs to any projects.
386 // 2 if not create folder
389 // 5 store the groups that have been updated.
390 String kSessionName = null;
391 String selectedName = null;
392 if (!responseAttributes.isEmpty()) {
393 // Pick selected Value
394 String userControllerName = null;
395 ArrayList<PEDependency> userDependencies = new ArrayList<>();
396 for (Map.Entry<String, String> entry: responseAttributes.entrySet()) {
397 String key = entry.getKey();
398 String value = entry.getValue();
399 if (key.equals(policyKeyID)) {
400 selectedName = value;
402 // kmodule configurations
403 else if ("kSessionName".equals(key)) {
404 kSessionName = value;
406 // Check User Specific values.
407 if ("$controller:".equals(key)) {
409 PEDependency dependency = PolicyUtils.jsonStringToObject(value,
411 userControllerName = key.replaceFirst("$controller:", "");
412 addToGroup(userControllerName, dependency);
413 } catch (Exception e) {
414 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while resolving Controller: " + e);
417 } else if ("$dependency$".equals(key) && value.startsWith("[") && value.endsWith("]")) {
418 value = value.substring(1, value.length() - 1).trim();
419 List<String> dependencyStrings = Arrays.asList(value.split("},{"));
420 for (String dependencyString : dependencyStrings) {
423 .add(PolicyUtils.jsonStringToObject(dependencyString, PEDependency.class));
424 } catch (Exception e) {
425 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
426 + "Error while resolving Dependencies: " + e);
431 if (userControllerName != null) {
432 // Adding custom dependencies here.
433 ArrayList<Object> values = groupMap.get(userControllerName);
434 values.add(userDependencies);
435 groupMap.put(userControllerName, values);
436 selectedName = userControllerName;
439 // If no Match then pick Default.
440 if (selectedName == null) {
441 selectedName = defaultName;
443 if (groupMap.containsKey(selectedName)) {
444 // If the key is not got as parameters set by the user, setting the default value for kSessionName as
446 if (kSessionName == null) {
447 if (selectedName == defaultName) {
448 kSessionName = "closedloop";
450 kSessionName = "closedloop-" + selectedName;
453 // create directories if missing.
454 manageProject(selectedName, kSessionName, name, rule);
455 addModifiedGroup(selectedName, "update"); // Will check for Create Later after generating the Pom.
459 private void syncGroupInfo() {
460 // Sync DB to JMemory.
461 EntityTransaction et = em.getTransaction();
463 Query query = em.createQuery("select b from BRMSGroupInfo AS b");
464 List<?> bList = query.getResultList();
465 if (bList.size() != groupMap.size()) {
466 for (Object value : bList) {
467 BRMSGroupInfo brmsGroupInfo = (BRMSGroupInfo) value;
468 PEDependency dependency = new PEDependency();
469 dependency.setArtifactId(brmsGroupInfo.getArtifactId());
470 dependency.setGroupId(brmsGroupInfo.getGroupId());
471 dependency.setVersion(brmsGroupInfo.getVersion());
472 ArrayList<Object> values = new ArrayList<>();
473 values.add(dependency);
474 groupMap.put(brmsGroupInfo.getControllerName(), values);
477 query = em.createQuery("select g from BRMSPolicyInfo AS g");
478 bList = query.getResultList();
479 if (bList.size() != policyMap.size()) {
480 for (Object value : bList) {
481 BRMSPolicyInfo brmsPolicyInfo = (BRMSPolicyInfo) value;
482 policyMap.put(brmsPolicyInfo.getPolicyName(), brmsPolicyInfo.getControllerName().getControllerName());
486 LOGGER.info("Updated Local Memory values with values from database.");
489 private void manageProject(String selectedName, String kSessionName, String name, String rule) {
490 // Check if the Project is in Sync. If not get the latest Version.
491 syncProject(selectedName);
492 createProject(PROJECTSLOCATION + File.separator + getArtifactID(selectedName) + File.separator + "src"
493 + File.separator + "main" + File.separator + RESOURCES, kSessionName);
494 copyDataToFile(PROJECTSLOCATION + File.separator + getArtifactID(selectedName) + File.separator + "src"
495 + File.separator + "main" + File.separator + RESOURCES + File.separator + RULES + File.separator
496 + name + ".drl", rule);
497 addToPolicy(name, selectedName);
501 * Add Policy to JMemory and DataBase.
503 private void addToPolicy(String policyName, String controllerName) {
504 policyMap.put(policyName, controllerName);
505 EntityTransaction et = em.getTransaction();
507 Query query = em.createQuery("select b from BRMSPolicyInfo as b where b.policyName = :pn");
508 query.setParameter("pn", policyName);
509 List<?> pList = query.getResultList();
510 boolean create = false;
511 BRMSPolicyInfo brmsPolicyInfo = new BRMSPolicyInfo();
512 if (!pList.isEmpty()) {
514 brmsPolicyInfo = (BRMSPolicyInfo) pList.get(0);
515 if (!brmsPolicyInfo.getControllerName().getControllerName().equals(controllerName)) {
522 query = em.createQuery("select b from BRMSGroupInfo as b where b.controllerName = :cn");
523 query.setParameter("cn", controllerName);
524 List<?> bList = query.getResultList();
525 BRMSGroupInfo brmsGroupInfo = new BRMSGroupInfo();
526 if (!bList.isEmpty()) {
527 brmsGroupInfo = (BRMSGroupInfo) bList.get(0);
529 brmsPolicyInfo.setPolicyName(policyName);
530 brmsPolicyInfo.setControllerName(brmsGroupInfo);
531 em.persist(brmsPolicyInfo);
537 private void syncProject(String selectedName) {
538 boolean projectExists = checkProject(selectedName);
541 version = getVersion(selectedName);
542 if (version == null) {
543 LOGGER.error("Error getting local version for the given Controller Name:" + selectedName
544 + " going with Default value");
545 version = VERSION_0_1_0;
547 String nextVersion = incrementVersion(version);
548 boolean outOfSync = checkRemoteSync(selectedName, nextVersion);
553 // We are out of Sync or Project is not Present.
554 downloadProject(selectedName);
557 private void downloadProject(String selectedName) {
558 NexusArtifact artifact = getLatestArtifactFromNexus(selectedName);
559 if (artifact == null)
561 String dirName = getDirectoryName(selectedName);
563 String fileName = "rule.jar";
565 website = new URL(artifact.getResourceURI());
566 ReadableByteChannel rbc = Channels.newChannel(website.openStream());
567 FileOutputStream fos = new FileOutputStream(fileName);
568 fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
570 extractJar(fileName, dirName);
571 new File(fileName).delete();
572 } catch (IOException e) {
573 LOGGER.error("Error while downloading the project to File System. " + e.getMessage(), e);
577 private void extractJar(String jarFileName, String artifactId) throws IOException {
578 JarFile jar = new JarFile(jarFileName);
579 Enumeration<?> enumEntries = jar.entries();
580 while (enumEntries.hasMoreElements()) {
581 JarEntry file = (JarEntry) enumEntries.nextElement();
583 String fileName = file.getName().substring(file.getName().lastIndexOf("/") + 1);
584 if (file.getName().endsWith(".drl")) {
585 String path = PROJECTSLOCATION + File.separator + artifactId + File.separator + "src" + File.separator
586 + "main" + File.separator + RESOURCES + File.separator + RULES;
587 new File(path).mkdirs();
588 if (syncFlag && policyMap.containsKey(fileName.replace(".drl", ""))) {
589 f = new File(path + File.separator + fileName);
591 f = new File(path + File.separator + fileName);
593 } else if (file.getName().endsWith(POM_XML_FILE)) {
594 String path = PROJECTSLOCATION + File.separator + artifactId;
595 new File(path).mkdirs();
596 f = new File(path + File.separator + fileName);
597 } else if (file.getName().endsWith(KMODULE_XML_FILE)) {
598 String path = PROJECTSLOCATION + File.separator + artifactId + File.separator + "src" + File.separator
599 + "main" + File.separator + RESOURCES + File.separator + META_INF;
600 new File(path).mkdirs();
601 f = new File(path + File.separator + fileName);
604 InputStream is = jar.getInputStream(file);
605 FileOutputStream fos = new FileOutputStream(f);
606 while (is.available() > 0) {
607 fos.write(is.read());
611 LOGGER.info(fileName + " Created..");
617 private NexusArtifact getLatestArtifactFromNexus(String selectedName) {
618 List<NexusArtifact> artifacts = getArtifactFromNexus(selectedName, null);
621 NexusArtifact result = null;
622 for (NexusArtifact artifact : artifacts) {
623 int majorVal = Integer.parseInt(artifact.getVersion().substring(0, artifact.getVersion().indexOf(".")));
624 int minorVal = Integer.parseInt(artifact.getVersion().substring(artifact.getVersion().indexOf(".") + 1,
625 artifact.getVersion().lastIndexOf(".")));
626 if (majorVal > bigNum) {
630 if ((bigNum == majorVal) && (minorVal > smallNum)) {
633 if (bigNum == majorVal && minorVal == smallNum) {
637 return additionalNexusLatestCheck(selectedName, result);
640 // Additional Check due to Limitations from Nexus API to check if the artifact is the latest.
641 private NexusArtifact additionalNexusLatestCheck(String selectedName, NexusArtifact result) {
645 String nextVersion = incrementVersion(result.getVersion());
646 List<NexusArtifact> artifact = getArtifactFromNexus(selectedName, nextVersion);
647 return artifact.isEmpty() ? result : additionalNexusLatestCheck(selectedName, artifact.get(0));
650 private boolean checkRemoteSync(String selectedName, String version) {
651 List<NexusArtifact> artifacts = getArtifactFromNexus(selectedName, version);
652 return artifacts.isEmpty() ? false : true;
655 private List<NexusArtifact> getArtifactFromNexus(String selectedName, String version) {
656 final NexusClient client = new NexusRestClient();
658 boolean flag = false;
659 while (i < repURLs.size()) {
661 String repURL = repURLs.get(0);
662 client.connect(repURL.substring(0, repURL.indexOf(repURL.split(":[0-9]+\\/nexus")[1])), repUserName,
664 final NexusArtifact template = new NexusArtifact();
665 template.setGroupId(getGroupID(selectedName));
666 template.setArtifactId(getArtifactID(selectedName));
667 if (version != null) {
668 template.setVersion(version);
670 List<NexusArtifact> resultList = client.searchByGAV(template);
671 if (resultList != null) {
675 } catch (NexusClientException | NexusConnectionException | NullPointerException e) {
676 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Connection to remote Nexus has failed. "
677 + e.getMessage(), e);
681 } catch (NexusClientException | NexusConnectionException e) {
682 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "failed to disconnect Connection from Nexus."
683 + e.getMessage(), e);
686 Collections.rotate(repURLs, -1);
691 return new ArrayList<>();
694 private void setVersion(String selectedName) {
695 String newVersion = VERSION_0_1_0;
697 NexusArtifact artifact = getLatestArtifactFromNexus(selectedName);
698 if (artifact != null) {
699 newVersion = incrementVersion(artifact.getVersion());
701 if (VERSION_0_1_0.equals(newVersion)) {
704 setVersion(newVersion, selectedName);
705 LOGGER.info("Controller: " + selectedName + "is on version: " + newVersion);
708 private String incrementVersion(String version) {
709 int majorVal = Integer.parseInt(version.substring(0, version.indexOf(".")));
710 int minorVal = Integer.parseInt(version.substring(version.indexOf(".") + 1, version.lastIndexOf(".")));
717 return majorVal + "." + minorVal + version.substring(version.lastIndexOf("."));
720 private boolean checkProject(String selectedName) {
721 return new File(PROJECTSLOCATION + File.separator + getDirectoryName(selectedName)).exists();
724 private String getDirectoryName(String selectedName) {
725 return getArtifactID(selectedName);
729 * Will Push policies to the PolicyRepo.
731 * @param notificationType
732 * <String> type of notification Type.
733 * @throws PolicyException
735 public void pushRules() throws PolicyException {
736 // Check how many groups have been updated.
737 // Invoke their Maven process.
739 im.startTransaction();
740 } catch (Exception e) {
741 LOGGER.error("Error while starting Transaction " + e);
743 if (!modifiedGroups.isEmpty()) {
744 Boolean flag = false;
745 for (Map.Entry<String, String> entry : modifiedGroups.entrySet()) {
746 InvocationResult result = null;
747 String group = entry.getKey();
749 InvocationRequest request = new DefaultInvocationRequest();
752 request.setPomFile(new File(
753 PROJECTSLOCATION + File.separator + getArtifactID(group) + File.separator + POM_XML_FILE));
754 request.setGoals(Arrays.asList(GOALS));
755 Invoker invoker = new DefaultInvoker();
756 result = invoker.execute(request);
757 if (result.getExecutionException() != null) {
758 LOGGER.error(result.getExecutionException());
759 } else if (result.getExitCode() != 0) {
760 LOGGER.error("Maven Invocation failure..!");
762 } catch (Exception e) {
763 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation issue for "
764 + getArtifactID(group) + e.getMessage(), e);
766 if (result != null && result.getExitCode() == 0) {
767 LOGGER.info("Build Completed..!");
769 addNotification(group, "create");
771 addNotification(group, entry.getValue());
775 throw new PolicyException(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation failure!");
779 sendNotification(controllers);
788 * Removes a Rule from Rule Projects.
790 public void removeRule(String name) {
791 String controllerName = getGroupName(name);
792 if (controllerName == null) {
793 LOGGER.info("Error finding the controllerName for the given Policy: " + name);
796 syncProject(controllerName);
797 getNameAndSetRemove(controllerName, name);
800 private String getGroupName(String name) {
801 if (policyMap.containsKey(name)) {
802 return policyMap.get(name);
805 return policyMap.containsKey(name) ? policyMap.get(name) : null;
809 private void addModifiedGroup(String controllerName, String operation) {
810 if (controllerName != null) {
811 modifiedGroups.put(controllerName, operation);
815 private void addNotification(String controllerName, String operation) {
816 ControllerPOJO controllerPOJO = new ControllerPOJO();
817 controllerPOJO.setName(controllerName);
818 controllerPOJO.setOperation(operation);
819 HashMap<String, String> drools = new HashMap<>();
820 drools.put("groupId", getGroupID(controllerName));
821 drools.put("artifactId", getArtifactID(controllerName));
822 drools.put("version", getVersion(controllerName));
823 controllerPOJO.setDrools(drools);
824 controllers.add(controllerPOJO);
826 LOGGER.debug("Notification added: " + PolicyUtils.objectToJsonString(controllerPOJO));
827 } catch (JsonProcessingException e) {
828 LOGGER.error(MessageCodes.ERROR_SCHEMA_INVALID + "Json Processing Error " + e);
832 private void removedRuleModifiedGroup(String controllerName) {
833 // This will be sending Notification to PDPD directly to Lock
834 ControllerPOJO controllerPOJO = new ControllerPOJO();
835 controllerPOJO.setName(controllerName);
836 controllerPOJO.setOperation("lock");
837 List<ControllerPOJO> controllerPojos = new ArrayList<>();
838 controllerPojos.add(controllerPOJO);
839 sendNotification(controllerPojos);
842 private void sendNotification(List<ControllerPOJO> controllers) {
843 NotificationPOJO notification = new NotificationPOJO();
844 String requestId = UUID.randomUUID().toString();
845 LOGGER.info("Generating notification RequestID : " + requestId);
846 notification.setRequestID(requestId);
847 notification.setEntity("controller");
848 notification.setControllers(controllers);
850 String notificationJson = PolicyUtils.objectToJsonString(notification);
851 LOGGER.info("Sending Notification :\n" + notificationJson);
852 sendMessage(notificationJson);
853 } catch (Exception e) {
854 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while sending notification to PDP-D "
855 + e.getMessage(), e);
859 private void sendMessage(String message) throws IOException, GeneralSecurityException, InterruptedException {
861 if ("dmaap".equalsIgnoreCase(notificationType)) {
862 // Sending Message through DMaaP Message Router
863 LOGGER.debug("DMAAP Publishing Message");
865 publisher.send("MyPartitionKey", message);
867 LOGGER.debug("Message Published on DMaaP :" + dmaapList.get(0) + "for Topic: " + pubTopic);
869 Thread.sleep(dmaapDelay);
872 // Sending Message through UEB interface.
873 LOGGER.debug("UEB Publishing Message");
875 CambriaBatchingPublisher pub = pubBuilder.build();
876 pub.send("MyPartitionKey", message);
878 final List<?> stuck = pub.close(uebDelay, TimeUnit.SECONDS);
879 if (!stuck.isEmpty()) {
880 LOGGER.error(stuck.size() + " messages unsent");
882 LOGGER.debug("Clean exit; Message Published on UEB : " + uebList + "for Topic: " + pubTopic);
888 private void createPom(String name) {
889 Model model = new Model();
890 model.setModelVersion("4.0.0");
891 model.setGroupId(getGroupID(name));
892 model.setArtifactId(getArtifactID(name));
893 model.setVersion(getVersion(name));
895 DistributionManagement distributionManagement = new DistributionManagement();
896 DeploymentRepository repository = new DeploymentRepository();
897 repository.setId(repID);
898 repository.setName(repName);
899 repository.setUrl(repURLs.get(0));
900 distributionManagement.setRepository(repository);
901 model.setDistributionManagement(distributionManagement);
902 // Dependency Management goes here.
903 List<Dependency> dependencyList = new ArrayList<>();
904 if (groupMap.get(name).size() > 1) {
905 @SuppressWarnings("unchecked")
906 ArrayList<PEDependency> dependencies = (ArrayList<PEDependency>) groupMap.get(name).get(1);
907 for (PEDependency dependency : dependencies) {
908 dependencyList.add(dependency.getDependency());
911 // Add Default dependencies.
912 dependencyList = getDependencies(name);
914 model.setDependencies(dependencyList);
915 Writer writer = null;
917 writer = WriterFactory.newXmlWriter(
918 new File(PROJECTSLOCATION + File.separator + getArtifactID(name) + File.separator + POM_XML_FILE));
919 MavenXpp3Writer pomWriter = new MavenXpp3Writer();
920 pomWriter.write(writer, model);
921 } catch (Exception e) {
922 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while creating POM for " + getArtifactID(name)
923 + e.getMessage(), e);
925 IOUtil.close(writer);
929 private List<Dependency> getDependencies(String controllerName) {
930 // Read the Dependency Information from property file.
931 Path file = Paths.get(DEPENDENCY_FILE);
932 if (!Files.notExists(file)) {
934 String dependencyJSON = new String(Files.readAllBytes(file), StandardCharsets.UTF_8);
935 DependencyInfo dependencyInfo = PolicyUtils.jsonStringToObject(dependencyJSON, DependencyInfo.class);
936 String controller = "default";
937 if (dependencyInfo.getDependencies().containsKey(controllerName)) {
938 controller = controllerName;
940 List<Dependency> dependencyList = new ArrayList<>();
941 for (PEDependency dependency : dependencyInfo.getDependencies().get(controller)) {
942 dependencyList.add(dependency.getDependency());
944 return dependencyList;
945 } catch (IOException | NullPointerException e) {
946 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
947 + "Error while getting dependecy Information for controller: " + controllerName
948 + e.getMessage(), e);
951 return defaultDependencies(controllerName);
954 // Default Dependency Section. Can be changed as required.
955 public List<Dependency> defaultDependencies(String controllerName) {
957 List<Dependency> dependencyList = new ArrayList<>();
958 String version = StringEscapeUtils.escapeJava(brmsdependencyversion);
960 Dependency demoDependency = new Dependency();
961 demoDependency.setGroupId(DROOLS_APPS_PACKAGE);
962 demoDependency.setArtifactId("demo");
963 demoDependency.setVersion(version);
964 dependencyList.add(demoDependency);
966 Dependency controlloopDependency = new Dependency();
967 controlloopDependency.setGroupId(DROOLS_APPS_PACKAGE);
968 controlloopDependency.setArtifactId("events");
969 controlloopDependency.setVersion(version);
970 dependencyList.add(controlloopDependency);
972 Dependency restDependency = new Dependency();
973 restDependency.setGroupId(DROOLS_APPS_PACKAGE);
974 restDependency.setArtifactId("rest");
975 restDependency.setVersion(version);
976 dependencyList.add(restDependency);
978 Dependency appcDependency = new Dependency();
979 appcDependency.setGroupId(DROOLS_APPS_PACKAGE);
980 appcDependency.setArtifactId("appc");
981 appcDependency.setVersion(version);
982 dependencyList.add(appcDependency);
984 Dependency aaiDependency = new Dependency();
985 aaiDependency.setGroupId(DROOLS_APPS_PACKAGE);
986 aaiDependency.setArtifactId("aai");
987 aaiDependency.setVersion(version);
988 dependencyList.add(aaiDependency);
990 Dependency msoDependency = new Dependency();
991 msoDependency.setGroupId(DROOLS_APPS_PACKAGE);
992 msoDependency.setArtifactId("mso");
993 msoDependency.setVersion(version);
994 dependencyList.add(msoDependency);
996 Dependency trafficgeneratorDependency = new Dependency();
997 trafficgeneratorDependency.setGroupId(DROOLS_APPS_PACKAGE);
998 trafficgeneratorDependency.setArtifactId("trafficgenerator");
999 trafficgeneratorDependency.setVersion(version);
1000 dependencyList.add(trafficgeneratorDependency);
1001 return dependencyList;
1004 private void createProject(String path, String ksessionName) {
1005 new File(path + File.separator + RULES).mkdirs();
1006 new File(path + File.separator + META_INF).mkdirs();
1007 if (!Files.exists(Paths.get(path + File.separator + META_INF + File.separator + KMODULE_XML_FILE))) {
1008 // Hard coding XML for PDP Drools to accept our Rules.
1009 String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "\n"
1010 + "<kmodule xmlns=\"http://jboss.org/kie/6.0.0/kmodule\">" + "\n"
1011 + "<kbase name=\"rules\" packages=\"rules\">" + "\n" + "<ksession name=\"" + ksessionName + "\"/>"
1012 + "\n" + "</kbase></kmodule>";
1013 copyDataToFile(path + File.separator + META_INF + File.separator + KMODULE_XML_FILE, xml);
1017 private void copyDataToFile(String file, String rule) {
1019 FileUtils.writeStringToFile(new File(file), rule);
1020 } catch (Exception e) {
1022 XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while creating Rule for " + file + e.getMessage(),
1027 private void readGroups(Properties config) throws PolicyException {
1028 String[] groupNames;
1029 String groupNamesError = "groupNames property is missing or empty from the property file ";
1030 if (!config.containsKey(GROUP_NAMES) || config.getProperty(GROUP_NAMES)==null){
1031 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
1034 if (config.getProperty(GROUP_NAMES).contains(",")) {
1035 groupNames = config.getProperty(GROUP_NAMES).replaceAll(" ", "").split(",");
1037 groupNames = new String[] { config.getProperty(GROUP_NAMES).replaceAll(" ", "") };
1039 if (groupNames == null || groupNames.length == 0) {
1040 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
1042 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
1045 groupMap = new HashMap<>();
1046 for (int counter = 0; counter < groupNames.length; counter++) {
1047 String name = groupNames[counter];
1048 String groupID = config.getProperty(name + ".groupID");
1049 if (groupID == null) {
1050 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1051 + ".groupID property is missing from the property file ");
1052 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1053 + ".groupID property is missing from the property file ");
1055 String artifactID = config.getProperty(name + ".artifactID");
1056 if (artifactID == null) {
1057 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1058 + ".artifactID property is missing from the property file ");
1059 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1060 + ".artifactID property is missing from the property file ");
1062 PEDependency dependency = new PEDependency();
1063 dependency.setArtifactId(artifactID);
1064 dependency.setGroupId(groupID);
1065 // Add to list if we got all
1066 addToGroup(name, dependency);
1070 private void addToGroup(String name, PEDependency dependency) {
1071 ArrayList<Object> values = new ArrayList<>();
1072 values.add(dependency);
1073 groupMap.put(name, values);
1074 EntityTransaction et = em.getTransaction();
1076 Query query = em.createQuery("select b from BRMSGroupInfo as b where b.controllerName = :cn");
1077 query.setParameter("cn", name);
1078 List<?> groupList = query.getResultList();
1079 BRMSGroupInfo brmsGroupInfo = null;
1080 if (!groupList.isEmpty()) {
1081 LOGGER.info("Controller name already Existing in DB. Will be updating the DB Values" + name);
1082 brmsGroupInfo = (BRMSGroupInfo) groupList.get(0);
1084 if (brmsGroupInfo == null) {
1085 brmsGroupInfo = new BRMSGroupInfo();
1087 brmsGroupInfo.setControllerName(name);
1088 brmsGroupInfo.setGroupId(dependency.getGroupId());
1089 brmsGroupInfo.setArtifactId(dependency.getArtifactId());
1090 brmsGroupInfo.setVersion(dependency.getVersion());
1091 em.persist(brmsGroupInfo);
1096 private String getArtifactID(String name) {
1097 return ((PEDependency) groupMap.get(name).get(0)).getArtifactId();
1100 private String getGroupID(String name) {
1101 return ((PEDependency) groupMap.get(name).get(0)).getGroupId();
1104 private String getVersion(String name) {
1105 return ((PEDependency) groupMap.get(name).get(0)).getVersion();
1108 private void getNameAndSetRemove(String controllerName, String policyName) {
1109 String artifactName = getArtifactID(controllerName);
1110 String ruleFolder = PROJECTSLOCATION + File.separator + artifactName + File.separator + "src" + File.separator
1111 + "main" + File.separator + RESOURCES + File.separator + RULES;
1112 File file = new File(ruleFolder + File.separator + policyName + ".drl");
1113 if (file.delete()) {
1114 LOGGER.info("Deleted File.. " + file.getAbsolutePath());
1115 removePolicyFromGroup(policyName, controllerName);
1117 if (new File(ruleFolder).listFiles().length == 0) {
1118 removedRuleModifiedGroup(controllerName);
1120 // This is an update in terms of PDPD.
1121 addModifiedGroup(controllerName, "update");
1125 // Removes Policy from Memory and Database.
1126 private void removePolicyFromGroup(String policyName, String controllerName) {
1127 policyMap.remove(policyName);
1128 EntityTransaction et = em.getTransaction();
1130 Query query = em.createQuery("select b from BRMSPolicyInfo as b where b.policyName = :pn");
1131 query.setParameter("pn", policyName);
1132 List<?> pList = query.getResultList();
1133 BRMSPolicyInfo brmsPolicyInfo;
1134 if (!pList.isEmpty()) {
1136 brmsPolicyInfo = (BRMSPolicyInfo) pList.get(0);
1137 if (brmsPolicyInfo.getControllerName().getControllerName().equals(controllerName)) {
1138 em.remove(brmsPolicyInfo);
1145 private void setVersion(String newVersion, String controllerName) {
1146 PEDependency userController = (PEDependency) groupMap.get(controllerName).get(0);
1147 userController.setVersion(newVersion);
1148 groupMap.get(controllerName).set(0, userController);
1151 // Return BackUpMonitor
1152 public static BackUpMonitor getBackUpMonitor() {
1156 public void rotateURLs() {
1157 if (repURLs != null) {
1158 Collections.rotate(repURLs, -1);
1162 public int urlListSize() {
1163 if (repURLs != null) {
1164 return repURLs.size();