2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 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_TEMPLATE_GROUP = "org.onap.policy.drools-applications.controlloop.templates";
108 private static final String DROOLS_APPS_MODEL_GROUP = "org.onap.policy.drools-applications.controlloop.common.model-impl";
109 private static final String META_INF = "META-INF";
110 private static final String KMODULE_XML_FILE = "kmodule.xml";
111 private static final String POM_XML_FILE = "pom.xml";
112 private static final String VERSION_0_1_0 = "0.1.0";
113 private static final String RULES = "rules";
114 private static final String RESOURCES = "resources";
115 private static final Logger LOGGER = FlexLogger.getLogger(BRMSPush.class.getName());
116 private static final String PROJECTSLOCATION = "RuleProjects";
117 private static final String[] GOALS = { "clean", "deploy" };
118 private static final String DEFAULT_VERSION = "1.2.0-SNAPSHOT";
119 private static final String DEPENDENCY_FILE = "dependency.json";
120 private static final String BRMSPERSISTENCE = "brmsEclipselink.persistencexml";
122 private static Map<String, String> modifiedGroups = new HashMap<>();
123 private static IntegrityMonitor im;
124 private static BackUpMonitor bm;
125 private String defaultName = null;
126 private String repID = null;
127 private String repName = null;
128 private ArrayList<String> repURLs = null;
129 private String repUserName = null;
130 private String repPassword = null;
131 private String policyKeyID = null;
132 private boolean createFlag = false;
133 private String uebList = null;
134 private List<String> dmaapList = null;
135 private String pubTopic = null;
136 private PublisherBuilder pubBuilder = null;
137 protected BusPublisher publisher = null;
138 private Long uebDelay = Long.parseLong("20");
139 private Long dmaapDelay = Long.parseLong("5000");
140 private String notificationType = null;
141 private ArrayList<ControllerPOJO> controllers;
142 private HashMap<String, ArrayList<Object>> groupMap = new HashMap<>();
143 private Map<String, String> policyMap = new HashMap<>();
144 private String brmsdependencyversion;
145 private EntityManager em;
146 private boolean syncFlag = false;
148 public BRMSPush(String propertiesFile, BackUpHandler handler) throws PolicyException {
149 if(propertiesFile==null || handler==null){
150 throw new PolicyException("Error no propertiesFile or handler");
152 Properties config = new Properties();
153 Path file = Paths.get(propertiesFile);
154 if (Files.notExists(file)) {
155 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Config File doesn't Exist in the specified Path "
157 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
158 + "Config File doesn't Exist in the specified Path " + file.toString());
160 if (file.toString().endsWith(".properties")) {
161 // Grab the Properties.
162 setProperty(file, config, handler);
167 private void setProperty(Path file, Properties config, BackUpHandler handler) throws PolicyException {
170 in = new FileInputStream(file.toFile());
172 } catch (IOException e) {
174 XACMLErrorConstants.ERROR_DATA_ISSUE + "Data/File Read Error while reading from the property file.",
176 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
177 + "Data/File Read Error while reading from the property file.");
179 LOGGER.info("Trying to set up IntegrityMonitor");
180 String resourceName = null;
182 LOGGER.info("Trying to set up IntegrityMonitor");
183 resourceName = config.getProperty("RESOURCE_NAME");
184 if (resourceName == null) {
185 LOGGER.warn("RESOURCE_NAME is missing setting default value. ");
186 resourceName = "brmsgw_pdp01";
188 resourceName = resourceName.trim();
189 setIntegrityMonitor(IntegrityMonitor.getInstance(resourceName, config));
190 } catch (Exception e) {
191 LOGGER.error("Error starting Integerity Monitor: " + e);
193 LOGGER.info("Trying to set up BackUpMonitor");
195 setBackupMonitor(BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), resourceName, config,
197 } catch (Exception e) {
198 LOGGER.error("Error starting BackUpMonitor: " + e);
200 if(!config.containsKey(BRMSPERSISTENCE)){
201 config.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, "META-INF/persistenceBRMS.xml");
203 config.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, config.getProperty(BRMSPERSISTENCE,"META-INF/persistenceBRMS.xml"));
205 EntityManagerFactory emf = Persistence.createEntityManagerFactory("BRMSGW", config);
206 em = emf.createEntityManager();
207 defaultName = config.getProperty("defaultName");
208 if (defaultName == null) {
210 XACMLErrorConstants.ERROR_DATA_ISSUE + "defaultName property is missing from the property file ");
211 throw new PolicyException(
212 XACMLErrorConstants.ERROR_DATA_ISSUE + "defaultName property is missing from the property file");
214 defaultName = defaultName.trim();
215 repID = config.getProperty("repositoryID");
218 XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryID property is missing from the property file ");
219 throw new PolicyException(
220 XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryID property is missing from the property file ");
222 repID = repID.trim();
223 repName = config.getProperty("repositoryName");
224 if (repName == null) {
225 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
226 + "repositoryName property is missing from the property file ");
227 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
228 + "repositoryName property is missing from the property file ");
230 repName = repName.trim();
231 String repURL = config.getProperty("repositoryURL");
232 if (repURL == null) {
234 XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryURL property is missing from the property file ");
235 throw new PolicyException(
236 XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryURL property is missing from the property file ");
238 if (repURL.contains(",")) {
239 repURLs = new ArrayList<>(Arrays.asList(repURL.trim().split(",")));
241 repURLs = new ArrayList<>();
244 repUserName = config.getProperty("repositoryUsername");
245 repPassword = config.getProperty("repositoryPassword");
246 if (repUserName == null || repPassword == null) {
247 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
248 + "repostoryUserName and respositoryPassword properties are required.");
249 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
250 + "repostoryUserName and respositoryPassword properties are required.");
252 repUserName = repUserName.trim();
253 repPassword = repPassword.trim();
254 policyKeyID = config.getProperty("policyKeyID");
255 if (policyKeyID == null) {
257 XACMLErrorConstants.ERROR_DATA_ISSUE + "policyKeyID property is missing from the property file ");
258 throw new PolicyException(
259 XACMLErrorConstants.ERROR_DATA_ISSUE + "policyKeyID property is missing from the property file ");
261 policyKeyID = policyKeyID.trim();
262 String syncF = config.getProperty("sync", "false").trim();
263 syncFlag = Boolean.parseBoolean(syncF);
265 PolicyLogger.info("SYNC Flag is turned ON. DB will be given Priority.");
267 brmsdependencyversion = config.getProperty("brms.dependency.version");
268 if (brmsdependencyversion == null) {
269 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
270 + "brmsdependencyversion property is missing from the property file, Using default Version.");
271 brmsdependencyversion = DEFAULT_VERSION;
273 brmsdependencyversion = brmsdependencyversion.trim();
277 notificationType = config.getProperty("NOTIFICATION_TYPE");
278 if ("dmaap".equalsIgnoreCase(notificationType)) {
280 LOGGER.info("Notification Type being used is DMaaP... creating instance of BusPublisher.");
281 // Setting up the Publisher for DMaaP MR
282 String dmaapServers = config.getProperty("NOTIFICATION_SERVERS");
283 pubTopic = config.getProperty("NOTIFICATION_TOPIC");
284 String aafLogin = config.getProperty("CLIENT_ID").trim();
285 String aafPassword = config.getProperty("CLIENT_KEY").trim();
287 if (dmaapServers == null || pubTopic == null) {
289 XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file ");
290 throw new PolicyException(
291 XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file ");
294 dmaapServers = dmaapServers.trim();
295 pubTopic = pubTopic.trim();
297 if (dmaapServers.contains(",")) {
298 dmaapList = new ArrayList<>(Arrays.asList(dmaapServers.split("\\s*,\\s*")));
300 dmaapList = new ArrayList<>();
301 dmaapList.add(dmaapServers);
304 this.publisher = new BusPublisher.DmaapPublisherWrapper(this.dmaapList, this.pubTopic, aafLogin,
307 String dDelay = config.getProperty("NOTIFICATION_DELAY");
308 if (dDelay != null && !dDelay.isEmpty()) {
309 dDelay = dDelay.trim();
311 dmaapDelay = Long.parseLong(dDelay);
312 } catch (NumberFormatException e) {
313 LOGGER.error("DMAAP_DELAY not a long format number" + e);
316 LOGGER.info("DMAAP BusPublisher is created.");
319 LOGGER.info("Notification Type being used is UEB... creating instance of PublisherBuilder.");
320 // Setting up the Publisher for UEB
321 uebList = config.getProperty("NOTIFICATION_SERVERS");
322 pubTopic = config.getProperty("NOTIFICATION_TOPIC");
323 String apiKey = config.getProperty("UEB_API_KEY");
324 String apiSecret = config.getProperty("UEB_API_SECRET");
325 if (uebList == null || pubTopic == null) {
327 XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file ");
328 throw new PolicyException(
329 XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file ");
331 uebList = uebList.trim();
332 pubTopic = pubTopic.trim();
333 pubBuilder = new CambriaClientBuilders.PublisherBuilder();
334 pubBuilder.usingHosts(uebList).onTopic(pubTopic);
335 if (apiKey != null && !apiKey.isEmpty() && apiSecret != null && !apiSecret.isEmpty()) {
336 apiKey = apiKey.trim();
337 apiSecret = apiSecret.trim();
338 pubBuilder.authenticatedBy(apiKey, apiSecret);
340 String uDelay = config.getProperty("NOTIFICATION_DELAY");
341 if (uDelay != null && !uDelay.isEmpty()) {
342 uDelay = uDelay.trim();
344 uebDelay = Long.parseLong(uDelay);
345 } catch (NumberFormatException e) {
346 LOGGER.error("UEB_DELAY not a long format number" + e);
349 LOGGER.info("UEB PublisherBuilder is created.");
355 private static void setBackupMonitor(BackUpMonitor instance) {
359 private static void setIntegrityMonitor(IntegrityMonitor instance) {
364 * Will Initialize the variables required for BRMSPush.
366 public void initiate(boolean flag) {
367 resetModifiedGroups();
368 controllers = new ArrayList<>();
370 bm.updateNotification();
371 } catch (Exception e) {
372 LOGGER.error("Error while updating Notification: " + e.getMessage(), e);
378 public void resetDS(){
379 resetModifiedGroups();
380 controllers = new ArrayList<>();
383 private static void resetModifiedGroups() {
384 modifiedGroups = new HashMap<>();
388 * Will Add rules to projects. Creates necessary folders if required.
390 public void addRule(String name, String rule, Map<String, String> responseAttributes) {
391 // 1 check the response Attributes and determine if this belongs to any projects.
392 // 2 if not create folder
395 // 5 store the groups that have been updated.
396 String kSessionName = null;
397 String selectedName = null;
398 if (!responseAttributes.isEmpty()) {
399 // Pick selected Value
400 String userControllerName = null;
401 ArrayList<PEDependency> userDependencies = new ArrayList<>();
402 for (Map.Entry<String, String> entry: responseAttributes.entrySet()) {
403 String key = entry.getKey();
404 String value = entry.getValue();
405 if (key.equals(policyKeyID)) {
406 selectedName = value;
408 // kmodule configurations
409 else if ("kSessionName".equals(key)) {
410 kSessionName = value;
412 // Check User Specific values.
413 if ("$controller:".equals(key)) {
415 PEDependency dependency = PolicyUtils.jsonStringToObject(value,
417 userControllerName = key.replaceFirst("$controller:", "");
418 LOGGER.info("addRule: userControllerName - " + userControllerName + ", dependency: - " + dependency);
419 addToGroup(userControllerName, dependency);
420 } catch (Exception e) {
421 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while resolving Controller: " + e);
424 } else if ("$dependency$".equals(key) && value.startsWith("[") && value.endsWith("]")) {
425 value = value.substring(1, value.length() - 1).trim();
426 List<String> dependencyStrings = Arrays.asList(value.split("},{"));
427 for (String dependencyString : dependencyStrings) {
430 .add(PolicyUtils.jsonStringToObject(dependencyString, PEDependency.class));
431 } catch (Exception e) {
432 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
433 + "Error while resolving Dependencies: " + e);
438 if (userControllerName != null) {
439 // Adding custom dependencies here.
440 ArrayList<Object> values = groupMap.get(userControllerName);
441 values.add(userDependencies);
442 groupMap.put(userControllerName, values);
443 selectedName = userControllerName;
446 // If no Match then pick Default.
447 if (selectedName == null) {
448 selectedName = defaultName;
450 if (groupMap.containsKey(selectedName)) {
451 // If the key is not got as parameters set by the user, setting the default value for kSessionName as
453 if (kSessionName == null) {
454 LOGGER.info("kSessionName is null, selectedName is : " + selectedName );
455 if (selectedName == defaultName) {
456 kSessionName = "closedloop";
458 kSessionName = "closedloop-" + selectedName;
461 // create directories if missing.
462 manageProject(selectedName, kSessionName, name, rule);
463 addModifiedGroup(selectedName, "update"); // Will check for Create Later after generating the Pom.
467 private void syncGroupInfo() {
468 // Sync DB to JMemory.
469 EntityTransaction et = em.getTransaction();
471 Query query = em.createQuery("select b from BRMSGroupInfo AS b");
472 List<?> bList = query.getResultList();
473 if (bList.size() != groupMap.size()) {
474 for (Object value : bList) {
475 BRMSGroupInfo brmsGroupInfo = (BRMSGroupInfo) value;
476 PEDependency dependency = new PEDependency();
477 dependency.setArtifactId(brmsGroupInfo.getArtifactId());
478 dependency.setGroupId(brmsGroupInfo.getGroupId());
479 dependency.setVersion(brmsGroupInfo.getVersion());
480 ArrayList<Object> values = new ArrayList<>();
481 values.add(dependency);
482 groupMap.put(brmsGroupInfo.getControllerName(), values);
485 query = em.createQuery("select g from BRMSPolicyInfo AS g");
486 bList = query.getResultList();
487 if (bList.size() != policyMap.size()) {
488 for (Object value : bList) {
489 BRMSPolicyInfo brmsPolicyInfo = (BRMSPolicyInfo) value;
490 policyMap.put(brmsPolicyInfo.getPolicyName(), brmsPolicyInfo.getControllerName().getControllerName());
494 LOGGER.info("Updated Local Memory values with values from database.");
497 private void manageProject(String selectedName, String kSessionName, String name, String rule) {
498 // Check if the Project is in Sync. If not get the latest Version.
499 syncProject(selectedName);
500 createProject(PROJECTSLOCATION + File.separator + getArtifactID(selectedName) + File.separator + "src"
501 + File.separator + "main" + File.separator + RESOURCES, kSessionName);
502 copyDataToFile(PROJECTSLOCATION + File.separator + getArtifactID(selectedName) + File.separator + "src"
503 + File.separator + "main" + File.separator + RESOURCES + File.separator + RULES + File.separator
504 + name + ".drl", rule);
505 addToPolicy(name, selectedName);
509 * Add Policy to JMemory and DataBase.
511 private void addToPolicy(String policyName, String controllerName) {
512 policyMap.put(policyName, controllerName);
513 EntityTransaction et = em.getTransaction();
515 Query query = em.createQuery("select b from BRMSPolicyInfo as b where b.policyName = :pn");
516 query.setParameter("pn", policyName);
517 List<?> pList = query.getResultList();
518 boolean create = false;
519 BRMSPolicyInfo brmsPolicyInfo = new BRMSPolicyInfo();
520 if (!pList.isEmpty()) {
522 brmsPolicyInfo = (BRMSPolicyInfo) pList.get(0);
523 if (!brmsPolicyInfo.getControllerName().getControllerName().equals(controllerName)) {
530 query = em.createQuery("select b from BRMSGroupInfo as b where b.controllerName = :cn");
531 query.setParameter("cn", controllerName);
532 List<?> bList = query.getResultList();
533 BRMSGroupInfo brmsGroupInfo = new BRMSGroupInfo();
534 if (!bList.isEmpty()) {
535 brmsGroupInfo = (BRMSGroupInfo) bList.get(0);
537 brmsPolicyInfo.setPolicyName(policyName);
538 brmsPolicyInfo.setControllerName(brmsGroupInfo);
539 em.persist(brmsPolicyInfo);
545 private void syncProject(String selectedName) {
546 boolean projectExists = checkProject(selectedName);
549 version = getVersion(selectedName);
550 if (version == null) {
551 LOGGER.error("Error getting local version for the given Controller Name:" + selectedName
552 + " going with Default value");
553 version = VERSION_0_1_0;
555 String nextVersion = incrementVersion(version);
556 boolean outOfSync = checkRemoteSync(selectedName, nextVersion);
561 // We are out of Sync or Project is not Present.
562 downloadProject(selectedName);
565 private void downloadProject(String selectedName) {
566 NexusArtifact artifact = getLatestArtifactFromNexus(selectedName);
567 if (artifact == null)
569 String dirName = getDirectoryName(selectedName);
571 String fileName = "rule.jar";
573 website = new URL(artifact.getResourceURI());
574 ReadableByteChannel rbc = Channels.newChannel(website.openStream());
575 FileOutputStream fos = new FileOutputStream(fileName);
576 fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
578 extractJar(fileName, dirName);
579 new File(fileName).delete();
580 } catch (IOException e) {
581 LOGGER.error("Error while downloading the project to File System. " + e.getMessage(), e);
585 private void extractJar(String jarFileName, String artifactId) throws IOException {
586 JarFile jar = new JarFile(jarFileName);
587 Enumeration<?> enumEntries = jar.entries();
588 while (enumEntries.hasMoreElements()) {
589 JarEntry file = (JarEntry) enumEntries.nextElement();
591 String fileName = file.getName().substring(file.getName().lastIndexOf("/") + 1);
592 if (file.getName().endsWith(".drl")) {
593 String path = PROJECTSLOCATION + File.separator + artifactId + File.separator + "src" + File.separator
594 + "main" + File.separator + RESOURCES + File.separator + RULES;
595 new File(path).mkdirs();
596 if (syncFlag && policyMap.containsKey(fileName.replace(".drl", ""))) {
597 f = new File(path + File.separator + fileName);
599 f = new File(path + File.separator + fileName);
601 } else if (file.getName().endsWith(POM_XML_FILE)) {
602 String path = PROJECTSLOCATION + File.separator + artifactId;
603 new File(path).mkdirs();
604 f = new File(path + File.separator + fileName);
605 } else if (file.getName().endsWith(KMODULE_XML_FILE)) {
606 String path = PROJECTSLOCATION + File.separator + artifactId + File.separator + "src" + File.separator
607 + "main" + File.separator + RESOURCES + File.separator + META_INF;
608 new File(path).mkdirs();
609 f = new File(path + File.separator + fileName);
612 InputStream is = jar.getInputStream(file);
613 FileOutputStream fos = new FileOutputStream(f);
614 while (is.available() > 0) {
615 fos.write(is.read());
619 LOGGER.info(fileName + " Created..");
625 private NexusArtifact getLatestArtifactFromNexus(String selectedName) {
626 List<NexusArtifact> artifacts = getArtifactFromNexus(selectedName, null);
629 NexusArtifact result = null;
630 for (NexusArtifact artifact : artifacts) {
631 int majorVal = Integer.parseInt(artifact.getVersion().substring(0, artifact.getVersion().indexOf(".")));
632 int minorVal = Integer.parseInt(artifact.getVersion().substring(artifact.getVersion().indexOf(".") + 1,
633 artifact.getVersion().lastIndexOf(".")));
634 if (majorVal > bigNum) {
638 if ((bigNum == majorVal) && (minorVal > smallNum)) {
641 if (bigNum == majorVal && minorVal == smallNum) {
645 return additionalNexusLatestCheck(selectedName, result);
648 // Additional Check due to Limitations from Nexus API to check if the artifact is the latest.
649 private NexusArtifact additionalNexusLatestCheck(String selectedName, NexusArtifact result) {
653 String nextVersion = incrementVersion(result.getVersion());
654 List<NexusArtifact> artifact = getArtifactFromNexus(selectedName, nextVersion);
655 return artifact.isEmpty() ? result : additionalNexusLatestCheck(selectedName, artifact.get(0));
658 private boolean checkRemoteSync(String selectedName, String version) {
659 List<NexusArtifact> artifacts = getArtifactFromNexus(selectedName, version);
660 return artifacts.isEmpty() ? false : true;
663 private List<NexusArtifact> getArtifactFromNexus(String selectedName, String version) {
664 final NexusClient client = new NexusRestClient();
666 boolean flag = false;
667 while (i < repURLs.size()) {
669 String repURL = repURLs.get(0);
670 client.connect(repURL.substring(0, repURL.indexOf(repURL.split(":[0-9]+\\/nexus")[1])), repUserName,
672 final NexusArtifact template = new NexusArtifact();
673 template.setGroupId(getGroupID(selectedName));
674 template.setArtifactId(getArtifactID(selectedName));
675 if (version != null) {
676 template.setVersion(version);
678 List<NexusArtifact> resultList = client.searchByGAV(template);
679 if (resultList != null) {
683 } catch (NexusClientException | NexusConnectionException | NullPointerException e) {
684 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Connection to remote Nexus has failed. "
685 + e.getMessage(), e);
689 } catch (NexusClientException | NexusConnectionException e) {
690 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "failed to disconnect Connection from Nexus."
691 + e.getMessage(), e);
694 Collections.rotate(repURLs, -1);
699 return new ArrayList<>();
702 private void setVersion(String selectedName) {
703 String newVersion = VERSION_0_1_0;
705 NexusArtifact artifact = getLatestArtifactFromNexus(selectedName);
706 if (artifact != null) {
707 newVersion = incrementVersion(artifact.getVersion());
709 if (VERSION_0_1_0.equals(newVersion)) {
712 setVersion(newVersion, selectedName);
713 LOGGER.info("Controller: " + selectedName + "is on version: " + newVersion);
716 private String incrementVersion(String version) {
717 int majorVal = Integer.parseInt(version.substring(0, version.indexOf(".")));
718 int minorVal = Integer.parseInt(version.substring(version.indexOf(".") + 1, version.lastIndexOf(".")));
725 return majorVal + "." + minorVal + version.substring(version.lastIndexOf("."));
728 private boolean checkProject(String selectedName) {
729 return new File(PROJECTSLOCATION + File.separator + getDirectoryName(selectedName)).exists();
732 private String getDirectoryName(String selectedName) {
733 return getArtifactID(selectedName);
737 * Will Push policies to the PolicyRepo.
739 * @param notificationType
740 * <String> type of notification Type.
741 * @throws PolicyException
743 public void pushRules() throws PolicyException {
744 // Check how many groups have been updated.
745 // Invoke their Maven process.
747 im.startTransaction();
748 } catch (Exception e) {
749 LOGGER.error("Error while starting Transaction " + e);
751 if (!modifiedGroups.isEmpty()) {
752 Boolean flag = false;
753 for (Map.Entry<String, String> entry : modifiedGroups.entrySet()) {
754 InvocationResult result = null;
755 String group = entry.getKey();
757 LOGGER.info("PushRules: ModifiedGroups, Key: " + group + ", Value: " + entry.getValue());
758 InvocationRequest request = new DefaultInvocationRequest();
761 request.setPomFile(new File(
762 PROJECTSLOCATION + File.separator + getArtifactID(group) + File.separator + POM_XML_FILE));
763 request.setGoals(Arrays.asList(GOALS));
764 Invoker invoker = new DefaultInvoker();
765 result = invoker.execute(request);
766 if (result.getExecutionException() != null) {
767 LOGGER.error(result.getExecutionException());
768 } else if (result.getExitCode() != 0) {
769 LOGGER.error("Maven Invocation failure..!");
771 } catch (Exception e) {
772 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation issue for "
773 + getArtifactID(group) + e.getMessage(), e);
775 if (result != null && result.getExitCode() == 0) {
776 LOGGER.info("Build Completed..!");
778 addNotification(group, "create");
780 addNotification(group, entry.getValue());
784 throw new PolicyException(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation failure!");
788 sendNotification(controllers);
797 * Removes a Rule from Rule Projects.
799 public void removeRule(String name) {
800 String controllerName = getGroupName(name);
801 if (controllerName == null) {
802 LOGGER.info("Error finding the controllerName for the given Policy: " + name);
805 syncProject(controllerName);
806 getNameAndSetRemove(controllerName, name);
809 private String getGroupName(String name) {
810 if (policyMap.containsKey(name)) {
811 return policyMap.get(name);
814 return policyMap.containsKey(name) ? policyMap.get(name) : null;
818 private void addModifiedGroup(String controllerName, String operation) {
819 if (controllerName != null) {
820 modifiedGroups.put(controllerName, operation);
824 private void addNotification(String controllerName, String operation) {
825 ControllerPOJO controllerPOJO = new ControllerPOJO();
826 controllerPOJO.setName(controllerName);
827 controllerPOJO.setOperation(operation);
828 HashMap<String, String> drools = new HashMap<>();
829 drools.put("groupId", getGroupID(controllerName));
830 drools.put("artifactId", getArtifactID(controllerName));
831 drools.put("version", getVersion(controllerName));
832 controllerPOJO.setDrools(drools);
833 controllers.add(controllerPOJO);
835 LOGGER.debug("Notification added: " + PolicyUtils.objectToJsonString(controllerPOJO));
836 } catch (JsonProcessingException e) {
837 LOGGER.error(MessageCodes.ERROR_SCHEMA_INVALID + "Json Processing Error " + e);
841 private void removedRuleModifiedGroup(String controllerName) {
842 // This will be sending Notification to PDPD directly to Lock
843 ControllerPOJO controllerPOJO = new ControllerPOJO();
844 controllerPOJO.setName(controllerName);
845 controllerPOJO.setOperation("lock");
846 List<ControllerPOJO> controllerPojos = new ArrayList<>();
847 controllerPojos.add(controllerPOJO);
848 sendNotification(controllerPojos);
851 private void sendNotification(List<ControllerPOJO> controllers) {
852 NotificationPOJO notification = new NotificationPOJO();
853 String requestId = UUID.randomUUID().toString();
854 LOGGER.info("Generating notification RequestID : " + requestId);
855 notification.setRequestID(requestId);
856 notification.setEntity("controller");
857 notification.setControllers(controllers);
859 String notificationJson = PolicyUtils.objectToJsonString(notification);
860 LOGGER.info("Sending Notification :\n" + notificationJson);
861 sendMessage(notificationJson);
862 } catch (Exception e) {
863 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while sending notification to PDP-D "
864 + e.getMessage(), e);
868 private void sendMessage(String message) throws IOException, GeneralSecurityException, InterruptedException {
870 if ("dmaap".equalsIgnoreCase(notificationType)) {
871 // Sending Message through DMaaP Message Router
872 LOGGER.debug("DMAAP Publishing Message");
874 publisher.send("MyPartitionKey", message);
876 LOGGER.debug("Message Published on DMaaP :" + dmaapList.get(0) + "for Topic: " + pubTopic);
878 Thread.sleep(dmaapDelay);
881 // Sending Message through UEB interface.
882 LOGGER.debug("UEB Publishing Message");
884 CambriaBatchingPublisher pub = pubBuilder.build();
885 pub.send("MyPartitionKey", message);
887 final List<?> stuck = pub.close(uebDelay, TimeUnit.SECONDS);
888 if (!stuck.isEmpty()) {
889 LOGGER.error(stuck.size() + " messages unsent");
891 LOGGER.debug("Clean exit; Message Published on UEB : " + uebList + "for Topic: " + pubTopic);
897 private void createPom(String name) {
898 Model model = new Model();
899 model.setModelVersion("4.0.0");
900 model.setGroupId(getGroupID(name));
901 model.setArtifactId(getArtifactID(name));
902 model.setVersion(getVersion(name));
904 DistributionManagement distributionManagement = new DistributionManagement();
905 DeploymentRepository repository = new DeploymentRepository();
906 repository.setId(repID);
907 repository.setName(repName);
908 repository.setUrl(repURLs.get(0));
909 distributionManagement.setRepository(repository);
910 model.setDistributionManagement(distributionManagement);
911 // Dependency Management goes here.
912 List<Dependency> dependencyList = new ArrayList<>();
913 if (groupMap.get(name).size() > 1) {
914 @SuppressWarnings("unchecked")
915 ArrayList<PEDependency> dependencies = (ArrayList<PEDependency>) groupMap.get(name).get(1);
916 for (PEDependency dependency : dependencies) {
917 dependencyList.add(dependency.getDependency());
920 // Add Default dependencies.
921 dependencyList = getDependencies(name);
923 model.setDependencies(dependencyList);
924 Writer writer = null;
926 writer = WriterFactory.newXmlWriter(
927 new File(PROJECTSLOCATION + File.separator + getArtifactID(name) + File.separator + POM_XML_FILE));
928 MavenXpp3Writer pomWriter = new MavenXpp3Writer();
929 pomWriter.write(writer, model);
930 } catch (Exception e) {
931 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while creating POM for " + getArtifactID(name)
932 + e.getMessage(), e);
934 IOUtil.close(writer);
938 private List<Dependency> getDependencies(String controllerName) {
939 // Read the Dependency Information from property file.
940 Path file = Paths.get(DEPENDENCY_FILE);
941 if (!Files.notExists(file)) {
943 String dependencyJSON = new String(Files.readAllBytes(file), StandardCharsets.UTF_8);
944 DependencyInfo dependencyInfo = PolicyUtils.jsonStringToObject(dependencyJSON, DependencyInfo.class);
945 String controller = "default";
946 if (dependencyInfo.getDependencies().containsKey(controllerName)) {
947 controller = controllerName;
949 List<Dependency> dependencyList = new ArrayList<>();
950 for (PEDependency dependency : dependencyInfo.getDependencies().get(controller)) {
951 dependencyList.add(dependency.getDependency());
953 return dependencyList;
954 } catch (IOException | NullPointerException e) {
955 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
956 + "Error while getting dependecy Information for controller: " + controllerName
957 + e.getMessage(), e);
960 return defaultDependencies(controllerName);
963 // Default Dependency Section. Can be changed as required.
964 public List<Dependency> defaultDependencies(String controllerName) {
966 List<Dependency> dependencyList = new ArrayList<>();
967 String version = StringEscapeUtils.escapeJava(brmsdependencyversion);
969 Dependency demoDependency = new Dependency();
970 demoDependency.setGroupId(DROOLS_APPS_TEMPLATE_GROUP);
971 demoDependency.setArtifactId("template.demo");
972 demoDependency.setVersion(version);
973 dependencyList.add(demoDependency);
975 Dependency controlloopDependency = new Dependency();
976 controlloopDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
977 controlloopDependency.setArtifactId("events");
978 controlloopDependency.setVersion(version);
979 dependencyList.add(controlloopDependency);
981 Dependency restDependency = new Dependency();
982 restDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
983 restDependency.setArtifactId("controlloop.common.model-impl.rest");
984 restDependency.setVersion(version);
985 dependencyList.add(restDependency);
987 Dependency appcDependency = new Dependency();
988 appcDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
989 appcDependency.setArtifactId("controlloop.common.model-impl.appc");
990 appcDependency.setVersion(version);
991 dependencyList.add(appcDependency);
993 Dependency aaiDependency = new Dependency();
994 aaiDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
995 aaiDependency.setArtifactId("controlloop.common.model-impl.aai");
996 aaiDependency.setVersion(version);
997 dependencyList.add(aaiDependency);
999 Dependency msoDependency = new Dependency();
1000 msoDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1001 msoDependency.setArtifactId("controlloop.common.model-impl.so");
1002 msoDependency.setVersion(version);
1003 dependencyList.add(msoDependency);
1005 Dependency trafficgeneratorDependency = new Dependency();
1006 trafficgeneratorDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1007 trafficgeneratorDependency.setArtifactId("controlloop.common.model-impl.trafficgenerator");
1008 trafficgeneratorDependency.setVersion(version);
1009 dependencyList.add(trafficgeneratorDependency);
1010 return dependencyList;
1013 private void createProject(String path, String ksessionName) {
1014 new File(path + File.separator + RULES).mkdirs();
1015 new File(path + File.separator + META_INF).mkdirs();
1016 if (!Files.exists(Paths.get(path + File.separator + META_INF + File.separator + KMODULE_XML_FILE))) {
1017 // Hard coding XML for PDP Drools to accept our Rules.
1018 String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "\n"
1019 + "<kmodule xmlns=\"http://jboss.org/kie/6.0.0/kmodule\">" + "\n"
1020 + "<kbase name=\"rules\" packages=\"rules\">" + "\n" + "<ksession name=\"" + ksessionName + "\"/>"
1021 + "\n" + "</kbase></kmodule>";
1022 copyDataToFile(path + File.separator + META_INF + File.separator + KMODULE_XML_FILE, xml);
1026 private void copyDataToFile(String file, String rule) {
1028 FileUtils.writeStringToFile(new File(file), rule);
1029 } catch (Exception e) {
1031 XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while creating Rule for " + file + e.getMessage(),
1036 private void readGroups(Properties config) throws PolicyException {
1037 String[] groupNames;
1038 String groupNamesError = "groupNames property is missing or empty from the property file ";
1039 if (!config.containsKey(GROUP_NAMES) || config.getProperty(GROUP_NAMES)==null){
1040 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
1043 if (config.getProperty(GROUP_NAMES).contains(",")) {
1044 groupNames = config.getProperty(GROUP_NAMES).replaceAll(" ", "").split(",");
1046 groupNames = new String[] { config.getProperty(GROUP_NAMES).replaceAll(" ", "") };
1048 if (groupNames == null || groupNames.length == 0) {
1049 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
1051 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
1054 groupMap = new HashMap<>();
1055 for (int counter = 0; counter < groupNames.length; counter++) {
1056 String name = groupNames[counter];
1057 String groupID = config.getProperty(name + ".groupID");
1058 if (groupID == null) {
1059 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1060 + ".groupID property is missing from the property file ");
1061 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1062 + ".groupID property is missing from the property file ");
1064 String artifactID = config.getProperty(name + ".artifactID");
1065 if (artifactID == null) {
1066 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1067 + ".artifactID property is missing from the property file ");
1068 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1069 + ".artifactID property is missing from the property file ");
1071 PEDependency dependency = new PEDependency();
1072 dependency.setArtifactId(artifactID);
1073 dependency.setGroupId(groupID);
1074 // Add to list if we got all
1075 addToGroup(name, dependency);
1079 private void addToGroup(String name, PEDependency dependency) {
1080 ArrayList<Object> values = new ArrayList<>();
1081 values.add(dependency);
1082 groupMap.put(name, values);
1083 EntityTransaction et = em.getTransaction();
1085 Query query = em.createQuery("select b from BRMSGroupInfo as b where b.controllerName = :cn");
1086 query.setParameter("cn", name);
1087 List<?> groupList = query.getResultList();
1088 BRMSGroupInfo brmsGroupInfo = null;
1089 if (!groupList.isEmpty()) {
1090 LOGGER.info("Controller name already Existing in DB. Will be updating the DB Values" + name);
1091 brmsGroupInfo = (BRMSGroupInfo) groupList.get(0);
1093 if (brmsGroupInfo == null) {
1094 brmsGroupInfo = new BRMSGroupInfo();
1096 brmsGroupInfo.setControllerName(name);
1097 brmsGroupInfo.setGroupId(dependency.getGroupId());
1098 brmsGroupInfo.setArtifactId(dependency.getArtifactId());
1099 brmsGroupInfo.setVersion(dependency.getVersion());
1100 em.persist(brmsGroupInfo);
1105 private String getArtifactID(String name) {
1106 return ((PEDependency) groupMap.get(name).get(0)).getArtifactId();
1109 private String getGroupID(String name) {
1110 return ((PEDependency) groupMap.get(name).get(0)).getGroupId();
1113 private String getVersion(String name) {
1114 return ((PEDependency) groupMap.get(name).get(0)).getVersion();
1117 private void getNameAndSetRemove(String controllerName, String policyName) {
1118 String artifactName = getArtifactID(controllerName);
1119 String ruleFolder = PROJECTSLOCATION + File.separator + artifactName + File.separator + "src" + File.separator
1120 + "main" + File.separator + RESOURCES + File.separator + RULES;
1121 File file = new File(ruleFolder + File.separator + policyName + ".drl");
1122 if (file.delete()) {
1123 LOGGER.info("Deleted File.. " + file.getAbsolutePath());
1124 removePolicyFromGroup(policyName, controllerName);
1126 if (new File(ruleFolder).listFiles().length == 0) {
1127 removedRuleModifiedGroup(controllerName);
1129 // This is an update in terms of PDPD.
1130 addModifiedGroup(controllerName, "update");
1134 // Removes Policy from Memory and Database.
1135 private void removePolicyFromGroup(String policyName, String controllerName) {
1136 policyMap.remove(policyName);
1137 EntityTransaction et = em.getTransaction();
1139 Query query = em.createQuery("select b from BRMSPolicyInfo as b where b.policyName = :pn");
1140 query.setParameter("pn", policyName);
1141 List<?> pList = query.getResultList();
1142 BRMSPolicyInfo brmsPolicyInfo;
1143 if (!pList.isEmpty()) {
1145 brmsPolicyInfo = (BRMSPolicyInfo) pList.get(0);
1146 if (brmsPolicyInfo.getControllerName().getControllerName().equals(controllerName)) {
1147 em.remove(brmsPolicyInfo);
1154 private void setVersion(String newVersion, String controllerName) {
1155 PEDependency userController = (PEDependency) groupMap.get(controllerName).get(0);
1156 userController.setVersion(newVersion);
1157 groupMap.get(controllerName).set(0, userController);
1160 // Return BackUpMonitor
1161 public static BackUpMonitor getBackUpMonitor() {
1165 public void rotateURLs() {
1166 if (repURLs != null) {
1167 Collections.rotate(repURLs, -1);
1171 public int urlListSize() {
1172 if (repURLs != null) {
1173 return repURLs.size();