2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.brms.api;
24 import com.att.nsa.cambria.client.CambriaBatchingPublisher;
25 import com.att.nsa.cambria.client.CambriaClientBuilders;
26 import com.att.nsa.cambria.client.CambriaClientBuilders.PublisherBuilder;
27 import com.fasterxml.jackson.core.JsonProcessingException;
30 import java.io.FileInputStream;
31 import java.io.FileOutputStream;
32 import java.io.IOException;
33 import java.io.InputStream;
34 import java.io.Writer;
36 import java.nio.channels.Channels;
37 import java.nio.channels.ReadableByteChannel;
38 import java.nio.charset.StandardCharsets;
39 import java.nio.file.Files;
40 import java.nio.file.Path;
41 import java.nio.file.Paths;
42 import java.security.GeneralSecurityException;
43 import java.util.ArrayList;
44 import java.util.Arrays;
45 import java.util.Collections;
46 import java.util.Enumeration;
47 import java.util.HashMap;
48 import java.util.List;
50 import java.util.Properties;
51 import java.util.UUID;
52 import java.util.concurrent.TimeUnit;
53 import java.util.jar.JarEntry;
54 import java.util.jar.JarFile;
55 import java.util.regex.Pattern;
57 import javax.persistence.EntityManager;
58 import javax.persistence.EntityManagerFactory;
59 import javax.persistence.EntityTransaction;
60 import javax.persistence.Persistence;
61 import javax.persistence.TypedQuery;
62 import javax.ws.rs.ProcessingException;
64 import org.apache.commons.io.FileUtils;
65 import org.apache.commons.lang.StringEscapeUtils;
66 import org.apache.maven.model.Dependency;
67 import org.apache.maven.model.DeploymentRepository;
68 import org.apache.maven.model.DistributionManagement;
69 import org.apache.maven.model.Model;
70 import org.apache.maven.model.io.xpp3.MavenXpp3Writer;
71 import org.apache.maven.shared.invoker.DefaultInvocationRequest;
72 import org.apache.maven.shared.invoker.DefaultInvoker;
73 import org.apache.maven.shared.invoker.InvocationRequest;
74 import org.apache.maven.shared.invoker.InvocationResult;
75 import org.apache.maven.shared.invoker.Invoker;
76 import org.codehaus.plexus.util.IOUtil;
78 import org.codehaus.plexus.util.WriterFactory;
79 import org.eclipse.persistence.config.PersistenceUnitProperties;
80 import org.onap.policy.api.PEDependency;
81 import org.onap.policy.api.PolicyException;
82 import org.onap.policy.brms.api.nexus.NexusRestSearchParameters;
83 import org.onap.policy.brms.api.nexus.NexusRestWrapper;
84 import org.onap.policy.brms.api.nexus.NexusRestWrapperException;
85 import org.onap.policy.brms.api.nexus.pojo.NexusArtifact;
86 import org.onap.policy.brms.entity.BrmsGroupInfo;
87 import org.onap.policy.brms.entity.BrmsPolicyInfo;
88 import org.onap.policy.brms.entity.DependencyInfo;
89 import org.onap.policy.common.im.IntegrityMonitor;
90 import org.onap.policy.common.logging.eelf.MessageCodes;
91 import org.onap.policy.common.logging.eelf.PolicyLogger;
92 import org.onap.policy.common.logging.flexlogger.FlexLogger;
93 import org.onap.policy.common.logging.flexlogger.Logger;
94 import org.onap.policy.utils.BackUpHandler;
95 import org.onap.policy.utils.BackUpMonitor;
96 import org.onap.policy.utils.BusPublisher;
97 import org.onap.policy.utils.PolicyUtils;
98 import org.onap.policy.xacml.api.XACMLErrorConstants;
101 * BRMSPush: Application responsible to push policies to the BRMS PDP Policy Repository (PR).
102 * Mavenize and push policy to PR
107 public class BrmsPush {
108 private static final String GROUP_NAMES = "groupNames";
109 private static final String DROOLS_APPS_TEMPLATE_GROUP =
110 "org.onap.policy.drools-applications.controlloop.templates";
111 private static final String DROOLS_APPS_MODEL_GROUP =
112 "org.onap.policy.drools-applications.controlloop.common.model-impl";
113 private static final String META_INF = "META-INF";
114 private static final String KMODULE_XML_FILE = "kmodule.xml";
115 private static final String POM_XML_FILE = "pom.xml";
116 private static final String VERSION_0_1_0 = "0.1.0";
117 private static final String RULES = "rules";
118 private static final String RESOURCES = "resources";
119 private static final Logger LOGGER = FlexLogger.getLogger(BrmsPush.class.getName());
120 private static final String PROJECTSLOCATION = "RuleProjects";
121 private static final String[] GOALS = {"clean", "deploy"};
122 private static final String DEFAULT_VERSION = "1.3.0-SNAPSHOT";
123 private static final String DEPENDENCY_FILE = "dependency.json";
124 private static final String BRMSPERSISTENCE = "brmsEclipselink.persistencexml";
126 private static Map<String, String> modifiedGroups = new HashMap<>();
127 private static IntegrityMonitor im;
128 private static BackUpMonitor bm;
129 private String defaultName = null;
130 private String repId = null;
131 private String repName = null;
132 private List<String> repUrlList = null;
133 private String repUserName = null;
134 private String repPassword = null;
135 private String policyKeyId = null;
136 private boolean createFlag = false;
137 private String uebList = null;
138 private List<String> dmaapList = null;
139 private String pubTopic = null;
140 private PublisherBuilder pubBuilder = null;
141 protected BusPublisher publisher = null;
142 private Long uebDelay = Long.parseLong("20");
143 private Long dmaapDelay = Long.parseLong("5000");
144 private String notificationType = null;
145 private List<ControllerPojo> controllers;
146 private Map<String, ArrayList<Object>> groupMap = new HashMap<>();
147 private final Map<String, String> policyMap = new HashMap<>();
148 private String brmsdependencyversion;
149 private EntityManager em;
150 private boolean syncFlag = false;
153 * Responsible to push policies to the BRMS PDP Policy Repository (PR).
155 * @param propertiesFile the properties file
156 * @param handler the {@link BackUpHandler}
157 * @throws PolicyException PolicyException related to the operation
159 public BrmsPush(final String propertiesFile, final BackUpHandler handler) throws PolicyException {
160 if (propertiesFile == null || handler == null) {
161 throw new PolicyException("Error no propertiesFile or handler");
163 final Properties config = new Properties();
164 final Path file = Paths.get(propertiesFile);
165 if (Files.notExists(file)) {
166 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Config File doesn't Exist in the specified Path "
168 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
169 + "Config File doesn't Exist in the specified Path " + file.toString());
171 if (file.toString().endsWith(".properties")) {
172 // Grab the Properties.
173 setProperty(file, config, handler);
178 private void setProperty(final Path file, final Properties config, final BackUpHandler handler)
179 throws PolicyException {
182 in = new FileInputStream(file.toFile());
184 } catch (final IOException e) {
186 XACMLErrorConstants.ERROR_DATA_ISSUE + "Data/File Read Error while reading from the property file.",
188 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
189 + "Data/File Read Error while reading from the property file.");
191 LOGGER.info("Trying to set up IntegrityMonitor");
192 String resourceName = null;
194 LOGGER.info("Trying to set up IntegrityMonitor");
195 resourceName = config.getProperty("RESOURCE_NAME");
196 if (resourceName == null) {
197 LOGGER.warn("RESOURCE_NAME is missing setting default value. ");
198 resourceName = "brmsgw_pdp01";
200 resourceName = resourceName.trim();
201 setIntegrityMonitor(IntegrityMonitor.getInstance(resourceName, config));
202 } catch (final Exception e) {
203 LOGGER.error("Error starting Integerity Monitor: " + e);
205 LOGGER.info("Trying to set up BackUpMonitor");
207 setBackupMonitor(BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), resourceName, config,
209 } catch (final Exception e) {
210 LOGGER.error("Error starting BackUpMonitor: " + e);
212 if (!config.containsKey(BRMSPERSISTENCE)) {
213 config.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, "META-INF/persistenceBRMS.xml");
215 config.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML,
216 config.getProperty(BRMSPERSISTENCE, "META-INF/persistenceBRMS.xml"));
218 final EntityManagerFactory emf = Persistence.createEntityManagerFactory("BRMSGW", config);
219 em = emf.createEntityManager();
220 defaultName = config.getProperty("defaultName");
221 if (defaultName == null) {
223 XACMLErrorConstants.ERROR_DATA_ISSUE + "defaultName property is missing from the property file ");
224 throw new PolicyException(
225 XACMLErrorConstants.ERROR_DATA_ISSUE + "defaultName property is missing from the property file");
227 defaultName = defaultName.trim();
228 repId = config.getProperty("repositoryID");
231 XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryID property is missing from the property file ");
232 throw new PolicyException(
233 XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryID property is missing from the property file ");
235 repId = repId.trim();
236 repName = config.getProperty("repositoryName");
237 if (repName == null) {
238 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
239 + "repositoryName property is missing from the property file ");
240 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
241 + "repositoryName property is missing from the property file ");
243 repName = repName.trim();
244 final String repUrl = config.getProperty("repositoryURL");
245 if (repUrl == null) {
247 XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryURL property is missing from the property file ");
248 throw new PolicyException(
249 XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryURL property is missing from the property file ");
251 if (repUrl.contains(",")) {
252 repUrlList = new ArrayList<>(Arrays.asList(repUrl.trim().split(",")));
254 repUrlList = new ArrayList<>();
255 repUrlList.add(repUrl);
257 repUserName = config.getProperty("repositoryUsername");
258 repPassword = config.getProperty("repositoryPassword");
259 if (repUserName == null || repPassword == null) {
260 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
261 + "repostoryUserName and respositoryPassword properties are required.");
262 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
263 + "repostoryUserName and respositoryPassword properties are required.");
265 repUserName = repUserName.trim();
266 repPassword = repPassword.trim();
267 policyKeyId = config.getProperty("policyKeyID");
268 if (policyKeyId == null) {
270 XACMLErrorConstants.ERROR_DATA_ISSUE + "policyKeyID property is missing from the property file ");
271 throw new PolicyException(
272 XACMLErrorConstants.ERROR_DATA_ISSUE + "policyKeyID property is missing from the property file ");
274 policyKeyId = policyKeyId.trim();
275 final String syncF = config.getProperty("sync", "false").trim();
276 syncFlag = Boolean.parseBoolean(syncF);
278 PolicyLogger.info("SYNC Flag is turned ON. DB will be given Priority.");
280 brmsdependencyversion = config.getProperty("brms.dependency.version");
281 if (brmsdependencyversion == null) {
282 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
283 + "brmsdependencyversion property is missing from the property file, Using default Version.");
284 brmsdependencyversion = DEFAULT_VERSION;
286 brmsdependencyversion = brmsdependencyversion.trim();
290 notificationType = config.getProperty("NOTIFICATION_TYPE");
291 if ("dmaap".equalsIgnoreCase(notificationType)) {
293 LOGGER.info("Notification Type being used is DMaaP... creating instance of BusPublisher.");
294 // Setting up the Publisher for DMaaP MR
295 String dmaapServers = config.getProperty("NOTIFICATION_SERVERS");
296 pubTopic = config.getProperty("NOTIFICATION_TOPIC");
297 final String aafLogin = config.getProperty("CLIENT_ID").trim();
298 final String aafPassword = config.getProperty("CLIENT_KEY").trim();
300 if (dmaapServers == null || pubTopic == null) {
302 XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file ");
303 throw new PolicyException(
304 XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file ");
307 dmaapServers = dmaapServers.trim();
308 pubTopic = pubTopic.trim();
310 if (dmaapServers.contains(",")) {
311 dmaapList = new ArrayList<>(Arrays.asList(dmaapServers.split("\\s*,\\s*")));
313 dmaapList = new ArrayList<>();
314 dmaapList.add(dmaapServers);
318 new BusPublisher.DmaapPublisherWrapper(this.dmaapList, this.pubTopic, aafLogin, aafPassword);
320 String notificationDelay = config.getProperty("NOTIFICATION_DELAY");
321 if (notificationDelay != null && !notificationDelay.isEmpty()) {
322 notificationDelay = notificationDelay.trim();
324 dmaapDelay = Long.parseLong(notificationDelay);
325 } catch (final NumberFormatException e) {
326 LOGGER.error("DMAAP_DELAY not a long format number" + e);
329 LOGGER.info("DMAAP BusPublisher is created.");
332 LOGGER.info("Notification Type being used is UEB... creating instance of PublisherBuilder.");
333 // Setting up the Publisher for UEB
334 uebList = config.getProperty("NOTIFICATION_SERVERS");
335 pubTopic = config.getProperty("NOTIFICATION_TOPIC");
336 if (uebList == null || pubTopic == null) {
338 XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file ");
339 throw new PolicyException(
340 XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file ");
342 uebList = uebList.trim();
343 pubTopic = pubTopic.trim();
344 pubBuilder = new CambriaClientBuilders.PublisherBuilder();
345 pubBuilder.usingHosts(uebList).onTopic(pubTopic).usingHttps(true);
346 String apiKey = config.getProperty("UEB_API_KEY");
347 String apiSecret = config.getProperty("UEB_API_SECRET");
348 if (apiKey != null && !apiKey.isEmpty() && apiSecret != null && !apiSecret.isEmpty()) {
349 apiKey = apiKey.trim();
350 apiSecret = apiSecret.trim();
351 pubBuilder.authenticatedBy(apiKey, apiSecret);
353 String notificationDelay = config.getProperty("NOTIFICATION_DELAY");
354 if (notificationDelay != null && !notificationDelay.isEmpty()) {
355 notificationDelay = notificationDelay.trim();
357 uebDelay = Long.parseLong(notificationDelay);
358 } catch (final NumberFormatException e) {
359 LOGGER.error("UEB_DELAY not a long format number" + e);
362 LOGGER.info("UEB PublisherBuilder is created.");
368 private static void setBackupMonitor(final BackUpMonitor instance) {
372 private static void setIntegrityMonitor(final IntegrityMonitor instance) {
377 * Will Initialize the variables required for BRMSPush.
379 public void initiate(final boolean flag) {
380 resetModifiedGroups();
381 controllers = new ArrayList<>();
383 bm.updateNotification();
384 } catch (final Exception e) {
385 LOGGER.error("Error while updating Notification: " + e.getMessage(), e);
392 public void resetDs() {
393 resetModifiedGroups();
394 controllers = new ArrayList<>();
397 private static void resetModifiedGroups() {
398 modifiedGroups = new HashMap<>();
402 * Will Add rules to projects. Creates necessary folders if required.
404 public void addRule(final String name, final String rule, final Map<String, String> responseAttributes) {
405 // 1 check the response Attributes and determine if this belongs to any projects.
406 // 2 if not create folder
409 // 5 store the groups that have been updated.
410 String ksessionName = null;
411 String selectedName = null;
412 if (!responseAttributes.isEmpty()) {
413 // Pick selected Value
414 String userControllerName = null;
415 final ArrayList<PEDependency> userDependencies = new ArrayList<>();
416 for (final Map.Entry<String, String> entry : responseAttributes.entrySet()) {
417 final String key = entry.getKey();
418 String value = entry.getValue();
419 if (key.equals(policyKeyId)) {
420 selectedName = value;
422 // kmodule configurations
423 else if ("kSessionName".equals(key)) {
424 ksessionName = value;
426 // Check User Specific values.
427 if ("$controller:".equals(key)) {
428 userControllerName = getUserControllerName(key, value);
429 } else if ("$dependency$".equals(key) && value.startsWith("[") && value.endsWith("]")) {
430 updateUserDependencies(userDependencies, value);
433 if (userControllerName != null) {
434 // Adding custom dependencies here.
435 final ArrayList<Object> values = groupMap.get(userControllerName);
436 values.add(userDependencies);
437 groupMap.put(userControllerName, values);
438 selectedName = userControllerName;
441 // If no Match then pick Default.
442 if (selectedName == null) {
443 selectedName = defaultName;
445 if (groupMap.containsKey(selectedName)) {
446 // If the key is not got as parameters set by the user, setting the default value for
449 if (ksessionName == null) {
450 LOGGER.info("kSessionName is null, selectedName is : " + selectedName);
451 if (selectedName.equalsIgnoreCase(defaultName)) {
452 ksessionName = "closedloop";
454 ksessionName = "closedloop-" + selectedName;
457 // create directories if missing.
458 manageProject(selectedName, ksessionName, name, rule);
460 // Will check for Create Later after generating the Pom.
461 addModifiedGroup(selectedName, "update");
465 private String getUserControllerName(String key, String value) {
466 String userControllerName = null;
467 // Check User Specific values.
469 final PEDependency dependency = PolicyUtils.jsonStringToObject(value, PEDependency.class);
470 userControllerName = key.replaceFirst("$controller:", "");
471 LOGGER.info("addRule: userControllerName - " + userControllerName + ", dependency: - "
473 addToGroup(userControllerName, dependency);
474 } catch (final Exception e) {
475 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while resolving Controller: " + e);
477 return userControllerName;
480 private void updateUserDependencies(ArrayList<PEDependency> userDependencies, String value) {
481 //update the user dependencies supplied as parameter to this method
482 value = value.substring(1, value.length() - 1).trim();
483 final List<String> dependencyStrings = Arrays.asList(value.split(Pattern.quote("},{")));
484 for (final String dependencyString : dependencyStrings) {
486 userDependencies.add(PolicyUtils.jsonStringToObject(dependencyString, PEDependency.class));
487 } catch (final Exception e) {
488 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while resolving Dependencies: "
494 private void syncGroupInfo() {
495 // Sync DB to JMemory.
496 final EntityTransaction et = em.getTransaction();
499 final TypedQuery<BrmsGroupInfo> groupInfoQuery =
500 em.createQuery("select b from BrmsGroupInfo AS b", BrmsGroupInfo.class);
501 final List<BrmsGroupInfo> groupInfoResult = groupInfoQuery.getResultList();
502 if (groupInfoResult.size() != groupMap.size()) {
503 for (final BrmsGroupInfo brmsGroupInfo : groupInfoResult) {
504 final PEDependency dependency = new PEDependency();
505 dependency.setArtifactId(brmsGroupInfo.getArtifactId());
506 dependency.setGroupId(brmsGroupInfo.getGroupId());
507 dependency.setVersion(brmsGroupInfo.getVersion());
508 final ArrayList<Object> values = new ArrayList<>();
509 values.add(dependency);
510 groupMap.put(brmsGroupInfo.getControllerName(), values);
514 final TypedQuery<BrmsPolicyInfo> policyInfoQuery =
515 em.createQuery("select g from BrmsPolicyInfo AS g", BrmsPolicyInfo.class);
516 final List<BrmsPolicyInfo> policyInfoResult = policyInfoQuery.getResultList();
517 if (policyInfoResult.size() != policyMap.size()) {
518 for (final BrmsPolicyInfo brmsPolicyInfo : policyInfoResult) {
519 policyMap.put(brmsPolicyInfo.getPolicyName(),
520 brmsPolicyInfo.getControllerName().getControllerName());
524 LOGGER.info("Updated Local Memory values with values from database.");
525 } catch (final Exception exception) {
526 LOGGER.error("Unable to sync group info", exception);
532 private void manageProject(final String selectedName, final String ksessionName, final String name,
534 // Check if the Project is in Sync. If not get the latest Version.
535 syncProject(selectedName);
536 createProject(PROJECTSLOCATION + File.separator + getArtifactId(selectedName) + File.separator + "src"
537 + File.separator + "main" + File.separator + RESOURCES, ksessionName);
538 copyDataToFile(PROJECTSLOCATION + File.separator + getArtifactId(selectedName) + File.separator + "src"
539 + File.separator + "main" + File.separator + RESOURCES + File.separator + RULES + File.separator + name
541 addToPolicy(name, selectedName);
545 * Add Policy to JMemory and DataBase.
547 private void addToPolicy(final String policyName, final String controllerName) {
549 final EntityTransaction et = em.getTransaction();
552 boolean create = false;
553 final TypedQuery<BrmsPolicyInfo> policyInfoQuery =
554 em.createQuery("select b from BrmsPolicyInfo as b where b.policyName = :pn", BrmsPolicyInfo.class);
555 policyInfoQuery.setParameter("pn", policyName);
556 final List<BrmsPolicyInfo> policyInfoResultList = policyInfoQuery.getResultList();
557 BrmsPolicyInfo brmsPolicyInfo = new BrmsPolicyInfo();
558 if (!policyInfoResultList.isEmpty()) {
560 brmsPolicyInfo = policyInfoResultList.get(0);
561 if (!brmsPolicyInfo.getControllerName().getControllerName().equals(controllerName)) {
568 final TypedQuery<BrmsGroupInfo> groupInfoQuery = em.createQuery(
569 "select b from BrmsGroupInfo as b where b.controllerName = :cn", BrmsGroupInfo.class);
570 groupInfoQuery.setParameter("cn", controllerName);
571 final List<BrmsGroupInfo> groupInfoResultList = groupInfoQuery.getResultList();
572 BrmsGroupInfo brmsGroupInfo = new BrmsGroupInfo();
573 if (!groupInfoResultList.isEmpty()) {
574 brmsGroupInfo = groupInfoResultList.get(0);
576 brmsPolicyInfo.setPolicyName(policyName);
577 brmsPolicyInfo.setControllerName(brmsGroupInfo);
578 em.persist(brmsPolicyInfo);
583 policyMap.put(policyName, controllerName);
584 } catch (final Exception exception) {
585 LOGGER.error("Unable add policy to database", exception);
591 private void syncProject(final String selectedName) {
592 final boolean projectExists = checkProject(selectedName);
595 version = getVersion(selectedName);
596 if (version == null) {
597 LOGGER.error("Error getting local version for the given Controller Name:" + selectedName
598 + " going with Default value");
599 version = VERSION_0_1_0;
601 final String nextVersion = incrementVersion(version);
602 final boolean outOfSync = checkRemoteSync(selectedName, nextVersion);
607 // We are out of Sync or Project is not Present.
608 downloadProject(selectedName);
611 private void downloadProject(final String selectedName) {
612 final NexusArtifact artifact = getLatestArtifactFromNexus(selectedName);
613 if (artifact == null) {
616 final String dirName = getDirectoryName(selectedName);
618 final String fileName = "rule.jar";
620 website = new URL(artifact.getUrlPath() + ".jar");
621 try (ReadableByteChannel rbc = Channels.newChannel(website.openStream());
622 FileOutputStream fos = new FileOutputStream(fileName)) {
623 fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
624 extractJar(fileName, dirName);
625 new File(fileName).delete();
626 } catch (final IOException e) {
627 LOGGER.error("Error while downloading the project to File System. " + e.getMessage(), e);
630 } catch (final IOException e1) {
631 LOGGER.error("Error while retrieve the artifact. " + e1.getMessage(), e1);
635 private void extractJar(final String jarFileName, final String artifactId) {
636 try (JarFile jar = new JarFile(jarFileName)) {
637 final Enumeration<?> enumEntries = jar.entries();
638 while (enumEntries.hasMoreElements()) {
639 parseJarContents(artifactId, jar, enumEntries);
641 } catch (final IOException e) {
642 LOGGER.info("exception Occured" + e);
646 private void parseJarContents(String artifactId, JarFile jar, Enumeration<?> enumEntries) {
647 final JarEntry jarEntry = (JarEntry) enumEntries.nextElement();
649 final String fileName = jarEntry.getName().substring(jarEntry.getName().lastIndexOf("/") + 1);
650 if (jarEntry.getName().endsWith(".drl")) {
651 final String path = PROJECTSLOCATION + File.separator + artifactId + File.separator + "src"
652 + File.separator + "main" + File.separator + RESOURCES + File.separator + RULES;
653 new File(path).mkdirs();
654 if (syncFlag && policyMap.containsKey(fileName.replace(".drl", ""))) {
655 file = new File(path + File.separator + fileName);
657 file = new File(path + File.separator + fileName);
659 } else if (jarEntry.getName().endsWith(POM_XML_FILE)) {
660 final String path = PROJECTSLOCATION + File.separator + artifactId;
661 new File(path).mkdirs();
662 file = new File(path + File.separator + fileName);
663 } else if (jarEntry.getName().endsWith(KMODULE_XML_FILE)) {
664 final String path = PROJECTSLOCATION + File.separator + artifactId + File.separator + "src"
665 + File.separator + "main" + File.separator + RESOURCES + File.separator + META_INF;
666 new File(path).mkdirs();
667 file = new File(path + File.separator + fileName);
670 try (InputStream is = jar.getInputStream(jarEntry);
671 FileOutputStream fos = new FileOutputStream(file)) {
672 while (is.available() > 0) {
673 fos.write(is.read());
675 LOGGER.info(fileName + " Created..");
676 } catch (final IOException e) {
677 LOGGER.info("exception Occured" + e);
682 private NexusArtifact getLatestArtifactFromNexus(final String selectedName) {
683 final List<NexusArtifact> artifacts = getArtifactFromNexus(selectedName, null);
686 NexusArtifact result = null;
687 for (final NexusArtifact artifact : artifacts) {
689 Integer.parseInt(artifact.getVersion().substring(0, artifact.getVersion().indexOf(".")));
690 final int minorVal = Integer.parseInt(artifact.getVersion()
691 .substring(artifact.getVersion().indexOf(".") + 1, artifact.getVersion().lastIndexOf(".")));
692 if (majorVal > bigNum) {
696 if ((bigNum == majorVal) && (minorVal > smallNum)) {
699 if (bigNum == majorVal && minorVal == smallNum) {
703 return additionalNexusLatestCheck(selectedName, result);
706 // Additional Check due to Limitations from Nexus API to check if the artifact is the latest.
707 private NexusArtifact additionalNexusLatestCheck(final String selectedName, final NexusArtifact result) {
708 if (result == null) {
711 final String nextVersion = incrementVersion(result.getVersion());
712 final List<NexusArtifact> artifact = getArtifactFromNexus(selectedName, nextVersion);
713 return artifact.isEmpty() ? result : additionalNexusLatestCheck(selectedName, artifact.get(0));
716 private boolean checkRemoteSync(final String selectedName, final String version) {
717 final List<NexusArtifact> artifacts = getArtifactFromNexus(selectedName, version);
718 return artifacts.isEmpty() ? false : true;
721 private List<NexusArtifact> getArtifactFromNexus(final String selectedName, final String version) {
722 NexusRestWrapper restWrapper = null;
724 boolean flag = false;
725 while (index < repUrlList.size()) {
727 final String repUrl = repUrlList.get(0);
729 new NexusRestWrapper(repUrl.substring(0, repUrl.indexOf(repUrl.split(":[0-9]+\\/nexus")[1])),
730 repUserName, repPassword);
731 final NexusRestSearchParameters searchParameters = new NexusRestSearchParameters();
732 searchParameters.useFilterSearch(getGroupId(selectedName), getArtifactId(selectedName), version, null,
735 final List<NexusArtifact> resultList = restWrapper.findArtifact(searchParameters).getArtifactList();
736 if (resultList != null) {
740 } catch (NexusRestWrapperException | ProcessingException e) {
741 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Connection to remote Nexus has failed. "
742 + e.getMessage(), e);
744 if (null != restWrapper) {
748 Collections.rotate(repUrlList, -1);
753 return new ArrayList<>();
756 private String incrementVersion(final String version) {
757 int majorVal = Integer.parseInt(version.substring(0, version.indexOf(".")));
758 int minorVal = Integer.parseInt(version.substring(version.indexOf(".") + 1, version.lastIndexOf(".")));
765 return majorVal + "." + minorVal + version.substring(version.lastIndexOf("."));
768 private boolean checkProject(final String selectedName) {
769 return new File(PROJECTSLOCATION + File.separator + getDirectoryName(selectedName)).exists();
772 private String getDirectoryName(final String selectedName) {
773 return getArtifactId(selectedName);
777 * Will Push policies to the PolicyRepo.
779 * @throws PolicyException PolicyException related to the operation
781 public void pushRules() throws PolicyException {
782 // Check how many groups have been updated.
783 // Invoke their Maven process.
785 im.startTransaction();
786 } catch (final Exception e) {
787 LOGGER.error("Error while starting Transaction " + e);
789 if (!modifiedGroups.isEmpty()) {
790 if (buildAndGenerateJarFile()) {
791 sendNotification(controllers);
800 * Removes a Rule from Rule Projects.
802 public void removeRule(final String name) {
803 final String controllerName = getGroupName(name);
804 if (controllerName == null) {
805 LOGGER.info("Error finding the controllerName for the given Policy: " + name);
808 syncProject(controllerName);
809 getNameAndSetRemove(controllerName, name);
812 private Boolean buildAndGenerateJarFile() throws PolicyException {
813 Boolean flag = false;
814 for (final Map.Entry<String, String> entry : modifiedGroups.entrySet()) {
815 InvocationResult result = null;
816 final String group = entry.getKey();
818 LOGGER.info("PushRules: ModifiedGroups, Key: " + group + ", Value: " + entry.getValue());
819 final InvocationRequest request = new DefaultInvocationRequest();
822 request.setPomFile(new File(
823 PROJECTSLOCATION + File.separator + getArtifactId(group) + File.separator + POM_XML_FILE));
824 request.setGoals(Arrays.asList(GOALS));
825 final Invoker invoker = new DefaultInvoker();
826 result = invoker.execute(request);
827 if (result.getExecutionException() != null) {
828 LOGGER.error(result.getExecutionException());
829 } else if (result.getExitCode() != 0) {
830 LOGGER.error("Maven Invocation failure..!");
832 } catch (final Exception e) {
833 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation issue for "
834 + getArtifactId(group) + e.getMessage(), e);
836 if (result != null && result.getExitCode() == 0) {
837 LOGGER.info("Build Completed..!");
839 addNotification(group, "create");
841 addNotification(group, entry.getValue());
845 throw new PolicyException(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation failure!");
851 private String getGroupName(final String name) {
852 if (policyMap.containsKey(name)) {
853 return policyMap.get(name);
856 return policyMap.containsKey(name) ? policyMap.get(name) : null;
860 private void addModifiedGroup(final String controllerName, final String operation) {
861 if (controllerName != null) {
862 modifiedGroups.put(controllerName, operation);
866 private void addNotification(final String controllerName, final String operation) {
867 final ControllerPojo controllerPojo = new ControllerPojo();
868 controllerPojo.setName(controllerName);
869 controllerPojo.setOperation(operation);
870 final HashMap<String, String> drools = new HashMap<>();
871 drools.put("groupId", getGroupId(controllerName));
872 drools.put("artifactId", getArtifactId(controllerName));
873 drools.put("version", getVersion(controllerName));
874 controllerPojo.setDrools(drools);
875 controllers.add(controllerPojo);
877 LOGGER.debug("Notification added: " + PolicyUtils.objectToJsonString(controllerPojo));
878 } catch (final JsonProcessingException e) {
879 LOGGER.error(MessageCodes.ERROR_SCHEMA_INVALID + "Json Processing Error " + e);
883 private void removedRuleModifiedGroup(final String controllerName) {
884 // This will be sending Notification to PDPD directly to Lock
885 final ControllerPojo controllerPojo = new ControllerPojo();
886 controllerPojo.setName(controllerName);
887 controllerPojo.setOperation("lock");
888 final List<ControllerPojo> controllerPojos = new ArrayList<>();
889 controllerPojos.add(controllerPojo);
890 sendNotification(controllerPojos);
893 private void sendNotification(final List<ControllerPojo> controllers) {
894 final NotificationPojo notification = new NotificationPojo();
895 final String requestId = UUID.randomUUID().toString();
896 LOGGER.info("Generating notification RequestID : " + requestId);
897 notification.setRequestId(requestId);
898 notification.setEntity("controller");
899 notification.setControllers(controllers);
901 final String notificationJson = PolicyUtils.objectToJsonString(notification);
902 LOGGER.info("Sending Notification :\n" + notificationJson);
903 sendMessage(notificationJson);
904 } catch (final Exception e) {
905 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while sending notification to PDP-D "
906 + e.getMessage(), e);
910 private void sendMessage(final String message) throws IOException, GeneralSecurityException, InterruptedException {
912 if ("dmaap".equalsIgnoreCase(notificationType)) {
913 // Sending Message through DMaaP Message Router
914 LOGGER.debug("DMAAP Publishing Message");
916 publisher.send("MyPartitionKey", message);
918 LOGGER.debug("Message Published on DMaaP :" + dmaapList.get(0) + "for Topic: " + pubTopic);
920 Thread.sleep(dmaapDelay);
923 // Sending Message through UEB interface.
924 LOGGER.debug("UEB Publishing Message");
926 final CambriaBatchingPublisher pub = pubBuilder.build();
927 pub.send("MyPartitionKey", message);
929 final List<?> stuck = pub.close(uebDelay, TimeUnit.SECONDS);
930 if (!stuck.isEmpty()) {
931 LOGGER.error(stuck.size() + " messages unsent");
933 LOGGER.debug("Clean exit; Message Published on UEB : " + uebList + "for Topic: " + pubTopic);
939 private void createPom(final String name) {
940 final Model model = new Model();
941 model.setModelVersion("4.0.0");
942 model.setGroupId(getGroupId(name));
943 model.setArtifactId(getArtifactId(name));
944 model.setVersion(getVersion(name));
946 final DistributionManagement distributionManagement = new DistributionManagement();
947 final DeploymentRepository repository = new DeploymentRepository();
948 repository.setId(repId);
949 repository.setName(repName);
950 repository.setUrl(repUrlList.get(0));
951 distributionManagement.setRepository(repository);
952 model.setDistributionManagement(distributionManagement);
953 // Dependency Management goes here.
954 List<Dependency> dependencyList = new ArrayList<>();
955 if (groupMap.get(name).size() > 1) {
956 @SuppressWarnings("unchecked")
957 final ArrayList<PEDependency> dependencies = (ArrayList<PEDependency>) groupMap.get(name).get(1);
958 for (final PEDependency dependency : dependencies) {
959 dependencyList.add(dependency.getDependency());
962 // Add Default dependencies.
963 dependencyList = getDependencies(name);
965 model.setDependencies(dependencyList);
966 Writer writer = null;
968 writer = WriterFactory.newXmlWriter(
969 new File(PROJECTSLOCATION + File.separator + getArtifactId(name) + File.separator + POM_XML_FILE));
970 final MavenXpp3Writer pomWriter = new MavenXpp3Writer();
971 pomWriter.write(writer, model);
972 } catch (final Exception e) {
973 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while creating POM for " + getArtifactId(name)
974 + e.getMessage(), e);
976 IOUtil.close(writer);
980 private List<Dependency> getDependencies(final String controllerName) {
981 // Read the Dependency Information from property file.
982 final Path file = Paths.get(DEPENDENCY_FILE);
983 if (!Files.notExists(file)) {
985 final String dependencyJson = new String(Files.readAllBytes(file), StandardCharsets.UTF_8);
986 final DependencyInfo dependencyInfo =
987 PolicyUtils.jsonStringToObject(dependencyJson, DependencyInfo.class);
988 String controller = "default";
989 if (dependencyInfo.getDependencies().containsKey(controllerName)) {
990 controller = controllerName;
992 final List<Dependency> dependencyList = new ArrayList<>();
993 for (final PEDependency dependency : dependencyInfo.getDependencies().get(controller)) {
994 dependencyList.add(dependency.getDependency());
996 return dependencyList;
997 } catch (IOException | NullPointerException e) {
998 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
999 + "Error while getting dependecy Information for controller: " + controllerName
1000 + e.getMessage(), e);
1003 return defaultDependencies(controllerName);
1007 * Default Dependency Section. Can be changed as required.
1009 * @param controllerName the controller name
1010 * @return changed dependency list
1012 public List<Dependency> defaultDependencies(final String controllerName) {
1014 final List<Dependency> dependencyList = new ArrayList<>();
1015 final String version = StringEscapeUtils.escapeJava(brmsdependencyversion);
1017 final Dependency demoDependency = new Dependency();
1018 demoDependency.setGroupId(DROOLS_APPS_TEMPLATE_GROUP);
1019 demoDependency.setArtifactId("template.demo");
1020 demoDependency.setVersion(version);
1021 dependencyList.add(demoDependency);
1023 final Dependency controlloopDependency = new Dependency();
1024 controlloopDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1025 controlloopDependency.setArtifactId("events");
1026 controlloopDependency.setVersion(version);
1027 dependencyList.add(controlloopDependency);
1029 final Dependency restDependency = new Dependency();
1030 restDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1031 restDependency.setArtifactId("controlloop.common.model-impl.rest");
1032 restDependency.setVersion(version);
1033 dependencyList.add(restDependency);
1035 final Dependency appcDependency = new Dependency();
1036 appcDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1037 appcDependency.setArtifactId("controlloop.common.model-impl.appc");
1038 appcDependency.setVersion(version);
1039 dependencyList.add(appcDependency);
1041 final Dependency aaiDependency = new Dependency();
1042 aaiDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1043 aaiDependency.setArtifactId("controlloop.common.model-impl.aai");
1044 aaiDependency.setVersion(version);
1045 dependencyList.add(aaiDependency);
1047 final Dependency msoDependency = new Dependency();
1048 msoDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1049 msoDependency.setArtifactId("controlloop.common.model-impl.so");
1050 msoDependency.setVersion(version);
1051 dependencyList.add(msoDependency);
1053 final Dependency trafficgeneratorDependency = new Dependency();
1054 trafficgeneratorDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1055 trafficgeneratorDependency.setArtifactId("controlloop.common.model-impl.trafficgenerator");
1056 trafficgeneratorDependency.setVersion(version);
1057 dependencyList.add(trafficgeneratorDependency);
1058 return dependencyList;
1061 private void createProject(final String path, final String ksessionName) {
1062 new File(path + File.separator + RULES).mkdirs();
1063 new File(path + File.separator + META_INF).mkdirs();
1064 if (!Files.exists(Paths.get(path + File.separator + META_INF + File.separator + KMODULE_XML_FILE))) {
1065 // Hard coding XML for PDP Drools to accept our Rules.
1066 final String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "\n"
1067 + "<kmodule xmlns=\"http://jboss.org/kie/6.0.0/kmodule\">" + "\n"
1068 + "<kbase name=\"rules\" packages=\"rules\">" + "\n" + "<ksession name=\"" + ksessionName + "\"/>"
1069 + "\n" + "</kbase></kmodule>";
1070 copyDataToFile(path + File.separator + META_INF + File.separator + KMODULE_XML_FILE, xml);
1074 private void copyDataToFile(final String file, final String rule) {
1076 FileUtils.writeStringToFile(new File(file), rule);
1077 } catch (final Exception e) {
1079 XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while creating Rule for " + file + e.getMessage(),
1084 private void readGroups(final Properties config) throws PolicyException {
1085 String[] groupNames;
1086 final String groupNamesError = "groupNames property is missing or empty from the property file ";
1087 if (!config.containsKey(GROUP_NAMES) || config.getProperty(GROUP_NAMES) == null) {
1088 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + groupNamesError);
1090 if (config.getProperty(GROUP_NAMES).contains(",")) {
1091 groupNames = config.getProperty(GROUP_NAMES).replaceAll(" ", "").split(",");
1093 groupNames = new String[] {config.getProperty(GROUP_NAMES).replaceAll(" ", "")};
1095 if (groupNames == null || groupNames.length == 0) {
1096 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + groupNamesError);
1097 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + groupNamesError);
1099 groupMap = new HashMap<>();
1100 for (int counter = 0; counter < groupNames.length; counter++) {
1101 final String name = groupNames[counter];
1102 final String groupId = config.getProperty(name + ".groupID");
1103 if (groupId == null) {
1104 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1105 + ".groupID property is missing from the property file ");
1106 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1107 + ".groupID property is missing from the property file ");
1109 final String artifactId = config.getProperty(name + ".artifactID");
1110 if (artifactId == null) {
1111 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1112 + ".artifactID property is missing from the property file ");
1113 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1114 + ".artifactID property is missing from the property file ");
1116 final PEDependency dependency = new PEDependency();
1117 dependency.setArtifactId(artifactId);
1118 dependency.setGroupId(groupId);
1119 // Add to list if we got all
1120 addToGroup(name, dependency);
1124 private void addToGroup(final String name, final PEDependency dependency) {
1125 final EntityTransaction et = em.getTransaction();
1128 final TypedQuery<BrmsGroupInfo> query = em
1129 .createQuery("select b from BrmsGroupInfo as b where b.controllerName = :cn", BrmsGroupInfo.class);
1130 query.setParameter("cn", name);
1131 final List<BrmsGroupInfo> groupList = query.getResultList();
1132 BrmsGroupInfo brmsGroupInfo = null;
1133 if (!groupList.isEmpty()) {
1134 LOGGER.info("Controller name already Existing in DB. Will be updating the DB Values" + name);
1135 brmsGroupInfo = groupList.get(0);
1137 if (brmsGroupInfo == null) {
1138 brmsGroupInfo = new BrmsGroupInfo();
1140 brmsGroupInfo.setControllerName(name);
1141 brmsGroupInfo.setGroupId(dependency.getGroupId());
1142 brmsGroupInfo.setArtifactId(dependency.getArtifactId());
1143 brmsGroupInfo.setVersion(dependency.getVersion());
1144 em.persist(brmsGroupInfo);
1148 final ArrayList<Object> values = new ArrayList<>();
1149 values.add(dependency);
1150 groupMap.put(name, values);
1151 } catch (final Exception exception) {
1152 LOGGER.error("Unable add/update policy group to database for controller name: " + name, exception);
1158 private String getArtifactId(final String name) {
1159 return ((PEDependency) groupMap.get(name).get(0)).getArtifactId();
1162 private String getGroupId(final String name) {
1163 return ((PEDependency) groupMap.get(name).get(0)).getGroupId();
1166 private String getVersion(final String name) {
1167 return ((PEDependency) groupMap.get(name).get(0)).getVersion();
1170 private void getNameAndSetRemove(final String controllerName, final String policyName) {
1171 final String artifactName = getArtifactId(controllerName);
1172 final String ruleFolder = PROJECTSLOCATION + File.separator + artifactName + File.separator + "src"
1173 + File.separator + "main" + File.separator + RESOURCES + File.separator + RULES;
1174 final File file = new File(ruleFolder + File.separator + policyName + ".drl");
1175 if (file.delete()) {
1176 LOGGER.info("Deleted File.. " + file.getAbsolutePath());
1177 removePolicyFromGroup(policyName, controllerName);
1179 if (new File(ruleFolder).listFiles().length == 0) {
1180 removedRuleModifiedGroup(controllerName);
1182 // This is an update in terms of PDPD.
1183 addModifiedGroup(controllerName, "update");
1187 // Removes Policy from Memory and Database.
1188 private void removePolicyFromGroup(final String policyName, final String controllerName) {
1189 final EntityTransaction et = em.getTransaction();
1192 final TypedQuery<BrmsPolicyInfo> query =
1193 em.createQuery("select b from BrmsPolicyInfo as b where b.policyName = :pn", BrmsPolicyInfo.class);
1194 query.setParameter("pn", policyName);
1195 final List<BrmsPolicyInfo> pList = query.getResultList();
1196 BrmsPolicyInfo brmsPolicyInfo;
1197 if (!pList.isEmpty()) {
1199 brmsPolicyInfo = pList.get(0);
1200 if (brmsPolicyInfo.getControllerName().getControllerName().equals(controllerName)) {
1201 em.remove(brmsPolicyInfo);
1206 policyMap.remove(policyName);
1207 } catch (final Exception exception) {
1208 LOGGER.error("Unable remove policy from group to database for policy name: " + policyName, exception);
1214 private void setVersion(final String selectedName) {
1215 String newVersion = VERSION_0_1_0;
1217 final NexusArtifact artifact = getLatestArtifactFromNexus(selectedName);
1218 if (artifact != null) {
1219 newVersion = incrementVersion(artifact.getVersion());
1221 if (VERSION_0_1_0.equals(newVersion)) {
1224 setVersion(newVersion, selectedName);
1225 LOGGER.info("Controller: " + selectedName + "is on version: " + newVersion);
1228 private void setVersion(final String newVersion, final String controllerName) {
1229 final PEDependency userController = (PEDependency) groupMap.get(controllerName).get(0);
1230 userController.setVersion(newVersion);
1231 groupMap.get(controllerName).set(0, userController);
1234 // Return BackUpMonitor
1235 public static BackUpMonitor getBackUpMonitor() {
1242 public void rotateUrls() {
1243 if (repUrlList != null) {
1244 Collections.rotate(repUrlList, -1);
1249 * Get URL List Size.
1251 * @return URL list size
1253 public int urlListSize() {
1254 return repUrlList != null ? repUrlList.size() : 0;