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);
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()) {
791 flag = buildAndGenerateJarFile();
793 sendNotification(controllers);
802 * Removes a Rule from Rule Projects.
804 public void removeRule(final String name) {
805 final String controllerName = getGroupName(name);
806 if (controllerName == null) {
807 LOGGER.info("Error finding the controllerName for the given Policy: " + name);
810 syncProject(controllerName);
811 getNameAndSetRemove(controllerName, name);
814 private Boolean buildAndGenerateJarFile() throws PolicyException {
815 Boolean flag = false;
816 for (final Map.Entry<String, String> entry : modifiedGroups.entrySet()) {
817 InvocationResult result = null;
818 final String group = entry.getKey();
820 LOGGER.info("PushRules: ModifiedGroups, Key: " + group + ", Value: " + entry.getValue());
821 final InvocationRequest request = new DefaultInvocationRequest();
824 request.setPomFile(new File(
825 PROJECTSLOCATION + File.separator + getArtifactId(group) + File.separator + POM_XML_FILE));
826 request.setGoals(Arrays.asList(GOALS));
827 final Invoker invoker = new DefaultInvoker();
828 result = invoker.execute(request);
829 if (result.getExecutionException() != null) {
830 LOGGER.error(result.getExecutionException());
831 } else if (result.getExitCode() != 0) {
832 LOGGER.error("Maven Invocation failure..!");
834 } catch (final Exception e) {
835 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation issue for "
836 + getArtifactId(group) + e.getMessage(), e);
838 if (result != null && result.getExitCode() == 0) {
839 LOGGER.info("Build Completed..!");
841 addNotification(group, "create");
843 addNotification(group, entry.getValue());
847 throw new PolicyException(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation failure!");
853 private String getGroupName(final String name) {
854 if (policyMap.containsKey(name)) {
855 return policyMap.get(name);
858 return policyMap.containsKey(name) ? policyMap.get(name) : null;
862 private void addModifiedGroup(final String controllerName, final String operation) {
863 if (controllerName != null) {
864 modifiedGroups.put(controllerName, operation);
868 private void addNotification(final String controllerName, final String operation) {
869 final ControllerPojo controllerPojo = new ControllerPojo();
870 controllerPojo.setName(controllerName);
871 controllerPojo.setOperation(operation);
872 final HashMap<String, String> drools = new HashMap<>();
873 drools.put("groupId", getGroupId(controllerName));
874 drools.put("artifactId", getArtifactId(controllerName));
875 drools.put("version", getVersion(controllerName));
876 controllerPojo.setDrools(drools);
877 controllers.add(controllerPojo);
879 LOGGER.debug("Notification added: " + PolicyUtils.objectToJsonString(controllerPojo));
880 } catch (final JsonProcessingException e) {
881 LOGGER.error(MessageCodes.ERROR_SCHEMA_INVALID + "Json Processing Error " + e);
885 private void removedRuleModifiedGroup(final String controllerName) {
886 // This will be sending Notification to PDPD directly to Lock
887 final ControllerPojo controllerPojo = new ControllerPojo();
888 controllerPojo.setName(controllerName);
889 controllerPojo.setOperation("lock");
890 final List<ControllerPojo> controllerPojos = new ArrayList<>();
891 controllerPojos.add(controllerPojo);
892 sendNotification(controllerPojos);
895 private void sendNotification(final List<ControllerPojo> controllers) {
896 final NotificationPojo notification = new NotificationPojo();
897 final String requestId = UUID.randomUUID().toString();
898 LOGGER.info("Generating notification RequestID : " + requestId);
899 notification.setRequestId(requestId);
900 notification.setEntity("controller");
901 notification.setControllers(controllers);
903 final String notificationJson = PolicyUtils.objectToJsonString(notification);
904 LOGGER.info("Sending Notification :\n" + notificationJson);
905 sendMessage(notificationJson);
906 } catch (final Exception e) {
907 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while sending notification to PDP-D "
908 + e.getMessage(), e);
912 private void sendMessage(final String message) throws IOException, GeneralSecurityException, InterruptedException {
914 if ("dmaap".equalsIgnoreCase(notificationType)) {
915 // Sending Message through DMaaP Message Router
916 LOGGER.debug("DMAAP Publishing Message");
918 publisher.send("MyPartitionKey", message);
920 LOGGER.debug("Message Published on DMaaP :" + dmaapList.get(0) + "for Topic: " + pubTopic);
922 Thread.sleep(dmaapDelay);
925 // Sending Message through UEB interface.
926 LOGGER.debug("UEB Publishing Message");
928 final CambriaBatchingPublisher pub = pubBuilder.build();
929 pub.send("MyPartitionKey", message);
931 final List<?> stuck = pub.close(uebDelay, TimeUnit.SECONDS);
932 if (!stuck.isEmpty()) {
933 LOGGER.error(stuck.size() + " messages unsent");
935 LOGGER.debug("Clean exit; Message Published on UEB : " + uebList + "for Topic: " + pubTopic);
941 private void createPom(final String name) {
942 final Model model = new Model();
943 model.setModelVersion("4.0.0");
944 model.setGroupId(getGroupId(name));
945 model.setArtifactId(getArtifactId(name));
946 model.setVersion(getVersion(name));
948 final DistributionManagement distributionManagement = new DistributionManagement();
949 final DeploymentRepository repository = new DeploymentRepository();
950 repository.setId(repId);
951 repository.setName(repName);
952 repository.setUrl(repUrlList.get(0));
953 distributionManagement.setRepository(repository);
954 model.setDistributionManagement(distributionManagement);
955 // Dependency Management goes here.
956 List<Dependency> dependencyList = new ArrayList<>();
957 if (groupMap.get(name).size() > 1) {
958 @SuppressWarnings("unchecked")
959 final ArrayList<PEDependency> dependencies = (ArrayList<PEDependency>) groupMap.get(name).get(1);
960 for (final PEDependency dependency : dependencies) {
961 dependencyList.add(dependency.getDependency());
964 // Add Default dependencies.
965 dependencyList = getDependencies(name);
967 model.setDependencies(dependencyList);
968 Writer writer = null;
970 writer = WriterFactory.newXmlWriter(
971 new File(PROJECTSLOCATION + File.separator + getArtifactId(name) + File.separator + POM_XML_FILE));
972 final MavenXpp3Writer pomWriter = new MavenXpp3Writer();
973 pomWriter.write(writer, model);
974 } catch (final Exception e) {
975 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while creating POM for " + getArtifactId(name)
976 + e.getMessage(), e);
978 IOUtil.close(writer);
982 private List<Dependency> getDependencies(final String controllerName) {
983 // Read the Dependency Information from property file.
984 final Path file = Paths.get(DEPENDENCY_FILE);
985 if (!Files.notExists(file)) {
987 final String dependencyJson = new String(Files.readAllBytes(file), StandardCharsets.UTF_8);
988 final DependencyInfo dependencyInfo =
989 PolicyUtils.jsonStringToObject(dependencyJson, DependencyInfo.class);
990 String controller = "default";
991 if (dependencyInfo.getDependencies().containsKey(controllerName)) {
992 controller = controllerName;
994 final List<Dependency> dependencyList = new ArrayList<>();
995 for (final PEDependency dependency : dependencyInfo.getDependencies().get(controller)) {
996 dependencyList.add(dependency.getDependency());
998 return dependencyList;
999 } catch (IOException | NullPointerException e) {
1000 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
1001 + "Error while getting dependecy Information for controller: " + controllerName
1002 + e.getMessage(), e);
1005 return defaultDependencies(controllerName);
1009 * Default Dependency Section. Can be changed as required.
1011 * @param controllerName the controller name
1012 * @return changed dependency list
1014 public List<Dependency> defaultDependencies(final String controllerName) {
1016 final List<Dependency> dependencyList = new ArrayList<>();
1017 final String version = StringEscapeUtils.escapeJava(brmsdependencyversion);
1019 final Dependency demoDependency = new Dependency();
1020 demoDependency.setGroupId(DROOLS_APPS_TEMPLATE_GROUP);
1021 demoDependency.setArtifactId("template.demo");
1022 demoDependency.setVersion(version);
1023 dependencyList.add(demoDependency);
1025 final Dependency controlloopDependency = new Dependency();
1026 controlloopDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1027 controlloopDependency.setArtifactId("events");
1028 controlloopDependency.setVersion(version);
1029 dependencyList.add(controlloopDependency);
1031 final Dependency restDependency = new Dependency();
1032 restDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1033 restDependency.setArtifactId("controlloop.common.model-impl.rest");
1034 restDependency.setVersion(version);
1035 dependencyList.add(restDependency);
1037 final Dependency appcDependency = new Dependency();
1038 appcDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1039 appcDependency.setArtifactId("controlloop.common.model-impl.appc");
1040 appcDependency.setVersion(version);
1041 dependencyList.add(appcDependency);
1043 final Dependency aaiDependency = new Dependency();
1044 aaiDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1045 aaiDependency.setArtifactId("controlloop.common.model-impl.aai");
1046 aaiDependency.setVersion(version);
1047 dependencyList.add(aaiDependency);
1049 final Dependency msoDependency = new Dependency();
1050 msoDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1051 msoDependency.setArtifactId("controlloop.common.model-impl.so");
1052 msoDependency.setVersion(version);
1053 dependencyList.add(msoDependency);
1055 final Dependency trafficgeneratorDependency = new Dependency();
1056 trafficgeneratorDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1057 trafficgeneratorDependency.setArtifactId("controlloop.common.model-impl.trafficgenerator");
1058 trafficgeneratorDependency.setVersion(version);
1059 dependencyList.add(trafficgeneratorDependency);
1060 return dependencyList;
1063 private void createProject(final String path, final String ksessionName) {
1064 new File(path + File.separator + RULES).mkdirs();
1065 new File(path + File.separator + META_INF).mkdirs();
1066 if (!Files.exists(Paths.get(path + File.separator + META_INF + File.separator + KMODULE_XML_FILE))) {
1067 // Hard coding XML for PDP Drools to accept our Rules.
1068 final String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "\n"
1069 + "<kmodule xmlns=\"http://jboss.org/kie/6.0.0/kmodule\">" + "\n"
1070 + "<kbase name=\"rules\" packages=\"rules\">" + "\n" + "<ksession name=\"" + ksessionName + "\"/>"
1071 + "\n" + "</kbase></kmodule>";
1072 copyDataToFile(path + File.separator + META_INF + File.separator + KMODULE_XML_FILE, xml);
1076 private void copyDataToFile(final String file, final String rule) {
1078 FileUtils.writeStringToFile(new File(file), rule);
1079 } catch (final Exception e) {
1081 XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while creating Rule for " + file + e.getMessage(),
1086 private void readGroups(final Properties config) throws PolicyException {
1087 String[] groupNames;
1088 final String groupNamesError = "groupNames property is missing or empty from the property file ";
1089 if (!config.containsKey(GROUP_NAMES) || config.getProperty(GROUP_NAMES) == null) {
1090 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + groupNamesError);
1092 if (config.getProperty(GROUP_NAMES).contains(",")) {
1093 groupNames = config.getProperty(GROUP_NAMES).replaceAll(" ", "").split(",");
1095 groupNames = new String[] {config.getProperty(GROUP_NAMES).replaceAll(" ", "")};
1097 if (groupNames == null || groupNames.length == 0) {
1098 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + groupNamesError);
1099 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + groupNamesError);
1101 groupMap = new HashMap<>();
1102 for (int counter = 0; counter < groupNames.length; counter++) {
1103 final String name = groupNames[counter];
1104 final String groupId = config.getProperty(name + ".groupID");
1105 if (groupId == null) {
1106 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1107 + ".groupID property is missing from the property file ");
1108 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1109 + ".groupID property is missing from the property file ");
1111 final String artifactId = config.getProperty(name + ".artifactID");
1112 if (artifactId == null) {
1113 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1114 + ".artifactID property is missing from the property file ");
1115 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1116 + ".artifactID property is missing from the property file ");
1118 final PEDependency dependency = new PEDependency();
1119 dependency.setArtifactId(artifactId);
1120 dependency.setGroupId(groupId);
1121 // Add to list if we got all
1122 addToGroup(name, dependency);
1126 private void addToGroup(final String name, final PEDependency dependency) {
1127 final EntityTransaction et = em.getTransaction();
1130 final TypedQuery<BrmsGroupInfo> query = em
1131 .createQuery("select b from BrmsGroupInfo as b where b.controllerName = :cn", BrmsGroupInfo.class);
1132 query.setParameter("cn", name);
1133 final List<BrmsGroupInfo> groupList = query.getResultList();
1134 BrmsGroupInfo brmsGroupInfo = null;
1135 if (!groupList.isEmpty()) {
1136 LOGGER.info("Controller name already Existing in DB. Will be updating the DB Values" + name);
1137 brmsGroupInfo = groupList.get(0);
1139 if (brmsGroupInfo == null) {
1140 brmsGroupInfo = new BrmsGroupInfo();
1142 brmsGroupInfo.setControllerName(name);
1143 brmsGroupInfo.setGroupId(dependency.getGroupId());
1144 brmsGroupInfo.setArtifactId(dependency.getArtifactId());
1145 brmsGroupInfo.setVersion(dependency.getVersion());
1146 em.persist(brmsGroupInfo);
1150 final ArrayList<Object> values = new ArrayList<>();
1151 values.add(dependency);
1152 groupMap.put(name, values);
1153 } catch (final Exception exception) {
1154 LOGGER.error("Unable add/update policy group to database for controller name: " + name, exception);
1160 private String getArtifactId(final String name) {
1161 return ((PEDependency) groupMap.get(name).get(0)).getArtifactId();
1164 private String getGroupId(final String name) {
1165 return ((PEDependency) groupMap.get(name).get(0)).getGroupId();
1168 private String getVersion(final String name) {
1169 return ((PEDependency) groupMap.get(name).get(0)).getVersion();
1172 private void getNameAndSetRemove(final String controllerName, final String policyName) {
1173 final String artifactName = getArtifactId(controllerName);
1174 final String ruleFolder = PROJECTSLOCATION + File.separator + artifactName + File.separator + "src"
1175 + File.separator + "main" + File.separator + RESOURCES + File.separator + RULES;
1176 final File file = new File(ruleFolder + File.separator + policyName + ".drl");
1177 if (file.delete()) {
1178 LOGGER.info("Deleted File.. " + file.getAbsolutePath());
1179 removePolicyFromGroup(policyName, controllerName);
1181 if (new File(ruleFolder).listFiles().length == 0) {
1182 removedRuleModifiedGroup(controllerName);
1184 // This is an update in terms of PDPD.
1185 addModifiedGroup(controllerName, "update");
1189 // Removes Policy from Memory and Database.
1190 private void removePolicyFromGroup(final String policyName, final String controllerName) {
1191 final EntityTransaction et = em.getTransaction();
1194 final TypedQuery<BrmsPolicyInfo> query =
1195 em.createQuery("select b from BrmsPolicyInfo as b where b.policyName = :pn", BrmsPolicyInfo.class);
1196 query.setParameter("pn", policyName);
1197 final List<BrmsPolicyInfo> pList = query.getResultList();
1198 BrmsPolicyInfo brmsPolicyInfo;
1199 if (!pList.isEmpty()) {
1201 brmsPolicyInfo = pList.get(0);
1202 if (brmsPolicyInfo.getControllerName().getControllerName().equals(controllerName)) {
1203 em.remove(brmsPolicyInfo);
1208 policyMap.remove(policyName);
1209 } catch (final Exception exception) {
1210 LOGGER.error("Unable remove policy from group to database for policy name: " + policyName, exception);
1216 private void setVersion(final String selectedName) {
1217 String newVersion = VERSION_0_1_0;
1219 final NexusArtifact artifact = getLatestArtifactFromNexus(selectedName);
1220 if (artifact != null) {
1221 newVersion = incrementVersion(artifact.getVersion());
1223 if (VERSION_0_1_0.equals(newVersion)) {
1226 setVersion(newVersion, selectedName);
1227 LOGGER.info("Controller: " + selectedName + "is on version: " + newVersion);
1230 private void setVersion(final String newVersion, final String controllerName) {
1231 final PEDependency userController = (PEDependency) groupMap.get(controllerName).get(0);
1232 userController.setVersion(newVersion);
1233 groupMap.get(controllerName).set(0, userController);
1236 // Return BackUpMonitor
1237 public static BackUpMonitor getBackUpMonitor() {
1244 public void rotateUrls() {
1245 if (repUrlList != null) {
1246 Collections.rotate(repUrlList, -1);
1251 * Get URL List Size.
1253 * @return URL list size
1255 public int urlListSize() {
1256 return repUrlList != null ? repUrlList.size() : 0;