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.brms.api;
23 import com.att.nsa.cambria.client.CambriaBatchingPublisher;
24 import com.att.nsa.cambria.client.CambriaClientBuilders;
25 import com.att.nsa.cambria.client.CambriaClientBuilders.PublisherBuilder;
26 import com.fasterxml.jackson.core.JsonProcessingException;
29 import java.io.FileInputStream;
30 import java.io.FileOutputStream;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.io.Writer;
35 import java.nio.channels.Channels;
36 import java.nio.channels.ReadableByteChannel;
37 import java.nio.charset.StandardCharsets;
38 import java.nio.file.Files;
39 import java.nio.file.Path;
40 import java.nio.file.Paths;
41 import java.security.GeneralSecurityException;
42 import java.util.ArrayList;
43 import java.util.Arrays;
44 import java.util.Collections;
45 import java.util.Enumeration;
46 import java.util.HashMap;
47 import java.util.List;
49 import java.util.Properties;
50 import java.util.UUID;
51 import java.util.concurrent.TimeUnit;
52 import java.util.jar.JarEntry;
53 import java.util.jar.JarFile;
54 import java.util.regex.Pattern;
56 import javax.persistence.EntityManager;
57 import javax.persistence.EntityManagerFactory;
58 import javax.persistence.EntityTransaction;
59 import javax.persistence.Persistence;
60 import javax.persistence.Query;
62 import org.apache.commons.io.FileUtils;
63 import org.apache.commons.lang.StringEscapeUtils;
64 import org.apache.maven.model.Dependency;
65 import org.apache.maven.model.DeploymentRepository;
66 import org.apache.maven.model.DistributionManagement;
67 import org.apache.maven.model.Model;
68 import org.apache.maven.model.io.xpp3.MavenXpp3Writer;
69 import org.apache.maven.shared.invoker.DefaultInvocationRequest;
70 import org.apache.maven.shared.invoker.DefaultInvoker;
71 import org.apache.maven.shared.invoker.InvocationRequest;
72 import org.apache.maven.shared.invoker.InvocationResult;
73 import org.apache.maven.shared.invoker.Invoker;
74 import org.codehaus.plexus.util.IOUtil;
75 import org.codehaus.plexus.util.WriterFactory;
76 import org.eclipse.persistence.config.PersistenceUnitProperties;
77 import org.onap.policy.api.PEDependency;
78 import org.onap.policy.api.PolicyException;
79 import org.onap.policy.brms.entity.BrmsGroupInfo;
80 import org.onap.policy.brms.entity.BrmsPolicyInfo;
81 import org.onap.policy.brms.entity.DependencyInfo;
82 import org.onap.policy.common.im.IntegrityMonitor;
83 import org.onap.policy.common.logging.eelf.MessageCodes;
84 import org.onap.policy.common.logging.eelf.PolicyLogger;
85 import org.onap.policy.common.logging.flexlogger.FlexLogger;
86 import org.onap.policy.common.logging.flexlogger.Logger;
87 import org.onap.policy.utils.BackUpHandler;
88 import org.onap.policy.utils.BackUpMonitor;
89 import org.onap.policy.utils.BusPublisher;
90 import org.onap.policy.utils.PolicyUtils;
91 import org.onap.policy.xacml.api.XACMLErrorConstants;
92 import org.sonatype.nexus.client.NexusClient;
93 import org.sonatype.nexus.client.NexusClientException;
94 import org.sonatype.nexus.client.NexusConnectionException;
95 import org.sonatype.nexus.client.rest.NexusRestClient;
96 import org.sonatype.nexus.rest.model.NexusArtifact;
99 * BRMSPush: Application responsible to push policies to the BRMS PDP Policy Repository (PR).
100 * Mavenize and push policy to PR
105 @SuppressWarnings("deprecation")
106 public class BrmsPush {
107 private static final String GROUP_NAMES = "groupNames";
108 private static final String DROOLS_APPS_TEMPLATE_GROUP =
109 "org.onap.policy.drools-applications.controlloop.templates";
110 private static final String DROOLS_APPS_MODEL_GROUP =
111 "org.onap.policy.drools-applications.controlloop.common.model-impl";
112 private static final String META_INF = "META-INF";
113 private static final String KMODULE_XML_FILE = "kmodule.xml";
114 private static final String POM_XML_FILE = "pom.xml";
115 private static final String VERSION_0_1_0 = "0.1.0";
116 private static final String RULES = "rules";
117 private static final String RESOURCES = "resources";
118 private static final Logger LOGGER = FlexLogger.getLogger(BrmsPush.class.getName());
119 private static final String PROJECTSLOCATION = "RuleProjects";
120 private static final String[] GOALS = {"clean", "deploy"};
121 private static final String DEFAULT_VERSION = "1.2.0-SNAPSHOT";
122 private static final String DEPENDENCY_FILE = "dependency.json";
123 private static final String BRMSPERSISTENCE = "brmsEclipselink.persistencexml";
125 private static Map<String, String> modifiedGroups = new HashMap<>();
126 private static IntegrityMonitor im;
127 private static BackUpMonitor bm;
128 private String defaultName = null;
129 private String repId = null;
130 private String repName = null;
131 private List<String> repUrlList = null;
132 private String repUserName = null;
133 private String repPassword = null;
134 private String policyKeyId = null;
135 private boolean createFlag = false;
136 private String uebList = null;
137 private List<String> dmaapList = null;
138 private String pubTopic = null;
139 private PublisherBuilder pubBuilder = null;
140 protected BusPublisher publisher = null;
141 private Long uebDelay = Long.parseLong("20");
142 private Long dmaapDelay = Long.parseLong("5000");
143 private String notificationType = null;
144 private List<ControllerPojo> controllers;
145 private Map<String, ArrayList<Object>> groupMap = new HashMap<>();
146 private final Map<String, String> policyMap = new HashMap<>();
147 private String brmsdependencyversion;
148 private EntityManager em;
149 private boolean syncFlag = false;
152 * Responsible to push policies to the BRMS PDP Policy Repository (PR).
154 * @param propertiesFile the properties file
155 * @param handler the {@link BackUpHandler}
156 * @throws PolicyException PolicyException related to the operation
158 public BrmsPush(final String propertiesFile, final BackUpHandler handler) throws PolicyException {
159 if (propertiesFile == null || handler == null) {
160 throw new PolicyException("Error no propertiesFile or handler");
162 final Properties config = new Properties();
163 final Path file = Paths.get(propertiesFile);
164 if (Files.notExists(file)) {
165 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Config File doesn't Exist in the specified Path "
167 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
168 + "Config File doesn't Exist in the specified Path " + file.toString());
170 if (file.toString().endsWith(".properties")) {
171 // Grab the Properties.
172 setProperty(file, config, handler);
177 private void setProperty(final Path file, final Properties config, final BackUpHandler handler)
178 throws PolicyException {
181 in = new FileInputStream(file.toFile());
183 } catch (final IOException e) {
185 XACMLErrorConstants.ERROR_DATA_ISSUE + "Data/File Read Error while reading from the property file.",
187 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
188 + "Data/File Read Error while reading from the property file.");
190 LOGGER.info("Trying to set up IntegrityMonitor");
191 String resourceName = null;
193 LOGGER.info("Trying to set up IntegrityMonitor");
194 resourceName = config.getProperty("RESOURCE_NAME");
195 if (resourceName == null) {
196 LOGGER.warn("RESOURCE_NAME is missing setting default value. ");
197 resourceName = "brmsgw_pdp01";
199 resourceName = resourceName.trim();
200 setIntegrityMonitor(IntegrityMonitor.getInstance(resourceName, config));
201 } catch (final Exception e) {
202 LOGGER.error("Error starting Integerity Monitor: " + e);
204 LOGGER.info("Trying to set up BackUpMonitor");
206 setBackupMonitor(BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), resourceName, config,
208 } catch (final Exception e) {
209 LOGGER.error("Error starting BackUpMonitor: " + e);
211 if (!config.containsKey(BRMSPERSISTENCE)) {
212 config.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, "META-INF/persistenceBRMS.xml");
214 config.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML,
215 config.getProperty(BRMSPERSISTENCE, "META-INF/persistenceBRMS.xml"));
217 final EntityManagerFactory emf = Persistence.createEntityManagerFactory("BRMSGW", config);
218 em = emf.createEntityManager();
219 defaultName = config.getProperty("defaultName");
220 if (defaultName == null) {
222 XACMLErrorConstants.ERROR_DATA_ISSUE + "defaultName property is missing from the property file ");
223 throw new PolicyException(
224 XACMLErrorConstants.ERROR_DATA_ISSUE + "defaultName property is missing from the property file");
226 defaultName = defaultName.trim();
227 repId = config.getProperty("repositoryID");
230 XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryID property is missing from the property file ");
231 throw new PolicyException(
232 XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryID property is missing from the property file ");
234 repId = repId.trim();
235 repName = config.getProperty("repositoryName");
236 if (repName == null) {
237 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
238 + "repositoryName property is missing from the property file ");
239 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
240 + "repositoryName property is missing from the property file ");
242 repName = repName.trim();
243 final String repUrl = config.getProperty("repositoryURL");
244 if (repUrl == null) {
246 XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryURL property is missing from the property file ");
247 throw new PolicyException(
248 XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryURL property is missing from the property file ");
250 if (repUrl.contains(",")) {
251 repUrlList = new ArrayList<>(Arrays.asList(repUrl.trim().split(",")));
253 repUrlList = new ArrayList<>();
254 repUrlList.add(repUrl);
256 repUserName = config.getProperty("repositoryUsername");
257 repPassword = config.getProperty("repositoryPassword");
258 if (repUserName == null || repPassword == null) {
259 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
260 + "repostoryUserName and respositoryPassword properties are required.");
261 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
262 + "repostoryUserName and respositoryPassword properties are required.");
264 repUserName = repUserName.trim();
265 repPassword = repPassword.trim();
266 policyKeyId = config.getProperty("policyKeyID");
267 if (policyKeyId == null) {
269 XACMLErrorConstants.ERROR_DATA_ISSUE + "policyKeyID property is missing from the property file ");
270 throw new PolicyException(
271 XACMLErrorConstants.ERROR_DATA_ISSUE + "policyKeyID property is missing from the property file ");
273 policyKeyId = policyKeyId.trim();
274 final String syncF = config.getProperty("sync", "false").trim();
275 syncFlag = Boolean.parseBoolean(syncF);
277 PolicyLogger.info("SYNC Flag is turned ON. DB will be given Priority.");
279 brmsdependencyversion = config.getProperty("brms.dependency.version");
280 if (brmsdependencyversion == null) {
281 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
282 + "brmsdependencyversion property is missing from the property file, Using default Version.");
283 brmsdependencyversion = DEFAULT_VERSION;
285 brmsdependencyversion = brmsdependencyversion.trim();
289 notificationType = config.getProperty("NOTIFICATION_TYPE");
290 if ("dmaap".equalsIgnoreCase(notificationType)) {
292 LOGGER.info("Notification Type being used is DMaaP... creating instance of BusPublisher.");
293 // Setting up the Publisher for DMaaP MR
294 String dmaapServers = config.getProperty("NOTIFICATION_SERVERS");
295 pubTopic = config.getProperty("NOTIFICATION_TOPIC");
296 final String aafLogin = config.getProperty("CLIENT_ID").trim();
297 final String aafPassword = config.getProperty("CLIENT_KEY").trim();
299 if (dmaapServers == null || pubTopic == null) {
301 XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file ");
302 throw new PolicyException(
303 XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file ");
306 dmaapServers = dmaapServers.trim();
307 pubTopic = pubTopic.trim();
309 if (dmaapServers.contains(",")) {
310 dmaapList = new ArrayList<>(Arrays.asList(dmaapServers.split("\\s*,\\s*")));
312 dmaapList = new ArrayList<>();
313 dmaapList.add(dmaapServers);
317 new BusPublisher.DmaapPublisherWrapper(this.dmaapList, this.pubTopic, aafLogin, aafPassword);
319 String notificationDelay = config.getProperty("NOTIFICATION_DELAY");
320 if (notificationDelay != null && !notificationDelay.isEmpty()) {
321 notificationDelay = notificationDelay.trim();
323 dmaapDelay = Long.parseLong(notificationDelay);
324 } catch (final NumberFormatException e) {
325 LOGGER.error("DMAAP_DELAY not a long format number" + e);
328 LOGGER.info("DMAAP BusPublisher is created.");
331 LOGGER.info("Notification Type being used is UEB... creating instance of PublisherBuilder.");
332 // Setting up the Publisher for UEB
333 uebList = config.getProperty("NOTIFICATION_SERVERS");
334 pubTopic = config.getProperty("NOTIFICATION_TOPIC");
335 if (uebList == null || pubTopic == null) {
337 XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file ");
338 throw new PolicyException(
339 XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file ");
341 uebList = uebList.trim();
342 pubTopic = pubTopic.trim();
343 pubBuilder = new CambriaClientBuilders.PublisherBuilder();
344 pubBuilder.usingHosts(uebList).onTopic(pubTopic);
345 String apiKey = config.getProperty("UEB_API_KEY");
346 String apiSecret = config.getProperty("UEB_API_SECRET");
347 if (apiKey != null && !apiKey.isEmpty() && apiSecret != null && !apiSecret.isEmpty()) {
348 apiKey = apiKey.trim();
349 apiSecret = apiSecret.trim();
350 pubBuilder.authenticatedBy(apiKey, apiSecret);
352 String notificationDelay = config.getProperty("NOTIFICATION_DELAY");
353 if (notificationDelay != null && !notificationDelay.isEmpty()) {
354 notificationDelay = notificationDelay.trim();
356 uebDelay = Long.parseLong(notificationDelay);
357 } catch (final NumberFormatException e) {
358 LOGGER.error("UEB_DELAY not a long format number" + e);
361 LOGGER.info("UEB PublisherBuilder is created.");
367 private static void setBackupMonitor(final BackUpMonitor instance) {
371 private static void setIntegrityMonitor(final IntegrityMonitor instance) {
376 * Will Initialize the variables required for BRMSPush.
378 public void initiate(final boolean flag) {
379 resetModifiedGroups();
380 controllers = new ArrayList<>();
382 bm.updateNotification();
383 } catch (final Exception e) {
384 LOGGER.error("Error while updating Notification: " + e.getMessage(), e);
391 public void resetDs() {
392 resetModifiedGroups();
393 controllers = new ArrayList<>();
396 private static void resetModifiedGroups() {
397 modifiedGroups = new HashMap<>();
401 * Will Add rules to projects. Creates necessary folders if required.
403 public void addRule(final String name, final String rule, final Map<String, String> responseAttributes) {
404 // 1 check the response Attributes and determine if this belongs to any projects.
405 // 2 if not create folder
408 // 5 store the groups that have been updated.
409 String ksessionName = null;
410 String selectedName = null;
411 if (!responseAttributes.isEmpty()) {
412 // Pick selected Value
413 String userControllerName = null;
414 final ArrayList<PEDependency> userDependencies = new ArrayList<>();
415 for (final Map.Entry<String, String> entry : responseAttributes.entrySet()) {
416 final String key = entry.getKey();
417 String value = entry.getValue();
418 if (key.equals(policyKeyId)) {
419 selectedName = value;
421 // kmodule configurations
422 else if ("kSessionName".equals(key)) {
423 ksessionName = value;
425 // Check User Specific values.
426 if ("$controller:".equals(key)) {
428 final PEDependency dependency = PolicyUtils.jsonStringToObject(value, PEDependency.class);
429 userControllerName = key.replaceFirst("$controller:", "");
430 LOGGER.info("addRule: userControllerName - " + userControllerName + ", dependency: - "
432 addToGroup(userControllerName, dependency);
433 } catch (final Exception e) {
434 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while resolving Controller: " + e);
437 } else if ("$dependency$".equals(key) && value.startsWith("[") && value.endsWith("]")) {
438 value = value.substring(1, value.length() - 1).trim();
439 final List<String> dependencyStrings = Arrays.asList(value.split(Pattern.quote("},{")));
440 for (final String dependencyString : dependencyStrings) {
442 userDependencies.add(PolicyUtils.jsonStringToObject(dependencyString, PEDependency.class));
443 } catch (final Exception e) {
444 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while resolving Dependencies: "
450 if (userControllerName != null) {
451 // Adding custom dependencies here.
452 final ArrayList<Object> values = groupMap.get(userControllerName);
453 values.add(userDependencies);
454 groupMap.put(userControllerName, values);
455 selectedName = userControllerName;
458 // If no Match then pick Default.
459 if (selectedName == null) {
460 selectedName = defaultName;
462 if (groupMap.containsKey(selectedName)) {
463 // If the key is not got as parameters set by the user, setting the default value for
466 if (ksessionName == null) {
467 LOGGER.info("kSessionName is null, selectedName is : " + selectedName);
468 if (selectedName.equalsIgnoreCase(defaultName)) {
469 ksessionName = "closedloop";
471 ksessionName = "closedloop-" + selectedName;
474 // create directories if missing.
475 manageProject(selectedName, ksessionName, name, rule);
477 // Will check for Create Later after generating the Pom.
478 addModifiedGroup(selectedName, "update");
482 private void syncGroupInfo() {
483 // Sync DB to JMemory.
484 final EntityTransaction et = em.getTransaction();
486 Query query = em.createQuery("select b from BrmsGroupInfo AS b");
487 List<?> result = query.getResultList();
488 if (result.size() != groupMap.size()) {
489 for (final Object value : result) {
490 final BrmsGroupInfo brmsGroupInfo = (BrmsGroupInfo) value;
491 final PEDependency dependency = new PEDependency();
492 dependency.setArtifactId(brmsGroupInfo.getArtifactId());
493 dependency.setGroupId(brmsGroupInfo.getGroupId());
494 dependency.setVersion(brmsGroupInfo.getVersion());
495 final ArrayList<Object> values = new ArrayList<>();
496 values.add(dependency);
497 groupMap.put(brmsGroupInfo.getControllerName(), values);
500 query = em.createQuery("select g from BrmsPolicyInfo AS g");
501 result = query.getResultList();
502 if (result.size() != policyMap.size()) {
503 for (final Object value : result) {
504 final BrmsPolicyInfo brmsPolicyInfo = (BrmsPolicyInfo) value;
505 policyMap.put(brmsPolicyInfo.getPolicyName(), brmsPolicyInfo.getControllerName().getControllerName());
509 LOGGER.info("Updated Local Memory values with values from database.");
512 private void manageProject(final String selectedName, final String ksessionName, final String name,
514 // Check if the Project is in Sync. If not get the latest Version.
515 syncProject(selectedName);
516 createProject(PROJECTSLOCATION + File.separator + getArtifactId(selectedName) + File.separator + "src"
517 + File.separator + "main" + File.separator + RESOURCES, ksessionName);
518 copyDataToFile(PROJECTSLOCATION + File.separator + getArtifactId(selectedName) + File.separator + "src"
519 + File.separator + "main" + File.separator + RESOURCES + File.separator + RULES + File.separator + name
521 addToPolicy(name, selectedName);
525 * Add Policy to JMemory and DataBase.
527 private void addToPolicy(final String policyName, final String controllerName) {
528 policyMap.put(policyName, controllerName);
529 final EntityTransaction et = em.getTransaction();
531 Query query = em.createQuery("select b from BrmsPolicyInfo as b where b.policyName = :pn");
532 query.setParameter("pn", policyName);
533 final List<?> pList = query.getResultList();
534 boolean create = false;
535 BrmsPolicyInfo brmsPolicyInfo = new BrmsPolicyInfo();
536 if (!pList.isEmpty()) {
538 brmsPolicyInfo = (BrmsPolicyInfo) pList.get(0);
539 if (!brmsPolicyInfo.getControllerName().getControllerName().equals(controllerName)) {
546 query = em.createQuery("select b from BrmsGroupInfo as b where b.controllerName = :cn");
547 query.setParameter("cn", controllerName);
548 final List<?> bList = query.getResultList();
549 BrmsGroupInfo brmsGroupInfo = new BrmsGroupInfo();
550 if (!bList.isEmpty()) {
551 brmsGroupInfo = (BrmsGroupInfo) bList.get(0);
553 brmsPolicyInfo.setPolicyName(policyName);
554 brmsPolicyInfo.setControllerName(brmsGroupInfo);
555 em.persist(brmsPolicyInfo);
561 private void syncProject(final String selectedName) {
562 final boolean projectExists = checkProject(selectedName);
565 version = getVersion(selectedName);
566 if (version == null) {
567 LOGGER.error("Error getting local version for the given Controller Name:" + selectedName
568 + " going with Default value");
569 version = VERSION_0_1_0;
571 final String nextVersion = incrementVersion(version);
572 final boolean outOfSync = checkRemoteSync(selectedName, nextVersion);
577 // We are out of Sync or Project is not Present.
578 downloadProject(selectedName);
581 private void downloadProject(final String selectedName) {
582 final NexusArtifact artifact = getLatestArtifactFromNexus(selectedName);
583 if (artifact == null) {
586 final String dirName = getDirectoryName(selectedName);
588 final String fileName = "rule.jar";
590 website = new URL(artifact.getResourceURI());
591 try (ReadableByteChannel rbc = Channels.newChannel(website.openStream());
592 FileOutputStream fos = new FileOutputStream(fileName)) {
593 fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
594 extractJar(fileName, dirName);
595 new File(fileName).delete();
596 } catch (final IOException e) {
597 LOGGER.error("Error while downloading the project to File System. " + e.getMessage(), e);
600 } catch (final IOException e1) {
601 LOGGER.error("Error while retrieve the artifact. " + e1.getMessage(), e1);
605 private void extractJar(final String jarFileName, final String artifactId) {
606 try (JarFile jar = new JarFile(jarFileName)) {
607 final Enumeration<?> enumEntries = jar.entries();
608 while (enumEntries.hasMoreElements()) {
609 final JarEntry jarEntry = (JarEntry) enumEntries.nextElement();
611 final String fileName = jarEntry.getName().substring(jarEntry.getName().lastIndexOf("/") + 1);
612 if (jarEntry.getName().endsWith(".drl")) {
613 final String path = PROJECTSLOCATION + File.separator + artifactId + File.separator + "src"
614 + File.separator + "main" + File.separator + RESOURCES + File.separator + RULES;
615 new File(path).mkdirs();
616 if (syncFlag && policyMap.containsKey(fileName.replace(".drl", ""))) {
617 file = new File(path + File.separator + fileName);
619 file = new File(path + File.separator + fileName);
621 } else if (jarEntry.getName().endsWith(POM_XML_FILE)) {
622 final String path = PROJECTSLOCATION + File.separator + artifactId;
623 new File(path).mkdirs();
624 file = new File(path + File.separator + fileName);
625 } else if (jarEntry.getName().endsWith(KMODULE_XML_FILE)) {
626 final String path = PROJECTSLOCATION + File.separator + artifactId + File.separator + "src"
627 + File.separator + "main" + File.separator + RESOURCES + File.separator + META_INF;
628 new File(path).mkdirs();
629 file = new File(path + File.separator + fileName);
632 try (InputStream is = jar.getInputStream(jarEntry);
633 FileOutputStream fos = new FileOutputStream(file)) {
634 while (is.available() > 0) {
635 fos.write(is.read());
637 LOGGER.info(fileName + " Created..");
638 } catch (final IOException e) {
639 LOGGER.info("exception Occured" + e);
643 } catch (final IOException e) {
644 LOGGER.info("exception Occured" + e);
648 private NexusArtifact getLatestArtifactFromNexus(final String selectedName) {
649 final List<NexusArtifact> artifacts = getArtifactFromNexus(selectedName, null);
652 NexusArtifact result = null;
653 for (final NexusArtifact artifact : artifacts) {
655 Integer.parseInt(artifact.getVersion().substring(0, artifact.getVersion().indexOf(".")));
656 final int minorVal = Integer.parseInt(artifact.getVersion()
657 .substring(artifact.getVersion().indexOf(".") + 1, artifact.getVersion().lastIndexOf(".")));
658 if (majorVal > bigNum) {
662 if ((bigNum == majorVal) && (minorVal > smallNum)) {
665 if (bigNum == majorVal && minorVal == smallNum) {
669 return additionalNexusLatestCheck(selectedName, result);
672 // Additional Check due to Limitations from Nexus API to check if the artifact is the latest.
673 private NexusArtifact additionalNexusLatestCheck(final String selectedName, final NexusArtifact result) {
674 if (result == null) {
677 final String nextVersion = incrementVersion(result.getVersion());
678 final List<NexusArtifact> artifact = getArtifactFromNexus(selectedName, nextVersion);
679 return artifact.isEmpty() ? result : additionalNexusLatestCheck(selectedName, artifact.get(0));
682 private boolean checkRemoteSync(final String selectedName, final String version) {
683 final List<NexusArtifact> artifacts = getArtifactFromNexus(selectedName, version);
684 return artifacts.isEmpty() ? false : true;
687 private List<NexusArtifact> getArtifactFromNexus(final String selectedName, final String version) {
688 final NexusClient client = new NexusRestClient();
690 boolean flag = false;
691 while (index < repUrlList.size()) {
693 final String repUrl = repUrlList.get(0);
694 client.connect(repUrl.substring(0, repUrl.indexOf(repUrl.split(":[0-9]+\\/nexus")[1])), repUserName,
696 final NexusArtifact template = new NexusArtifact();
697 template.setGroupId(getGroupId(selectedName));
698 template.setArtifactId(getArtifactId(selectedName));
699 if (version != null) {
700 template.setVersion(version);
702 final List<NexusArtifact> resultList = client.searchByGAV(template);
703 if (resultList != null) {
707 } catch (NexusClientException | NexusConnectionException | NullPointerException e) {
708 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Connection to remote Nexus has failed. "
709 + e.getMessage(), e);
713 } catch (NexusClientException | NexusConnectionException e) {
714 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "failed to disconnect Connection from Nexus."
715 + e.getMessage(), e);
718 Collections.rotate(repUrlList, -1);
723 return new ArrayList<>();
726 private String incrementVersion(final String version) {
727 int majorVal = Integer.parseInt(version.substring(0, version.indexOf(".")));
728 int minorVal = Integer.parseInt(version.substring(version.indexOf(".") + 1, version.lastIndexOf(".")));
735 return majorVal + "." + minorVal + version.substring(version.lastIndexOf("."));
738 private boolean checkProject(final String selectedName) {
739 return new File(PROJECTSLOCATION + File.separator + getDirectoryName(selectedName)).exists();
742 private String getDirectoryName(final String selectedName) {
743 return getArtifactId(selectedName);
747 * Will Push policies to the PolicyRepo.
749 * @throws PolicyException PolicyException related to the operation
751 public void pushRules() throws PolicyException {
752 // Check how many groups have been updated.
753 // Invoke their Maven process.
755 im.startTransaction();
756 } catch (final Exception e) {
757 LOGGER.error("Error while starting Transaction " + e);
759 if (!modifiedGroups.isEmpty()) {
760 Boolean flag = false;
761 for (final Map.Entry<String, String> entry : modifiedGroups.entrySet()) {
762 InvocationResult result = null;
763 final String group = entry.getKey();
765 LOGGER.info("PushRules: ModifiedGroups, Key: " + group + ", Value: " + entry.getValue());
766 final InvocationRequest request = new DefaultInvocationRequest();
769 request.setPomFile(new File(
770 PROJECTSLOCATION + File.separator + getArtifactId(group) + File.separator + POM_XML_FILE));
771 request.setGoals(Arrays.asList(GOALS));
772 final Invoker invoker = new DefaultInvoker();
773 result = invoker.execute(request);
774 if (result.getExecutionException() != null) {
775 LOGGER.error(result.getExecutionException());
776 } else if (result.getExitCode() != 0) {
777 LOGGER.error("Maven Invocation failure..!");
779 } catch (final Exception e) {
780 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation issue for "
781 + getArtifactId(group) + e.getMessage(), e);
783 if (result != null && result.getExitCode() == 0) {
784 LOGGER.info("Build Completed..!");
786 addNotification(group, "create");
788 addNotification(group, entry.getValue());
792 throw new PolicyException(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation failure!");
796 sendNotification(controllers);
805 * Removes a Rule from Rule Projects.
807 public void removeRule(final String name) {
808 final String controllerName = getGroupName(name);
809 if (controllerName == null) {
810 LOGGER.info("Error finding the controllerName for the given Policy: " + name);
813 syncProject(controllerName);
814 getNameAndSetRemove(controllerName, name);
817 private String getGroupName(final String name) {
818 if (policyMap.containsKey(name)) {
819 return policyMap.get(name);
822 return policyMap.containsKey(name) ? policyMap.get(name) : null;
826 private void addModifiedGroup(final String controllerName, final String operation) {
827 if (controllerName != null) {
828 modifiedGroups.put(controllerName, operation);
832 private void addNotification(final String controllerName, final String operation) {
833 final ControllerPojo controllerPojo = new ControllerPojo();
834 controllerPojo.setName(controllerName);
835 controllerPojo.setOperation(operation);
836 final HashMap<String, String> drools = new HashMap<>();
837 drools.put("groupId", getGroupId(controllerName));
838 drools.put("artifactId", getArtifactId(controllerName));
839 drools.put("version", getVersion(controllerName));
840 controllerPojo.setDrools(drools);
841 controllers.add(controllerPojo);
843 LOGGER.debug("Notification added: " + PolicyUtils.objectToJsonString(controllerPojo));
844 } catch (final JsonProcessingException e) {
845 LOGGER.error(MessageCodes.ERROR_SCHEMA_INVALID + "Json Processing Error " + e);
849 private void removedRuleModifiedGroup(final String controllerName) {
850 // This will be sending Notification to PDPD directly to Lock
851 final ControllerPojo controllerPojo = new ControllerPojo();
852 controllerPojo.setName(controllerName);
853 controllerPojo.setOperation("lock");
854 final List<ControllerPojo> controllerPojos = new ArrayList<>();
855 controllerPojos.add(controllerPojo);
856 sendNotification(controllerPojos);
859 private void sendNotification(final List<ControllerPojo> controllers) {
860 final NotificationPojo notification = new NotificationPojo();
861 final String requestId = UUID.randomUUID().toString();
862 LOGGER.info("Generating notification RequestID : " + requestId);
863 notification.setRequestId(requestId);
864 notification.setEntity("controller");
865 notification.setControllers(controllers);
867 final String notificationJson = PolicyUtils.objectToJsonString(notification);
868 LOGGER.info("Sending Notification :\n" + notificationJson);
869 sendMessage(notificationJson);
870 } catch (final Exception e) {
871 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while sending notification to PDP-D "
872 + e.getMessage(), e);
876 private void sendMessage(final String message) throws IOException, GeneralSecurityException, InterruptedException {
878 if ("dmaap".equalsIgnoreCase(notificationType)) {
879 // Sending Message through DMaaP Message Router
880 LOGGER.debug("DMAAP Publishing Message");
882 publisher.send("MyPartitionKey", message);
884 LOGGER.debug("Message Published on DMaaP :" + dmaapList.get(0) + "for Topic: " + pubTopic);
886 Thread.sleep(dmaapDelay);
889 // Sending Message through UEB interface.
890 LOGGER.debug("UEB Publishing Message");
892 final CambriaBatchingPublisher pub = pubBuilder.build();
893 pub.send("MyPartitionKey", message);
895 final List<?> stuck = pub.close(uebDelay, TimeUnit.SECONDS);
896 if (!stuck.isEmpty()) {
897 LOGGER.error(stuck.size() + " messages unsent");
899 LOGGER.debug("Clean exit; Message Published on UEB : " + uebList + "for Topic: " + pubTopic);
905 private void createPom(final String name) {
906 final Model model = new Model();
907 model.setModelVersion("4.0.0");
908 model.setGroupId(getGroupId(name));
909 model.setArtifactId(getArtifactId(name));
910 model.setVersion(getVersion(name));
912 final DistributionManagement distributionManagement = new DistributionManagement();
913 final DeploymentRepository repository = new DeploymentRepository();
914 repository.setId(repId);
915 repository.setName(repName);
916 repository.setUrl(repUrlList.get(0));
917 distributionManagement.setRepository(repository);
918 model.setDistributionManagement(distributionManagement);
919 // Dependency Management goes here.
920 List<Dependency> dependencyList = new ArrayList<>();
921 if (groupMap.get(name).size() > 1) {
922 @SuppressWarnings("unchecked")
923 final ArrayList<PEDependency> dependencies = (ArrayList<PEDependency>) groupMap.get(name).get(1);
924 for (final PEDependency dependency : dependencies) {
925 dependencyList.add(dependency.getDependency());
928 // Add Default dependencies.
929 dependencyList = getDependencies(name);
931 model.setDependencies(dependencyList);
932 Writer writer = null;
934 writer = WriterFactory.newXmlWriter(
935 new File(PROJECTSLOCATION + File.separator + getArtifactId(name) + File.separator + POM_XML_FILE));
936 final MavenXpp3Writer pomWriter = new MavenXpp3Writer();
937 pomWriter.write(writer, model);
938 } catch (final Exception e) {
939 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while creating POM for " + getArtifactId(name)
940 + e.getMessage(), e);
942 IOUtil.close(writer);
946 private List<Dependency> getDependencies(final String controllerName) {
947 // Read the Dependency Information from property file.
948 final Path file = Paths.get(DEPENDENCY_FILE);
949 if (!Files.notExists(file)) {
951 final String dependencyJson = new String(Files.readAllBytes(file), StandardCharsets.UTF_8);
952 final DependencyInfo dependencyInfo =
953 PolicyUtils.jsonStringToObject(dependencyJson, DependencyInfo.class);
954 String controller = "default";
955 if (dependencyInfo.getDependencies().containsKey(controllerName)) {
956 controller = controllerName;
958 final List<Dependency> dependencyList = new ArrayList<>();
959 for (final PEDependency dependency : dependencyInfo.getDependencies().get(controller)) {
960 dependencyList.add(dependency.getDependency());
962 return dependencyList;
963 } catch (IOException | NullPointerException e) {
964 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
965 + "Error while getting dependecy Information for controller: " + controllerName
966 + e.getMessage(), e);
969 return defaultDependencies(controllerName);
973 * Default Dependency Section. Can be changed as required.
975 * @param controllerName the controller name
976 * @return changed dependency list
978 public List<Dependency> defaultDependencies(final String controllerName) {
980 final List<Dependency> dependencyList = new ArrayList<>();
981 final String version = StringEscapeUtils.escapeJava(brmsdependencyversion);
983 final Dependency demoDependency = new Dependency();
984 demoDependency.setGroupId(DROOLS_APPS_TEMPLATE_GROUP);
985 demoDependency.setArtifactId("template.demo");
986 demoDependency.setVersion(version);
987 dependencyList.add(demoDependency);
989 final Dependency controlloopDependency = new Dependency();
990 controlloopDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
991 controlloopDependency.setArtifactId("events");
992 controlloopDependency.setVersion(version);
993 dependencyList.add(controlloopDependency);
995 final Dependency restDependency = new Dependency();
996 restDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
997 restDependency.setArtifactId("controlloop.common.model-impl.rest");
998 restDependency.setVersion(version);
999 dependencyList.add(restDependency);
1001 final Dependency appcDependency = new Dependency();
1002 appcDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1003 appcDependency.setArtifactId("controlloop.common.model-impl.appc");
1004 appcDependency.setVersion(version);
1005 dependencyList.add(appcDependency);
1007 final Dependency aaiDependency = new Dependency();
1008 aaiDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1009 aaiDependency.setArtifactId("controlloop.common.model-impl.aai");
1010 aaiDependency.setVersion(version);
1011 dependencyList.add(aaiDependency);
1013 final Dependency msoDependency = new Dependency();
1014 msoDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1015 msoDependency.setArtifactId("controlloop.common.model-impl.so");
1016 msoDependency.setVersion(version);
1017 dependencyList.add(msoDependency);
1019 final Dependency trafficgeneratorDependency = new Dependency();
1020 trafficgeneratorDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1021 trafficgeneratorDependency.setArtifactId("controlloop.common.model-impl.trafficgenerator");
1022 trafficgeneratorDependency.setVersion(version);
1023 dependencyList.add(trafficgeneratorDependency);
1024 return dependencyList;
1027 private void createProject(final String path, final String ksessionName) {
1028 new File(path + File.separator + RULES).mkdirs();
1029 new File(path + File.separator + META_INF).mkdirs();
1030 if (!Files.exists(Paths.get(path + File.separator + META_INF + File.separator + KMODULE_XML_FILE))) {
1031 // Hard coding XML for PDP Drools to accept our Rules.
1032 final String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "\n"
1033 + "<kmodule xmlns=\"http://jboss.org/kie/6.0.0/kmodule\">" + "\n"
1034 + "<kbase name=\"rules\" packages=\"rules\">" + "\n" + "<ksession name=\"" + ksessionName + "\"/>"
1035 + "\n" + "</kbase></kmodule>";
1036 copyDataToFile(path + File.separator + META_INF + File.separator + KMODULE_XML_FILE, xml);
1040 private void copyDataToFile(final String file, final String rule) {
1042 FileUtils.writeStringToFile(new File(file), rule);
1043 } catch (final Exception e) {
1045 XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while creating Rule for " + file + e.getMessage(),
1050 private void readGroups(final Properties config) throws PolicyException {
1051 String[] groupNames;
1052 final String groupNamesError = "groupNames property is missing or empty from the property file ";
1053 if (!config.containsKey(GROUP_NAMES) || config.getProperty(GROUP_NAMES) == null) {
1054 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + groupNamesError);
1056 if (config.getProperty(GROUP_NAMES).contains(",")) {
1057 groupNames = config.getProperty(GROUP_NAMES).replaceAll(" ", "").split(",");
1059 groupNames = new String[] {config.getProperty(GROUP_NAMES).replaceAll(" ", "")};
1061 if (groupNames == null || groupNames.length == 0) {
1062 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + groupNamesError);
1063 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + groupNamesError);
1065 groupMap = new HashMap<>();
1066 for (int counter = 0; counter < groupNames.length; counter++) {
1067 final String name = groupNames[counter];
1068 final String groupId = config.getProperty(name + ".groupID");
1069 if (groupId == null) {
1070 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1071 + ".groupID property is missing from the property file ");
1072 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1073 + ".groupID property is missing from the property file ");
1075 final String artifactId = config.getProperty(name + ".artifactID");
1076 if (artifactId == null) {
1077 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1078 + ".artifactID property is missing from the property file ");
1079 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1080 + ".artifactID property is missing from the property file ");
1082 final PEDependency dependency = new PEDependency();
1083 dependency.setArtifactId(artifactId);
1084 dependency.setGroupId(groupId);
1085 // Add to list if we got all
1086 addToGroup(name, dependency);
1090 private void addToGroup(final String name, final PEDependency dependency) {
1091 final ArrayList<Object> values = new ArrayList<>();
1092 values.add(dependency);
1093 groupMap.put(name, values);
1094 final EntityTransaction et = em.getTransaction();
1096 final Query query = em.createQuery("select b from BrmsGroupInfo as b where b.controllerName = :cn");
1097 query.setParameter("cn", name);
1098 final List<?> groupList = query.getResultList();
1099 BrmsGroupInfo brmsGroupInfo = null;
1100 if (!groupList.isEmpty()) {
1101 LOGGER.info("Controller name already Existing in DB. Will be updating the DB Values" + name);
1102 brmsGroupInfo = (BrmsGroupInfo) groupList.get(0);
1104 if (brmsGroupInfo == null) {
1105 brmsGroupInfo = new BrmsGroupInfo();
1107 brmsGroupInfo.setControllerName(name);
1108 brmsGroupInfo.setGroupId(dependency.getGroupId());
1109 brmsGroupInfo.setArtifactId(dependency.getArtifactId());
1110 brmsGroupInfo.setVersion(dependency.getVersion());
1111 em.persist(brmsGroupInfo);
1116 private String getArtifactId(final String name) {
1117 return ((PEDependency) groupMap.get(name).get(0)).getArtifactId();
1120 private String getGroupId(final String name) {
1121 return ((PEDependency) groupMap.get(name).get(0)).getGroupId();
1124 private String getVersion(final String name) {
1125 return ((PEDependency) groupMap.get(name).get(0)).getVersion();
1128 private void getNameAndSetRemove(final String controllerName, final String policyName) {
1129 final String artifactName = getArtifactId(controllerName);
1130 final String ruleFolder = PROJECTSLOCATION + File.separator + artifactName + File.separator + "src"
1131 + File.separator + "main" + File.separator + RESOURCES + File.separator + RULES;
1132 final File file = new File(ruleFolder + File.separator + policyName + ".drl");
1133 if (file.delete()) {
1134 LOGGER.info("Deleted File.. " + file.getAbsolutePath());
1135 removePolicyFromGroup(policyName, controllerName);
1137 if (new File(ruleFolder).listFiles().length == 0) {
1138 removedRuleModifiedGroup(controllerName);
1140 // This is an update in terms of PDPD.
1141 addModifiedGroup(controllerName, "update");
1145 // Removes Policy from Memory and Database.
1146 private void removePolicyFromGroup(final String policyName, final String controllerName) {
1147 policyMap.remove(policyName);
1148 final EntityTransaction et = em.getTransaction();
1150 final Query query = em.createQuery("select b from BrmsPolicyInfo as b where b.policyName = :pn");
1151 query.setParameter("pn", policyName);
1152 final List<?> pList = query.getResultList();
1153 BrmsPolicyInfo brmsPolicyInfo;
1154 if (!pList.isEmpty()) {
1156 brmsPolicyInfo = (BrmsPolicyInfo) pList.get(0);
1157 if (brmsPolicyInfo.getControllerName().getControllerName().equals(controllerName)) {
1158 em.remove(brmsPolicyInfo);
1165 private void setVersion(final String selectedName) {
1166 String newVersion = VERSION_0_1_0;
1168 final NexusArtifact artifact = getLatestArtifactFromNexus(selectedName);
1169 if (artifact != null) {
1170 newVersion = incrementVersion(artifact.getVersion());
1172 if (VERSION_0_1_0.equals(newVersion)) {
1175 setVersion(newVersion, selectedName);
1176 LOGGER.info("Controller: " + selectedName + "is on version: " + newVersion);
1179 private void setVersion(final String newVersion, final String controllerName) {
1180 final PEDependency userController = (PEDependency) groupMap.get(controllerName).get(0);
1181 userController.setVersion(newVersion);
1182 groupMap.get(controllerName).set(0, userController);
1185 // Return BackUpMonitor
1186 public static BackUpMonitor getBackUpMonitor() {
1193 public void rotateUrls() {
1194 if (repUrlList != null) {
1195 Collections.rotate(repUrlList, -1);
1200 * Get URL List Size.
1202 * @return URL list size
1204 public int urlListSize() {
1205 return repUrlList != null ? repUrlList.size() : 0;