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;
77 import org.codehaus.plexus.util.WriterFactory;
78 import org.eclipse.persistence.config.PersistenceUnitProperties;
79 import org.onap.policy.api.PEDependency;
80 import org.onap.policy.api.PolicyException;
81 import org.onap.policy.brms.api.nexus.NexusRestSearchParameters;
82 import org.onap.policy.brms.api.nexus.NexusRestWrapper;
83 import org.onap.policy.brms.api.nexus.NexusRestWrapperException;
84 import org.onap.policy.brms.api.nexus.pojo.NexusArtifact;
85 import org.onap.policy.brms.entity.BrmsGroupInfo;
86 import org.onap.policy.brms.entity.BrmsPolicyInfo;
87 import org.onap.policy.brms.entity.DependencyInfo;
88 import org.onap.policy.common.im.IntegrityMonitor;
89 import org.onap.policy.common.logging.eelf.MessageCodes;
90 import org.onap.policy.common.logging.eelf.PolicyLogger;
91 import org.onap.policy.common.logging.flexlogger.FlexLogger;
92 import org.onap.policy.common.logging.flexlogger.Logger;
93 import org.onap.policy.utils.BackUpHandler;
94 import org.onap.policy.utils.BackUpMonitor;
95 import org.onap.policy.utils.BusPublisher;
96 import org.onap.policy.utils.PolicyUtils;
97 import org.onap.policy.xacml.api.XACMLErrorConstants;
100 * BRMSPush: Application responsible to push policies to the BRMS PDP Policy Repository (PR). Mavenize and push policy
106 public class BrmsPush {
107 private static final String GROUP_NAMES = "groupNames";
108 private static final String DROOLS_APPS_TEMPLATE_GROUP =
109 "org.onap.policy.drools-applications.controlloop.templates";
110 private static final String DROOLS_APPS_MODEL_GROUP =
111 "org.onap.policy.drools-applications.controlloop.common.model-impl";
112 private static final String META_INF = "META-INF";
113 private static final String KMODULE_XML_FILE = "kmodule.xml";
114 private static final String POM_XML_FILE = "pom.xml";
115 private static final String VERSION_0_1_0 = "0.1.0";
116 private static final String RULES = "rules";
117 private static final String RESOURCES = "resources";
118 private static final Logger LOGGER = FlexLogger.getLogger(BrmsPush.class.getName());
119 private static final String PROJECTSLOCATION = "RuleProjects";
120 private static final String[] GOALS = { "clean", "deploy" };
121 private static final String DEFAULT_VERSION = "1.4.0-SNAPSHOT";
122 private static final String DEPENDENCY_FILE = "dependency.json";
123 private static final String BRMSPERSISTENCE = "brmsEclipselink.persistencexml";
125 private static Map<String, String> modifiedGroups = new HashMap<>();
126 private static IntegrityMonitor im;
127 private static BackUpMonitor bm;
128 private String defaultName = null;
129 private String repId = null;
130 private String repName = null;
131 private List<String> repUrlList = null;
132 private String repUserName = null;
133 private String repPassword = null;
134 private String policyKeyId = null;
135 private boolean createFlag = false;
136 private String uebList = null;
137 private List<String> dmaapList = null;
138 private String pubTopic = null;
139 private PublisherBuilder pubBuilder = null;
140 protected BusPublisher publisher = null;
141 private Long uebDelay = Long.parseLong("20");
142 private Long dmaapDelay = Long.parseLong("5000");
143 private String notificationType = null;
144 private List<ControllerPojo> controllers;
145 private Map<String, ArrayList<Object>> groupMap = new HashMap<>();
146 private final Map<String, String> policyMap = new HashMap<>();
147 private String brmsdependencyversion;
148 private EntityManager em;
149 private boolean syncFlag = false;
152 * Responsible to push policies to the BRMS PDP Policy Repository (PR).
154 * @param propertiesFile the properties file
155 * @param handler the {@link BackUpHandler}
156 * @throws PolicyException PolicyException related to the operation
158 public BrmsPush(final String propertiesFile, final BackUpHandler handler) throws PolicyException {
159 if (propertiesFile == null || handler == null) {
160 throw new PolicyException("Error no propertiesFile or handler");
162 final Properties config = new Properties();
163 final Path file = Paths.get(propertiesFile);
164 if (Files.notExists(file)) {
165 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Config File doesn't Exist in the specified Path "
167 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
168 + "Config File doesn't Exist in the specified Path " + file.toString());
170 if (file.toString().endsWith(".properties")) {
171 // Grab the Properties.
172 setProperty(file, config, handler);
177 private void setProperty(final Path file, final Properties config, final BackUpHandler handler)
178 throws PolicyException {
181 in = new FileInputStream(file.toFile());
183 } catch (final IOException e) {
185 XACMLErrorConstants.ERROR_DATA_ISSUE + "Data/File Read Error while reading from the property file.",
187 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
188 + "Data/File Read Error while reading from the property file.");
190 LOGGER.info("Trying to set up IntegrityMonitor");
191 String resourceName = null;
193 LOGGER.info("Trying to set up IntegrityMonitor");
194 resourceName = config.getProperty("RESOURCE_NAME");
195 if (resourceName == null) {
196 LOGGER.warn("RESOURCE_NAME is missing setting default value. ");
197 resourceName = "brmsgw_pdp01";
199 resourceName = resourceName.trim();
200 setIntegrityMonitor(IntegrityMonitor.getInstance(resourceName, config));
201 } catch (final Exception e) {
202 LOGGER.error("Error starting Integerity Monitor: " + e);
204 LOGGER.info("Trying to set up BackUpMonitor");
206 setBackupMonitor(BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), resourceName, config,
208 } catch (final Exception e) {
209 LOGGER.error("Error starting BackUpMonitor: " + e);
211 if (!config.containsKey(BRMSPERSISTENCE)) {
212 config.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, "META-INF/persistenceBRMS.xml");
214 config.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML,
215 config.getProperty(BRMSPERSISTENCE, "META-INF/persistenceBRMS.xml"));
217 final EntityManagerFactory emf = Persistence.createEntityManagerFactory("BRMSGW", config);
218 em = emf.createEntityManager();
219 defaultName = config.getProperty("defaultName");
220 if (defaultName == null) {
222 XACMLErrorConstants.ERROR_DATA_ISSUE + "defaultName property is missing from the property file ");
223 throw new PolicyException(
224 XACMLErrorConstants.ERROR_DATA_ISSUE + "defaultName property is missing from the property file");
226 defaultName = defaultName.trim();
227 repId = config.getProperty("repositoryID");
230 XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryID property is missing from the property file ");
231 throw new PolicyException(
232 XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryID property is missing from the property file ");
234 repId = repId.trim();
235 repName = config.getProperty("repositoryName");
236 if (repName == null) {
237 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
238 + "repositoryName property is missing from the property file ");
239 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
240 + "repositoryName property is missing from the property file ");
242 repName = repName.trim();
243 final String repUrl = config.getProperty("repositoryURL");
244 if (repUrl == null) {
246 XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryURL property is missing from the property file ");
247 throw new PolicyException(
248 XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryURL property is missing from the property file ");
250 if (repUrl.contains(",")) {
251 repUrlList = new ArrayList<>(Arrays.asList(repUrl.trim().split(",")));
253 repUrlList = new ArrayList<>();
254 repUrlList.add(repUrl);
256 repUserName = config.getProperty("repositoryUsername");
257 repPassword = config.getProperty("repositoryPassword");
258 if (repUserName == null || repPassword == null) {
259 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
260 + "repostoryUserName and respositoryPassword properties are required.");
261 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
262 + "repostoryUserName and respositoryPassword properties are required.");
264 repUserName = repUserName.trim();
265 repPassword = repPassword.trim();
266 policyKeyId = config.getProperty("policyKeyID");
267 if (policyKeyId == null) {
269 XACMLErrorConstants.ERROR_DATA_ISSUE + "policyKeyID property is missing from the property file ");
270 throw new PolicyException(
271 XACMLErrorConstants.ERROR_DATA_ISSUE + "policyKeyID property is missing from the property file ");
273 policyKeyId = policyKeyId.trim();
274 final String syncF = config.getProperty("sync", "false").trim();
275 syncFlag = Boolean.parseBoolean(syncF);
277 PolicyLogger.info("SYNC Flag is turned ON. DB will be given Priority.");
279 brmsdependencyversion = config.getProperty("brms.dependency.version");
280 if (brmsdependencyversion == null) {
281 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
282 + "brmsdependencyversion property is missing from the property file, Using default Version.");
283 brmsdependencyversion = DEFAULT_VERSION;
285 brmsdependencyversion = brmsdependencyversion.trim();
289 notificationType = config.getProperty("NOTIFICATION_TYPE");
290 if ("dmaap".equalsIgnoreCase(notificationType)) {
292 LOGGER.info("Notification Type being used is DMaaP... creating instance of BusPublisher.");
293 // Setting up the Publisher for DMaaP MR
294 String dmaapServers = config.getProperty("NOTIFICATION_SERVERS");
295 pubTopic = config.getProperty("NOTIFICATION_TOPIC");
296 final String aafLogin = config.getProperty("CLIENT_ID").trim();
297 final String aafPassword = config.getProperty("CLIENT_KEY").trim();
299 if (dmaapServers == null || pubTopic == null) {
301 XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file ");
302 throw new PolicyException(
303 XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file ");
306 dmaapServers = dmaapServers.trim();
307 pubTopic = pubTopic.trim();
309 if (dmaapServers.contains(",")) {
310 dmaapList = new ArrayList<>(Arrays.asList(dmaapServers.split("\\s*,\\s*")));
312 dmaapList = new ArrayList<>();
313 dmaapList.add(dmaapServers);
317 new BusPublisher.DmaapPublisherWrapper(this.dmaapList, this.pubTopic, aafLogin, aafPassword);
319 String notificationDelay = config.getProperty("NOTIFICATION_DELAY");
320 if (notificationDelay != null && !notificationDelay.isEmpty()) {
321 notificationDelay = notificationDelay.trim();
323 dmaapDelay = Long.parseLong(notificationDelay);
324 } catch (final NumberFormatException e) {
325 LOGGER.error("DMAAP_DELAY not a long format number" + e);
328 LOGGER.info("DMAAP BusPublisher is created.");
331 LOGGER.info("Notification Type being used is UEB... creating instance of PublisherBuilder.");
332 // Setting up the Publisher for UEB
333 uebList = config.getProperty("NOTIFICATION_SERVERS");
334 pubTopic = config.getProperty("NOTIFICATION_TOPIC");
335 if (uebList == null || pubTopic == null) {
337 XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file ");
338 throw new PolicyException(
339 XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file ");
341 uebList = uebList.trim();
342 pubTopic = pubTopic.trim();
343 pubBuilder = new CambriaClientBuilders.PublisherBuilder();
344 pubBuilder.usingHosts(uebList).onTopic(pubTopic).usingHttps(true);
345 String apiKey = config.getProperty("UEB_API_KEY");
346 String apiSecret = config.getProperty("UEB_API_SECRET");
347 if (apiKey != null && !apiKey.isEmpty() && apiSecret != null && !apiSecret.isEmpty()) {
348 apiKey = apiKey.trim();
349 apiSecret = apiSecret.trim();
350 pubBuilder.authenticatedBy(apiKey, apiSecret);
352 String notificationDelay = config.getProperty("NOTIFICATION_DELAY");
353 if (notificationDelay != null && !notificationDelay.isEmpty()) {
354 notificationDelay = notificationDelay.trim();
356 uebDelay = Long.parseLong(notificationDelay);
357 } catch (final NumberFormatException e) {
358 LOGGER.error("UEB_DELAY not a long format number" + e);
361 LOGGER.info("UEB PublisherBuilder is created.");
367 private static void setBackupMonitor(final BackUpMonitor instance) {
371 private static void setIntegrityMonitor(final IntegrityMonitor instance) {
376 * Will Initialize the variables required for BRMSPush.
378 public void initiate(final boolean flag) {
379 resetModifiedGroups();
380 controllers = new ArrayList<>();
382 bm.updateNotification();
383 } catch (final Exception e) {
384 LOGGER.error("Error while updating Notification: " + e.getMessage(), e);
391 public void resetDs() {
392 resetModifiedGroups();
393 controllers = new ArrayList<>();
396 private static void resetModifiedGroups() {
397 modifiedGroups = new HashMap<>();
401 * Will Add rules to projects. Creates necessary folders if required.
403 public void addRule(final String name, final String rule, final Map<String, String> responseAttributes) {
404 // 1 check the response Attributes and determine if this belongs to any projects.
405 // 2 if not create folder
408 // 5 store the groups that have been updated.
409 String ksessionName = null;
410 String selectedName = null;
411 if (!responseAttributes.isEmpty()) {
412 // Pick selected Value
413 String userControllerName = null;
414 final ArrayList<PEDependency> userDependencies = new ArrayList<>();
415 for (final Map.Entry<String, String> entry : responseAttributes.entrySet()) {
416 final String key = entry.getKey();
417 final String value = entry.getValue();
418 if (key.equals(policyKeyId)) {
419 selectedName = value;
421 // kmodule configurations
422 else if ("kSessionName".equals(key)) {
423 ksessionName = value;
425 // Check User Specific values.
426 if ("$controller:".equals(key)) {
427 userControllerName = getUserControllerName(key, value);
428 } else if ("$dependency$".equals(key) && value.startsWith("[") && value.endsWith("]")) {
429 updateUserDependencies(userDependencies, value);
432 if (userControllerName != null) {
433 // Adding custom dependencies here.
434 final ArrayList<Object> values = groupMap.get(userControllerName);
435 values.add(userDependencies);
436 groupMap.put(userControllerName, values);
437 selectedName = userControllerName;
440 // If no Match then pick Default.
441 if (selectedName == null) {
442 selectedName = defaultName;
444 if (groupMap.containsKey(selectedName)) {
445 // If the key is not got as parameters set by the user, setting the default value for
448 if (ksessionName == null) {
449 LOGGER.info("kSessionName is null, selectedName is : " + selectedName);
450 if (selectedName.equalsIgnoreCase(defaultName)) {
451 ksessionName = "closedloop";
453 ksessionName = "closedloop-" + selectedName;
456 // create directories if missing.
457 manageProject(selectedName, ksessionName, name, rule);
459 // Will check for Create Later after generating the Pom.
460 addModifiedGroup(selectedName, "update");
464 private String getUserControllerName(final String key, final String value) {
465 String userControllerName = null;
466 // Check User Specific values.
468 final PEDependency dependency = PolicyUtils.jsonStringToObject(value, PEDependency.class);
469 userControllerName = key.replaceFirst("$controller:", "");
470 LOGGER.info("addRule: userControllerName - " + userControllerName + ", dependency: - " + dependency);
471 addToGroup(userControllerName, dependency);
472 } catch (final Exception e) {
473 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while resolving Controller: " + e);
475 return userControllerName;
478 private void updateUserDependencies(final ArrayList<PEDependency> userDependencies, String value) {
479 // update the user dependencies supplied as parameter to this method
480 value = value.substring(1, value.length() - 1).trim();
481 final List<String> dependencyStrings = Arrays.asList(value.split(Pattern.quote("},{")));
482 for (final String dependencyString : dependencyStrings) {
484 userDependencies.add(PolicyUtils.jsonStringToObject(dependencyString, PEDependency.class));
485 } catch (final Exception e) {
486 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while resolving Dependencies: " + e);
491 private void syncGroupInfo() {
492 // Sync DB to JMemory.
493 final EntityTransaction et = em.getTransaction();
496 final TypedQuery<BrmsGroupInfo> groupInfoQuery =
497 em.createQuery("select b from BrmsGroupInfo AS b", BrmsGroupInfo.class);
498 final List<BrmsGroupInfo> groupInfoResult = groupInfoQuery.getResultList();
499 if (groupInfoResult.size() != groupMap.size()) {
500 for (final BrmsGroupInfo brmsGroupInfo : groupInfoResult) {
501 final PEDependency dependency = new PEDependency();
502 dependency.setArtifactId(brmsGroupInfo.getArtifactId());
503 dependency.setGroupId(brmsGroupInfo.getGroupId());
504 dependency.setVersion(brmsGroupInfo.getVersion());
505 final ArrayList<Object> values = new ArrayList<>();
506 values.add(dependency);
507 groupMap.put(brmsGroupInfo.getControllerName(), values);
511 final TypedQuery<BrmsPolicyInfo> policyInfoQuery =
512 em.createQuery("select g from BrmsPolicyInfo AS g", BrmsPolicyInfo.class);
513 final List<BrmsPolicyInfo> policyInfoResult = policyInfoQuery.getResultList();
514 if (policyInfoResult.size() != policyMap.size()) {
515 for (final BrmsPolicyInfo brmsPolicyInfo : policyInfoResult) {
516 policyMap.put(brmsPolicyInfo.getPolicyName(),
517 brmsPolicyInfo.getControllerName().getControllerName());
521 LOGGER.info("Updated Local Memory values with values from database.");
522 } catch (final Exception exception) {
523 LOGGER.error("Unable to sync group info", exception);
529 private void manageProject(final String selectedName, final String ksessionName, final String name,
531 // Check if the Project is in Sync. If not get the latest Version.
532 syncProject(selectedName);
533 createProject(PROJECTSLOCATION + File.separator + getArtifactId(selectedName) + File.separator + "src"
534 + File.separator + "main" + File.separator + RESOURCES, ksessionName);
535 copyDataToFile(PROJECTSLOCATION + File.separator + getArtifactId(selectedName) + File.separator + "src"
536 + File.separator + "main" + File.separator + RESOURCES + File.separator + RULES + File.separator + name
538 addToPolicy(name, selectedName);
542 * Add Policy to JMemory and DataBase.
544 private void addToPolicy(final String policyName, final String controllerName) {
546 final EntityTransaction et = em.getTransaction();
549 boolean create = false;
550 final TypedQuery<BrmsPolicyInfo> policyInfoQuery =
551 em.createQuery("select b from BrmsPolicyInfo as b where b.policyName = :pn", BrmsPolicyInfo.class);
552 policyInfoQuery.setParameter("pn", policyName);
553 final List<BrmsPolicyInfo> policyInfoResultList = policyInfoQuery.getResultList();
554 BrmsPolicyInfo brmsPolicyInfo = new BrmsPolicyInfo();
555 if (!policyInfoResultList.isEmpty()) {
557 brmsPolicyInfo = policyInfoResultList.get(0);
558 if (!brmsPolicyInfo.getControllerName().getControllerName().equals(controllerName)) {
565 final TypedQuery<BrmsGroupInfo> groupInfoQuery = em.createQuery(
566 "select b from BrmsGroupInfo as b where b.controllerName = :cn", BrmsGroupInfo.class);
567 groupInfoQuery.setParameter("cn", controllerName);
568 final List<BrmsGroupInfo> groupInfoResultList = groupInfoQuery.getResultList();
569 BrmsGroupInfo brmsGroupInfo = new BrmsGroupInfo();
570 if (!groupInfoResultList.isEmpty()) {
571 brmsGroupInfo = groupInfoResultList.get(0);
573 brmsPolicyInfo.setPolicyName(policyName);
574 brmsPolicyInfo.setControllerName(brmsGroupInfo);
575 em.persist(brmsPolicyInfo);
580 policyMap.put(policyName, controllerName);
581 } catch (final Exception exception) {
582 LOGGER.error("Unable add policy to database", exception);
588 private void syncProject(final String selectedName) {
589 final boolean projectExists = checkProject(selectedName);
592 version = getVersion(selectedName);
593 if (version == null) {
594 LOGGER.error("Error getting local version for the given Controller Name:" + selectedName
595 + " going with Default value");
596 version = VERSION_0_1_0;
598 final String nextVersion = incrementVersion(version);
599 final boolean outOfSync = checkRemoteSync(selectedName, nextVersion);
604 // We are out of Sync or Project is not Present.
605 downloadProject(selectedName);
608 private void downloadProject(final String selectedName) {
609 final NexusArtifact artifact = getLatestArtifactFromNexus(selectedName);
610 if (artifact == null) {
613 final String dirName = getDirectoryName(selectedName);
615 final String fileName = "rule.jar";
617 website = new URL(artifact.getUrlPath() + ".jar");
618 try (ReadableByteChannel rbc = Channels.newChannel(website.openStream());
619 FileOutputStream fos = new FileOutputStream(fileName)) {
620 fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
621 extractJar(fileName, dirName);
622 new File(fileName).delete();
623 } catch (final IOException e) {
624 LOGGER.error("Error while downloading the project to File System. " + e.getMessage(), e);
627 } catch (final IOException e1) {
628 LOGGER.error("Error while retrieve the artifact. " + e1.getMessage(), e1);
632 private void extractJar(final String jarFileName, final String artifactId) {
633 try (JarFile jar = new JarFile(jarFileName)) {
634 final Enumeration<?> enumEntries = jar.entries();
635 while (enumEntries.hasMoreElements()) {
636 parseJarContents(artifactId, jar, enumEntries);
638 } catch (final IOException e) {
639 LOGGER.info("exception Occured" + e);
643 private void parseJarContents(final String artifactId, final JarFile jar, final Enumeration<?> enumEntries) {
644 final JarEntry jarEntry = (JarEntry) enumEntries.nextElement();
646 final String fileName = jarEntry.getName().substring(jarEntry.getName().lastIndexOf("/") + 1);
647 if (jarEntry.getName().endsWith(".drl")) {
648 final String path = PROJECTSLOCATION + File.separator + artifactId + File.separator + "src" + File.separator
649 + "main" + File.separator + RESOURCES + File.separator + RULES;
650 new File(path).mkdirs();
651 if (syncFlag && policyMap.containsKey(fileName.replace(".drl", ""))) {
652 file = new File(path + File.separator + fileName);
654 file = new File(path + File.separator + fileName);
656 } else if (jarEntry.getName().endsWith(POM_XML_FILE)) {
657 final String path = PROJECTSLOCATION + File.separator + artifactId;
658 new File(path).mkdirs();
659 file = new File(path + File.separator + fileName);
660 } else if (jarEntry.getName().endsWith(KMODULE_XML_FILE)) {
661 final String path = PROJECTSLOCATION + File.separator + artifactId + File.separator + "src" + File.separator
662 + "main" + File.separator + RESOURCES + File.separator + META_INF;
663 new File(path).mkdirs();
664 file = new File(path + File.separator + fileName);
667 try (InputStream is = jar.getInputStream(jarEntry); FileOutputStream fos = new FileOutputStream(file)) {
668 while (is.available() > 0) {
669 fos.write(is.read());
671 LOGGER.info(fileName + " Created..");
672 } catch (final IOException e) {
673 LOGGER.info("exception Occured" + e);
678 private NexusArtifact getLatestArtifactFromNexus(final String selectedName) {
679 final List<NexusArtifact> artifacts = getArtifactFromNexus(selectedName, null);
682 NexusArtifact result = null;
683 for (final NexusArtifact artifact : artifacts) {
685 Integer.parseInt(artifact.getVersion().substring(0, artifact.getVersion().indexOf(".")));
686 final int minorVal = Integer.parseInt(artifact.getVersion()
687 .substring(artifact.getVersion().indexOf(".") + 1, artifact.getVersion().lastIndexOf(".")));
688 if (majorVal > bigNum) {
692 if ((bigNum == majorVal) && (minorVal > smallNum)) {
695 if (bigNum == majorVal && minorVal == smallNum) {
699 return additionalNexusLatestCheck(selectedName, result);
702 // Additional Check due to Limitations from Nexus API to check if the artifact is the latest.
703 private NexusArtifact additionalNexusLatestCheck(final String selectedName, final NexusArtifact result) {
704 if (result == null) {
707 final String nextVersion = incrementVersion(result.getVersion());
708 final List<NexusArtifact> artifact = getArtifactFromNexus(selectedName, nextVersion);
709 return artifact.isEmpty() ? result : additionalNexusLatestCheck(selectedName, artifact.get(0));
712 private boolean checkRemoteSync(final String selectedName, final String version) {
713 final List<NexusArtifact> artifacts = getArtifactFromNexus(selectedName, version);
714 return artifacts.isEmpty() ? false : true;
717 private List<NexusArtifact> getArtifactFromNexus(final String selectedName, final String version) {
718 NexusRestWrapper restWrapper = null;
720 boolean flag = false;
721 while (index < repUrlList.size()) {
723 final String repUrl = repUrlList.get(0);
725 new NexusRestWrapper(repUrl.substring(0, repUrl.indexOf(repUrl.split(":[0-9]+\\/nexus")[1])),
726 repUserName, repPassword);
727 final NexusRestSearchParameters searchParameters = new NexusRestSearchParameters();
728 searchParameters.useFilterSearch(getGroupId(selectedName), getArtifactId(selectedName), version, null,
731 final List<NexusArtifact> resultList = restWrapper.findArtifact(searchParameters).getArtifactList();
732 if (resultList != null) {
736 } catch (NexusRestWrapperException | ProcessingException e) {
737 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Connection to remote Nexus has failed. "
738 + e.getMessage(), e);
740 if (null != restWrapper) {
744 Collections.rotate(repUrlList, -1);
749 return new ArrayList<>();
752 private String incrementVersion(final String version) {
753 int majorVal = Integer.parseInt(version.substring(0, version.indexOf(".")));
754 int minorVal = Integer.parseInt(version.substring(version.indexOf(".") + 1, version.lastIndexOf(".")));
761 return majorVal + "." + minorVal + version.substring(version.lastIndexOf("."));
764 private boolean checkProject(final String selectedName) {
765 return new File(PROJECTSLOCATION + File.separator + getDirectoryName(selectedName)).exists();
768 private String getDirectoryName(final String selectedName) {
769 return getArtifactId(selectedName);
773 * Will Push policies to the PolicyRepo.
775 * @throws PolicyException PolicyException related to the operation
777 public void pushRules() throws PolicyException {
778 // Check how many groups have been updated.
779 // Invoke their Maven process.
781 im.startTransaction();
782 } catch (final Exception e) {
783 LOGGER.error("Error while starting Transaction " + e);
785 if (!modifiedGroups.isEmpty()) {
786 if (buildAndGenerateJarFile()) {
787 sendNotification(controllers);
796 * Removes a Rule from Rule Projects.
798 public void removeRule(final String name) {
799 final String controllerName = getGroupName(name);
800 if (controllerName == null) {
801 LOGGER.info("Error finding the controllerName for the given Policy: " + name);
804 syncProject(controllerName);
805 getNameAndSetRemove(controllerName, name);
808 private Boolean buildAndGenerateJarFile() throws PolicyException {
809 Boolean flag = false;
810 for (final Map.Entry<String, String> entry : modifiedGroups.entrySet()) {
811 InvocationResult result = null;
812 final String group = entry.getKey();
814 LOGGER.info("PushRules: ModifiedGroups, Key: " + group + ", Value: " + entry.getValue());
815 final InvocationRequest request = new DefaultInvocationRequest();
818 request.setPomFile(new File(
819 PROJECTSLOCATION + File.separator + getArtifactId(group) + File.separator + POM_XML_FILE));
820 request.setGoals(Arrays.asList(GOALS));
821 final Invoker invoker = new DefaultInvoker();
822 result = invoker.execute(request);
823 if (result.getExecutionException() != null) {
824 LOGGER.error(result.getExecutionException());
825 } else if (result.getExitCode() != 0) {
826 LOGGER.error("Maven Invocation failure..!");
828 } catch (final Exception e) {
829 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation issue for "
830 + getArtifactId(group) + e.getMessage(), e);
832 if (result != null && result.getExitCode() == 0) {
833 LOGGER.info("Build Completed..!");
835 addNotification(group, "create");
837 addNotification(group, entry.getValue());
841 throw new PolicyException(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation failure!");
847 private String getGroupName(final String name) {
848 if (policyMap.containsKey(name)) {
849 return policyMap.get(name);
852 return policyMap.containsKey(name) ? policyMap.get(name) : null;
856 private void addModifiedGroup(final String controllerName, final String operation) {
857 if (controllerName != null) {
858 modifiedGroups.put(controllerName, operation);
862 private void addNotification(final String controllerName, final String operation) {
863 final ControllerPojo controllerPojo = new ControllerPojo();
864 controllerPojo.setName(controllerName);
865 controllerPojo.setOperation(operation);
866 final HashMap<String, String> drools = new HashMap<>();
867 drools.put("groupId", getGroupId(controllerName));
868 drools.put("artifactId", getArtifactId(controllerName));
869 drools.put("version", getVersion(controllerName));
870 controllerPojo.setDrools(drools);
871 controllers.add(controllerPojo);
873 LOGGER.debug("Notification added: " + PolicyUtils.objectToJsonString(controllerPojo));
874 } catch (final JsonProcessingException e) {
875 LOGGER.error(MessageCodes.ERROR_SCHEMA_INVALID + "Json Processing Error " + e);
879 private void removedRuleModifiedGroup(final String controllerName) {
880 // This will be sending Notification to PDPD directly to Lock
881 final ControllerPojo controllerPojo = new ControllerPojo();
882 controllerPojo.setName(controllerName);
883 controllerPojo.setOperation("lock");
884 final List<ControllerPojo> controllerPojos = new ArrayList<>();
885 controllerPojos.add(controllerPojo);
886 sendNotification(controllerPojos);
889 private void sendNotification(final List<ControllerPojo> controllers) {
890 final NotificationPojo notification = new NotificationPojo();
891 final String requestId = UUID.randomUUID().toString();
892 LOGGER.info("Generating notification RequestID : " + requestId);
893 notification.setRequestId(requestId);
894 notification.setEntity("controller");
895 notification.setControllers(controllers);
897 final String notificationJson = PolicyUtils.objectToJsonString(notification);
898 LOGGER.info("Sending Notification :\n" + notificationJson);
899 sendMessage(notificationJson);
900 } catch (final Exception e) {
901 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while sending notification to PDP-D "
902 + e.getMessage(), e);
906 private void sendMessage(final String message) throws IOException, GeneralSecurityException, InterruptedException {
908 if ("dmaap".equalsIgnoreCase(notificationType)) {
909 // Sending Message through DMaaP Message Router
910 LOGGER.debug("DMAAP Publishing Message");
912 publisher.send("MyPartitionKey", message);
914 LOGGER.debug("Message Published on DMaaP :" + dmaapList.get(0) + "for Topic: " + pubTopic);
916 Thread.sleep(dmaapDelay);
919 // Sending Message through UEB interface.
920 LOGGER.debug("UEB Publishing Message");
922 final CambriaBatchingPublisher pub = pubBuilder.build();
923 pub.send("MyPartitionKey", message);
925 final List<?> stuck = pub.close(uebDelay, TimeUnit.SECONDS);
926 if (!stuck.isEmpty()) {
927 LOGGER.error(stuck.size() + " messages unsent");
929 LOGGER.debug("Clean exit; Message Published on UEB : " + uebList + "for Topic: " + pubTopic);
935 private void createPom(final String name) {
936 final Model model = new Model();
937 model.setModelVersion("4.0.0");
938 model.setGroupId(getGroupId(name));
939 model.setArtifactId(getArtifactId(name));
940 model.setVersion(getVersion(name));
942 final DistributionManagement distributionManagement = new DistributionManagement();
943 final DeploymentRepository repository = new DeploymentRepository();
944 repository.setId(repId);
945 repository.setName(repName);
946 repository.setUrl(repUrlList.get(0));
947 distributionManagement.setRepository(repository);
948 model.setDistributionManagement(distributionManagement);
949 // Dependency Management goes here.
950 List<Dependency> dependencyList = new ArrayList<>();
951 if (groupMap.get(name).size() > 1) {
952 @SuppressWarnings("unchecked")
953 final ArrayList<PEDependency> dependencies = (ArrayList<PEDependency>) groupMap.get(name).get(1);
954 for (final PEDependency dependency : dependencies) {
955 dependencyList.add(dependency.getDependency());
958 // Add Default dependencies.
959 dependencyList = getDependencies(name);
961 model.setDependencies(dependencyList);
962 Writer writer = null;
964 writer = WriterFactory.newXmlWriter(
965 new File(PROJECTSLOCATION + File.separator + getArtifactId(name) + File.separator + POM_XML_FILE));
966 final MavenXpp3Writer pomWriter = new MavenXpp3Writer();
967 pomWriter.write(writer, model);
968 } catch (final Exception e) {
969 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while creating POM for " + getArtifactId(name)
970 + e.getMessage(), e);
972 IOUtil.close(writer);
976 private List<Dependency> getDependencies(final String controllerName) {
977 // Read the Dependency Information from property file.
978 final Path file = Paths.get(DEPENDENCY_FILE);
979 if (!Files.notExists(file)) {
981 final String dependencyJson = new String(Files.readAllBytes(file), StandardCharsets.UTF_8);
982 final DependencyInfo dependencyInfo =
983 PolicyUtils.jsonStringToObject(dependencyJson, DependencyInfo.class);
984 String controller = "default";
985 if (dependencyInfo.getDependencies().containsKey(controllerName)) {
986 controller = controllerName;
988 final List<Dependency> dependencyList = new ArrayList<>();
989 for (final PEDependency dependency : dependencyInfo.getDependencies().get(controller)) {
990 dependencyList.add(dependency.getDependency());
992 return dependencyList;
993 } catch (IOException | NullPointerException e) {
994 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
995 + "Error while getting dependecy Information for controller: " + controllerName
996 + e.getMessage(), e);
999 return defaultDependencies(controllerName);
1003 * Default Dependency Section. Can be changed as required.
1005 * @param controllerName the controller name
1006 * @return changed dependency list
1008 public List<Dependency> defaultDependencies(final String controllerName) {
1010 final List<Dependency> dependencyList = new ArrayList<>();
1011 final String version = StringEscapeUtils.escapeJava(brmsdependencyversion);
1013 final Dependency demoDependency = new Dependency();
1014 demoDependency.setGroupId(DROOLS_APPS_TEMPLATE_GROUP);
1015 demoDependency.setArtifactId("template.demo");
1016 demoDependency.setVersion(version);
1017 dependencyList.add(demoDependency);
1019 final Dependency controlloopDependency = new Dependency();
1020 controlloopDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1021 controlloopDependency.setArtifactId("events");
1022 controlloopDependency.setVersion(version);
1023 dependencyList.add(controlloopDependency);
1025 final Dependency restDependency = new Dependency();
1026 restDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1027 restDependency.setArtifactId("controlloop.common.model-impl.rest");
1028 restDependency.setVersion(version);
1029 dependencyList.add(restDependency);
1031 final Dependency appcDependency = new Dependency();
1032 appcDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1033 appcDependency.setArtifactId("controlloop.common.model-impl.appc");
1034 appcDependency.setVersion(version);
1035 dependencyList.add(appcDependency);
1037 final Dependency aaiDependency = new Dependency();
1038 aaiDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1039 aaiDependency.setArtifactId("controlloop.common.model-impl.aai");
1040 aaiDependency.setVersion(version);
1041 dependencyList.add(aaiDependency);
1043 final Dependency msoDependency = new Dependency();
1044 msoDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1045 msoDependency.setArtifactId("controlloop.common.model-impl.so");
1046 msoDependency.setVersion(version);
1047 dependencyList.add(msoDependency);
1049 final Dependency trafficgeneratorDependency = new Dependency();
1050 trafficgeneratorDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1051 trafficgeneratorDependency.setArtifactId("controlloop.common.model-impl.trafficgenerator");
1052 trafficgeneratorDependency.setVersion(version);
1053 dependencyList.add(trafficgeneratorDependency);
1054 return dependencyList;
1057 private void createProject(final String path, final String ksessionName) {
1058 new File(path + File.separator + RULES).mkdirs();
1059 new File(path + File.separator + META_INF).mkdirs();
1060 if (!Files.exists(Paths.get(path + File.separator + META_INF + File.separator + KMODULE_XML_FILE))) {
1061 // Hard coding XML for PDP Drools to accept our Rules.
1062 final String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "\n"
1063 + "<kmodule xmlns=\"http://jboss.org/kie/6.0.0/kmodule\">" + "\n"
1064 + "<kbase name=\"rules\" packages=\"rules\">" + "\n" + "<ksession name=\"" + ksessionName + "\"/>"
1065 + "\n" + "</kbase></kmodule>";
1066 copyDataToFile(path + File.separator + META_INF + File.separator + KMODULE_XML_FILE, xml);
1070 private void copyDataToFile(final String file, final String rule) {
1072 FileUtils.writeStringToFile(new File(file), rule);
1073 } catch (final Exception e) {
1075 XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while creating Rule for " + file + e.getMessage(),
1080 private void readGroups(final Properties config) throws PolicyException {
1081 String[] groupNames;
1082 final String groupNamesError = "groupNames property is missing or empty from the property file ";
1083 if (!config.containsKey(GROUP_NAMES) || config.getProperty(GROUP_NAMES) == null) {
1084 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + groupNamesError);
1086 if (config.getProperty(GROUP_NAMES).contains(",")) {
1087 groupNames = config.getProperty(GROUP_NAMES).replaceAll(" ", "").split(",");
1089 groupNames = new String[] { config.getProperty(GROUP_NAMES).replaceAll(" ", "") };
1091 if (groupNames == null || groupNames.length == 0) {
1092 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + groupNamesError);
1093 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + groupNamesError);
1095 groupMap = new HashMap<>();
1096 for (int counter = 0; counter < groupNames.length; counter++) {
1097 final String name = groupNames[counter];
1098 final String groupId = config.getProperty(name + ".groupID");
1099 if (groupId == null) {
1100 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1101 + ".groupID property is missing from the property file ");
1102 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1103 + ".groupID property is missing from the property file ");
1105 final String artifactId = config.getProperty(name + ".artifactID");
1106 if (artifactId == null) {
1107 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1108 + ".artifactID property is missing from the property file ");
1109 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1110 + ".artifactID property is missing from the property file ");
1112 final PEDependency dependency = new PEDependency();
1113 dependency.setArtifactId(artifactId);
1114 dependency.setGroupId(groupId);
1115 // Add to list if we got all
1116 addToGroup(name, dependency);
1120 private void addToGroup(final String name, final PEDependency dependency) {
1121 final EntityTransaction et = em.getTransaction();
1124 final TypedQuery<BrmsGroupInfo> query = em
1125 .createQuery("select b from BrmsGroupInfo as b where b.controllerName = :cn", BrmsGroupInfo.class);
1126 query.setParameter("cn", name);
1127 final List<BrmsGroupInfo> groupList = query.getResultList();
1128 BrmsGroupInfo brmsGroupInfo = null;
1129 if (!groupList.isEmpty()) {
1130 LOGGER.info("Controller name already Existing in DB. Will be updating the DB Values" + name);
1131 brmsGroupInfo = groupList.get(0);
1133 if (brmsGroupInfo == null) {
1134 brmsGroupInfo = new BrmsGroupInfo();
1136 brmsGroupInfo.setControllerName(name);
1137 brmsGroupInfo.setGroupId(dependency.getGroupId());
1138 brmsGroupInfo.setArtifactId(dependency.getArtifactId());
1139 brmsGroupInfo.setVersion(dependency.getVersion());
1140 em.persist(brmsGroupInfo);
1144 final ArrayList<Object> values = new ArrayList<>();
1145 values.add(dependency);
1146 groupMap.put(name, values);
1147 } catch (final Exception exception) {
1148 LOGGER.error("Unable add/update policy group to database for controller name: " + name, exception);
1154 private String getArtifactId(final String name) {
1155 return ((PEDependency) groupMap.get(name).get(0)).getArtifactId();
1158 private String getGroupId(final String name) {
1159 return ((PEDependency) groupMap.get(name).get(0)).getGroupId();
1162 private String getVersion(final String name) {
1163 return ((PEDependency) groupMap.get(name).get(0)).getVersion();
1166 private void getNameAndSetRemove(final String controllerName, final String policyName) {
1167 final String artifactName = getArtifactId(controllerName);
1168 final String ruleFolder = PROJECTSLOCATION + File.separator + artifactName + File.separator + "src"
1169 + File.separator + "main" + File.separator + RESOURCES + File.separator + RULES;
1170 final File file = new File(ruleFolder + File.separator + policyName + ".drl");
1171 if (file.delete()) {
1172 LOGGER.info("Deleted File.. " + file.getAbsolutePath());
1173 removePolicyFromGroup(policyName, controllerName);
1175 if (new File(ruleFolder).listFiles().length == 0) {
1176 removedRuleModifiedGroup(controllerName);
1178 // This is an update in terms of PDPD.
1179 addModifiedGroup(controllerName, "update");
1183 // Removes Policy from Memory and Database.
1184 private void removePolicyFromGroup(final String policyName, final String controllerName) {
1185 final EntityTransaction et = em.getTransaction();
1188 final TypedQuery<BrmsPolicyInfo> query =
1189 em.createQuery("select b from BrmsPolicyInfo as b where b.policyName = :pn", BrmsPolicyInfo.class);
1190 query.setParameter("pn", policyName);
1191 final List<BrmsPolicyInfo> pList = query.getResultList();
1192 BrmsPolicyInfo brmsPolicyInfo;
1193 if (!pList.isEmpty()) {
1195 brmsPolicyInfo = pList.get(0);
1196 if (brmsPolicyInfo.getControllerName().getControllerName().equals(controllerName)) {
1197 em.remove(brmsPolicyInfo);
1202 policyMap.remove(policyName);
1203 } catch (final Exception exception) {
1204 LOGGER.error("Unable remove policy from group to database for policy name: " + policyName, exception);
1210 private void setVersion(final String selectedName) {
1211 String newVersion = VERSION_0_1_0;
1213 final NexusArtifact artifact = getLatestArtifactFromNexus(selectedName);
1214 if (artifact != null) {
1215 newVersion = incrementVersion(artifact.getVersion());
1217 if (VERSION_0_1_0.equals(newVersion)) {
1220 setVersion(newVersion, selectedName);
1221 LOGGER.info("Controller: " + selectedName + "is on version: " + newVersion);
1224 private void setVersion(final String newVersion, final String controllerName) {
1225 final PEDependency userController = (PEDependency) groupMap.get(controllerName).get(0);
1226 userController.setVersion(newVersion);
1227 groupMap.get(controllerName).set(0, userController);
1230 // Return BackUpMonitor
1231 public static BackUpMonitor getBackUpMonitor() {
1238 public void rotateUrls() {
1239 if (repUrlList != null) {
1240 Collections.rotate(repUrlList, -1);
1245 * Get URL List Size.
1247 * @return URL list size
1249 public int urlListSize() {
1250 return repUrlList != null ? repUrlList.size() : 0;