2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.brms.api;
23 import com.att.nsa.cambria.client.CambriaBatchingPublisher;
24 import com.att.nsa.cambria.client.CambriaClientBuilders;
25 import com.att.nsa.cambria.client.CambriaClientBuilders.PublisherBuilder;
26 import com.fasterxml.jackson.core.JsonProcessingException;
29 import java.io.FileInputStream;
30 import java.io.FileOutputStream;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.io.Writer;
35 import java.nio.channels.Channels;
36 import java.nio.channels.ReadableByteChannel;
37 import java.nio.charset.StandardCharsets;
38 import java.nio.file.Files;
39 import java.nio.file.Path;
40 import java.nio.file.Paths;
41 import java.security.GeneralSecurityException;
42 import java.util.ArrayList;
43 import java.util.Arrays;
44 import java.util.Collections;
45 import java.util.Enumeration;
46 import java.util.HashMap;
47 import java.util.List;
49 import java.util.Properties;
50 import java.util.UUID;
51 import java.util.concurrent.TimeUnit;
52 import java.util.jar.JarEntry;
53 import java.util.jar.JarFile;
54 import java.util.regex.Pattern;
56 import javax.persistence.EntityManager;
57 import javax.persistence.EntityManagerFactory;
58 import javax.persistence.EntityTransaction;
59 import javax.persistence.Persistence;
60 import javax.persistence.TypedQuery;
61 import javax.ws.rs.ProcessingException;
63 import org.apache.commons.io.FileUtils;
64 import org.apache.commons.lang.StringEscapeUtils;
65 import org.apache.maven.model.Dependency;
66 import org.apache.maven.model.DeploymentRepository;
67 import org.apache.maven.model.DistributionManagement;
68 import org.apache.maven.model.Model;
69 import org.apache.maven.model.io.xpp3.MavenXpp3Writer;
70 import org.apache.maven.shared.invoker.DefaultInvocationRequest;
71 import org.apache.maven.shared.invoker.DefaultInvoker;
72 import org.apache.maven.shared.invoker.InvocationRequest;
73 import org.apache.maven.shared.invoker.InvocationResult;
74 import org.apache.maven.shared.invoker.Invoker;
75 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).
101 * Mavenize and push policy to PR
106 public class BrmsPush {
107 private static final String GROUP_NAMES = "groupNames";
108 private static final String DROOLS_APPS_TEMPLATE_GROUP =
109 "org.onap.policy.drools-applications.controlloop.templates";
110 private static final String DROOLS_APPS_MODEL_GROUP =
111 "org.onap.policy.drools-applications.controlloop.common.model-impl";
112 private static final String META_INF = "META-INF";
113 private static final String KMODULE_XML_FILE = "kmodule.xml";
114 private static final String POM_XML_FILE = "pom.xml";
115 private static final String VERSION_0_1_0 = "0.1.0";
116 private static final String RULES = "rules";
117 private static final String RESOURCES = "resources";
118 private static final Logger LOGGER = FlexLogger.getLogger(BrmsPush.class.getName());
119 private static final String PROJECTSLOCATION = "RuleProjects";
120 private static final String[] GOALS = {"clean", "deploy"};
121 private static final String DEFAULT_VERSION = "1.2.1-SNAPSHOT";
122 private static final String DEPENDENCY_FILE = "dependency.json";
123 private static final String BRMSPERSISTENCE = "brmsEclipselink.persistencexml";
125 private static Map<String, String> modifiedGroups = new HashMap<>();
126 private static IntegrityMonitor im;
127 private static BackUpMonitor bm;
128 private String defaultName = null;
129 private String repId = null;
130 private String repName = null;
131 private List<String> repUrlList = null;
132 private String repUserName = null;
133 private String repPassword = null;
134 private String policyKeyId = null;
135 private boolean createFlag = false;
136 private String uebList = null;
137 private List<String> dmaapList = null;
138 private String pubTopic = null;
139 private PublisherBuilder pubBuilder = null;
140 protected BusPublisher publisher = null;
141 private Long uebDelay = Long.parseLong("20");
142 private Long dmaapDelay = Long.parseLong("5000");
143 private String notificationType = null;
144 private List<ControllerPojo> controllers;
145 private Map<String, ArrayList<Object>> groupMap = new HashMap<>();
146 private final Map<String, String> policyMap = new HashMap<>();
147 private String brmsdependencyversion;
148 private EntityManager em;
149 private boolean syncFlag = false;
152 * Responsible to push policies to the BRMS PDP Policy Repository (PR).
154 * @param propertiesFile the properties file
155 * @param handler the {@link BackUpHandler}
156 * @throws PolicyException PolicyException related to the operation
158 public BrmsPush(final String propertiesFile, final BackUpHandler handler) throws PolicyException {
159 if (propertiesFile == null || handler == null) {
160 throw new PolicyException("Error no propertiesFile or handler");
162 final Properties config = new Properties();
163 final Path file = Paths.get(propertiesFile);
164 if (Files.notExists(file)) {
165 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Config File doesn't Exist in the specified Path "
167 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
168 + "Config File doesn't Exist in the specified Path " + file.toString());
170 if (file.toString().endsWith(".properties")) {
171 // Grab the Properties.
172 setProperty(file, config, handler);
177 private void setProperty(final Path file, final Properties config, final BackUpHandler handler)
178 throws PolicyException {
181 in = new FileInputStream(file.toFile());
183 } catch (final IOException e) {
185 XACMLErrorConstants.ERROR_DATA_ISSUE + "Data/File Read Error while reading from the property file.",
187 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
188 + "Data/File Read Error while reading from the property file.");
190 LOGGER.info("Trying to set up IntegrityMonitor");
191 String resourceName = null;
193 LOGGER.info("Trying to set up IntegrityMonitor");
194 resourceName = config.getProperty("RESOURCE_NAME");
195 if (resourceName == null) {
196 LOGGER.warn("RESOURCE_NAME is missing setting default value. ");
197 resourceName = "brmsgw_pdp01";
199 resourceName = resourceName.trim();
200 setIntegrityMonitor(IntegrityMonitor.getInstance(resourceName, config));
201 } catch (final Exception e) {
202 LOGGER.error("Error starting Integerity Monitor: " + e);
204 LOGGER.info("Trying to set up BackUpMonitor");
206 setBackupMonitor(BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), resourceName, config,
208 } catch (final Exception e) {
209 LOGGER.error("Error starting BackUpMonitor: " + e);
211 if (!config.containsKey(BRMSPERSISTENCE)) {
212 config.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, "META-INF/persistenceBRMS.xml");
214 config.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML,
215 config.getProperty(BRMSPERSISTENCE, "META-INF/persistenceBRMS.xml"));
217 final EntityManagerFactory emf = Persistence.createEntityManagerFactory("BRMSGW", config);
218 em = emf.createEntityManager();
219 defaultName = config.getProperty("defaultName");
220 if (defaultName == null) {
222 XACMLErrorConstants.ERROR_DATA_ISSUE + "defaultName property is missing from the property file ");
223 throw new PolicyException(
224 XACMLErrorConstants.ERROR_DATA_ISSUE + "defaultName property is missing from the property file");
226 defaultName = defaultName.trim();
227 repId = config.getProperty("repositoryID");
230 XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryID property is missing from the property file ");
231 throw new PolicyException(
232 XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryID property is missing from the property file ");
234 repId = repId.trim();
235 repName = config.getProperty("repositoryName");
236 if (repName == null) {
237 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
238 + "repositoryName property is missing from the property file ");
239 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
240 + "repositoryName property is missing from the property file ");
242 repName = repName.trim();
243 final String repUrl = config.getProperty("repositoryURL");
244 if (repUrl == null) {
246 XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryURL property is missing from the property file ");
247 throw new PolicyException(
248 XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryURL property is missing from the property file ");
250 if (repUrl.contains(",")) {
251 repUrlList = new ArrayList<>(Arrays.asList(repUrl.trim().split(",")));
253 repUrlList = new ArrayList<>();
254 repUrlList.add(repUrl);
256 repUserName = config.getProperty("repositoryUsername");
257 repPassword = config.getProperty("repositoryPassword");
258 if (repUserName == null || repPassword == null) {
259 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
260 + "repostoryUserName and respositoryPassword properties are required.");
261 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
262 + "repostoryUserName and respositoryPassword properties are required.");
264 repUserName = repUserName.trim();
265 repPassword = repPassword.trim();
266 policyKeyId = config.getProperty("policyKeyID");
267 if (policyKeyId == null) {
269 XACMLErrorConstants.ERROR_DATA_ISSUE + "policyKeyID property is missing from the property file ");
270 throw new PolicyException(
271 XACMLErrorConstants.ERROR_DATA_ISSUE + "policyKeyID property is missing from the property file ");
273 policyKeyId = policyKeyId.trim();
274 final String syncF = config.getProperty("sync", "false").trim();
275 syncFlag = Boolean.parseBoolean(syncF);
277 PolicyLogger.info("SYNC Flag is turned ON. DB will be given Priority.");
279 brmsdependencyversion = config.getProperty("brms.dependency.version");
280 if (brmsdependencyversion == null) {
281 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
282 + "brmsdependencyversion property is missing from the property file, Using default Version.");
283 brmsdependencyversion = DEFAULT_VERSION;
285 brmsdependencyversion = brmsdependencyversion.trim();
289 notificationType = config.getProperty("NOTIFICATION_TYPE");
290 if ("dmaap".equalsIgnoreCase(notificationType)) {
292 LOGGER.info("Notification Type being used is DMaaP... creating instance of BusPublisher.");
293 // Setting up the Publisher for DMaaP MR
294 String dmaapServers = config.getProperty("NOTIFICATION_SERVERS");
295 pubTopic = config.getProperty("NOTIFICATION_TOPIC");
296 final String aafLogin = config.getProperty("CLIENT_ID").trim();
297 final String aafPassword = config.getProperty("CLIENT_KEY").trim();
299 if (dmaapServers == null || pubTopic == null) {
301 XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file ");
302 throw new PolicyException(
303 XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file ");
306 dmaapServers = dmaapServers.trim();
307 pubTopic = pubTopic.trim();
309 if (dmaapServers.contains(",")) {
310 dmaapList = new ArrayList<>(Arrays.asList(dmaapServers.split("\\s*,\\s*")));
312 dmaapList = new ArrayList<>();
313 dmaapList.add(dmaapServers);
317 new BusPublisher.DmaapPublisherWrapper(this.dmaapList, this.pubTopic, aafLogin, aafPassword);
319 String notificationDelay = config.getProperty("NOTIFICATION_DELAY");
320 if (notificationDelay != null && !notificationDelay.isEmpty()) {
321 notificationDelay = notificationDelay.trim();
323 dmaapDelay = Long.parseLong(notificationDelay);
324 } catch (final NumberFormatException e) {
325 LOGGER.error("DMAAP_DELAY not a long format number" + e);
328 LOGGER.info("DMAAP BusPublisher is created.");
331 LOGGER.info("Notification Type being used is UEB... creating instance of PublisherBuilder.");
332 // Setting up the Publisher for UEB
333 uebList = config.getProperty("NOTIFICATION_SERVERS");
334 pubTopic = config.getProperty("NOTIFICATION_TOPIC");
335 if (uebList == null || pubTopic == null) {
337 XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file ");
338 throw new PolicyException(
339 XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file ");
341 uebList = uebList.trim();
342 pubTopic = pubTopic.trim();
343 pubBuilder = new CambriaClientBuilders.PublisherBuilder();
344 pubBuilder.usingHosts(uebList).onTopic(pubTopic);
345 String apiKey = config.getProperty("UEB_API_KEY");
346 String apiSecret = config.getProperty("UEB_API_SECRET");
347 if (apiKey != null && !apiKey.isEmpty() && apiSecret != null && !apiSecret.isEmpty()) {
348 apiKey = apiKey.trim();
349 apiSecret = apiSecret.trim();
350 pubBuilder.authenticatedBy(apiKey, apiSecret);
352 String notificationDelay = config.getProperty("NOTIFICATION_DELAY");
353 if (notificationDelay != null && !notificationDelay.isEmpty()) {
354 notificationDelay = notificationDelay.trim();
356 uebDelay = Long.parseLong(notificationDelay);
357 } catch (final NumberFormatException e) {
358 LOGGER.error("UEB_DELAY not a long format number" + e);
361 LOGGER.info("UEB PublisherBuilder is created.");
367 private static void setBackupMonitor(final BackUpMonitor instance) {
371 private static void setIntegrityMonitor(final IntegrityMonitor instance) {
376 * Will Initialize the variables required for BRMSPush.
378 public void initiate(final boolean flag) {
379 resetModifiedGroups();
380 controllers = new ArrayList<>();
382 bm.updateNotification();
383 } catch (final Exception e) {
384 LOGGER.error("Error while updating Notification: " + e.getMessage(), e);
391 public void resetDs() {
392 resetModifiedGroups();
393 controllers = new ArrayList<>();
396 private static void resetModifiedGroups() {
397 modifiedGroups = new HashMap<>();
401 * Will Add rules to projects. Creates necessary folders if required.
403 public void addRule(final String name, final String rule, final Map<String, String> responseAttributes) {
404 // 1 check the response Attributes and determine if this belongs to any projects.
405 // 2 if not create folder
408 // 5 store the groups that have been updated.
409 String ksessionName = null;
410 String selectedName = null;
411 if (!responseAttributes.isEmpty()) {
412 // Pick selected Value
413 String userControllerName = null;
414 final ArrayList<PEDependency> userDependencies = new ArrayList<>();
415 for (final Map.Entry<String, String> entry : responseAttributes.entrySet()) {
416 final String key = entry.getKey();
417 String value = entry.getValue();
418 if (key.equals(policyKeyId)) {
419 selectedName = value;
421 // kmodule configurations
422 else if ("kSessionName".equals(key)) {
423 ksessionName = value;
425 // Check User Specific values.
426 if ("$controller:".equals(key)) {
428 final PEDependency dependency = PolicyUtils.jsonStringToObject(value, PEDependency.class);
429 userControllerName = key.replaceFirst("$controller:", "");
430 LOGGER.info("addRule: userControllerName - " + userControllerName + ", dependency: - "
432 addToGroup(userControllerName, dependency);
433 } catch (final Exception e) {
434 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while resolving Controller: " + e);
437 } else if ("$dependency$".equals(key) && value.startsWith("[") && value.endsWith("]")) {
438 value = value.substring(1, value.length() - 1).trim();
439 final List<String> dependencyStrings = Arrays.asList(value.split(Pattern.quote("},{")));
440 for (final String dependencyString : dependencyStrings) {
442 userDependencies.add(PolicyUtils.jsonStringToObject(dependencyString, PEDependency.class));
443 } catch (final Exception e) {
444 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while resolving Dependencies: "
450 if (userControllerName != null) {
451 // Adding custom dependencies here.
452 final ArrayList<Object> values = groupMap.get(userControllerName);
453 values.add(userDependencies);
454 groupMap.put(userControllerName, values);
455 selectedName = userControllerName;
458 // If no Match then pick Default.
459 if (selectedName == null) {
460 selectedName = defaultName;
462 if (groupMap.containsKey(selectedName)) {
463 // If the key is not got as parameters set by the user, setting the default value for
466 if (ksessionName == null) {
467 LOGGER.info("kSessionName is null, selectedName is : " + selectedName);
468 if (selectedName.equalsIgnoreCase(defaultName)) {
469 ksessionName = "closedloop";
471 ksessionName = "closedloop-" + selectedName;
474 // create directories if missing.
475 manageProject(selectedName, ksessionName, name, rule);
477 // Will check for Create Later after generating the Pom.
478 addModifiedGroup(selectedName, "update");
482 private void syncGroupInfo() {
483 // Sync DB to JMemory.
484 final EntityTransaction et = em.getTransaction();
487 final TypedQuery<BrmsGroupInfo> groupInfoQuery =
488 em.createQuery("select b from BrmsGroupInfo AS b", BrmsGroupInfo.class);
489 final List<BrmsGroupInfo> groupInfoResult = groupInfoQuery.getResultList();
490 if (groupInfoResult.size() != groupMap.size()) {
491 for (final BrmsGroupInfo brmsGroupInfo : groupInfoResult) {
492 final PEDependency dependency = new PEDependency();
493 dependency.setArtifactId(brmsGroupInfo.getArtifactId());
494 dependency.setGroupId(brmsGroupInfo.getGroupId());
495 dependency.setVersion(brmsGroupInfo.getVersion());
496 final ArrayList<Object> values = new ArrayList<>();
497 values.add(dependency);
498 groupMap.put(brmsGroupInfo.getControllerName(), values);
502 final TypedQuery<BrmsPolicyInfo> policyInfoQuery =
503 em.createQuery("select g from BrmsPolicyInfo AS g", BrmsPolicyInfo.class);
504 final List<BrmsPolicyInfo> policyInfoResult = policyInfoQuery.getResultList();
505 if (policyInfoResult.size() != policyMap.size()) {
506 for (final BrmsPolicyInfo brmsPolicyInfo : policyInfoResult) {
507 policyMap.put(brmsPolicyInfo.getPolicyName(),
508 brmsPolicyInfo.getControllerName().getControllerName());
512 LOGGER.info("Updated Local Memory values with values from database.");
513 } catch (final Exception exception) {
514 LOGGER.error("Unable to sync group info", exception);
520 private void manageProject(final String selectedName, final String ksessionName, final String name,
522 // Check if the Project is in Sync. If not get the latest Version.
523 syncProject(selectedName);
524 createProject(PROJECTSLOCATION + File.separator + getArtifactId(selectedName) + File.separator + "src"
525 + File.separator + "main" + File.separator + RESOURCES, ksessionName);
526 copyDataToFile(PROJECTSLOCATION + File.separator + getArtifactId(selectedName) + File.separator + "src"
527 + File.separator + "main" + File.separator + RESOURCES + File.separator + RULES + File.separator + name
529 addToPolicy(name, selectedName);
533 * Add Policy to JMemory and DataBase.
535 private void addToPolicy(final String policyName, final String controllerName) {
537 final EntityTransaction et = em.getTransaction();
540 boolean create = false;
541 final TypedQuery<BrmsPolicyInfo> policyInfoQuery =
542 em.createQuery("select b from BrmsPolicyInfo as b where b.policyName = :pn", BrmsPolicyInfo.class);
543 policyInfoQuery.setParameter("pn", policyName);
544 final List<BrmsPolicyInfo> policyInfoResultList = policyInfoQuery.getResultList();
545 BrmsPolicyInfo brmsPolicyInfo = new BrmsPolicyInfo();
546 if (!policyInfoResultList.isEmpty()) {
548 brmsPolicyInfo = policyInfoResultList.get(0);
549 if (!brmsPolicyInfo.getControllerName().getControllerName().equals(controllerName)) {
556 final TypedQuery<BrmsGroupInfo> groupInfoQuery = em.createQuery(
557 "select b from BrmsGroupInfo as b where b.controllerName = :cn", BrmsGroupInfo.class);
558 groupInfoQuery.setParameter("cn", controllerName);
559 final List<BrmsGroupInfo> groupInfoResultList = groupInfoQuery.getResultList();
560 BrmsGroupInfo brmsGroupInfo = new BrmsGroupInfo();
561 if (!groupInfoResultList.isEmpty()) {
562 brmsGroupInfo = groupInfoResultList.get(0);
564 brmsPolicyInfo.setPolicyName(policyName);
565 brmsPolicyInfo.setControllerName(brmsGroupInfo);
566 em.persist(brmsPolicyInfo);
571 policyMap.put(policyName, controllerName);
572 } catch (final Exception exception) {
573 LOGGER.error("Unable add policy to database", exception);
579 private void syncProject(final String selectedName) {
580 final boolean projectExists = checkProject(selectedName);
583 version = getVersion(selectedName);
584 if (version == null) {
585 LOGGER.error("Error getting local version for the given Controller Name:" + selectedName
586 + " going with Default value");
587 version = VERSION_0_1_0;
589 final String nextVersion = incrementVersion(version);
590 final boolean outOfSync = checkRemoteSync(selectedName, nextVersion);
595 // We are out of Sync or Project is not Present.
596 downloadProject(selectedName);
599 private void downloadProject(final String selectedName) {
600 final NexusArtifact artifact = getLatestArtifactFromNexus(selectedName);
601 if (artifact == null) {
604 final String dirName = getDirectoryName(selectedName);
606 final String fileName = "rule.jar";
608 website = new URL(artifact.getUrlPath() + ".jar");
609 try (ReadableByteChannel rbc = Channels.newChannel(website.openStream());
610 FileOutputStream fos = new FileOutputStream(fileName)) {
611 fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
612 extractJar(fileName, dirName);
613 new File(fileName).delete();
614 } catch (final IOException e) {
615 LOGGER.error("Error while downloading the project to File System. " + e.getMessage(), e);
618 } catch (final IOException e1) {
619 LOGGER.error("Error while retrieve the artifact. " + e1.getMessage(), e1);
623 private void extractJar(final String jarFileName, final String artifactId) {
624 try (JarFile jar = new JarFile(jarFileName)) {
625 final Enumeration<?> enumEntries = jar.entries();
626 while (enumEntries.hasMoreElements()) {
627 final JarEntry jarEntry = (JarEntry) enumEntries.nextElement();
629 final String fileName = jarEntry.getName().substring(jarEntry.getName().lastIndexOf("/") + 1);
630 if (jarEntry.getName().endsWith(".drl")) {
631 final String path = PROJECTSLOCATION + File.separator + artifactId + File.separator + "src"
632 + File.separator + "main" + File.separator + RESOURCES + File.separator + RULES;
633 new File(path).mkdirs();
634 if (syncFlag && policyMap.containsKey(fileName.replace(".drl", ""))) {
635 file = new File(path + File.separator + fileName);
637 file = new File(path + File.separator + fileName);
639 } else if (jarEntry.getName().endsWith(POM_XML_FILE)) {
640 final String path = PROJECTSLOCATION + File.separator + artifactId;
641 new File(path).mkdirs();
642 file = new File(path + File.separator + fileName);
643 } else if (jarEntry.getName().endsWith(KMODULE_XML_FILE)) {
644 final String path = PROJECTSLOCATION + File.separator + artifactId + File.separator + "src"
645 + File.separator + "main" + File.separator + RESOURCES + File.separator + META_INF;
646 new File(path).mkdirs();
647 file = new File(path + File.separator + fileName);
650 try (InputStream is = jar.getInputStream(jarEntry);
651 FileOutputStream fos = new FileOutputStream(file)) {
652 while (is.available() > 0) {
653 fos.write(is.read());
655 LOGGER.info(fileName + " Created..");
656 } catch (final IOException e) {
657 LOGGER.info("exception Occured" + e);
661 } catch (final IOException e) {
662 LOGGER.info("exception Occured" + e);
666 private NexusArtifact getLatestArtifactFromNexus(final String selectedName) {
667 final List<NexusArtifact> artifacts = getArtifactFromNexus(selectedName, null);
670 NexusArtifact result = null;
671 for (final NexusArtifact artifact : artifacts) {
673 Integer.parseInt(artifact.getVersion().substring(0, artifact.getVersion().indexOf(".")));
674 final int minorVal = Integer.parseInt(artifact.getVersion()
675 .substring(artifact.getVersion().indexOf(".") + 1, artifact.getVersion().lastIndexOf(".")));
676 if (majorVal > bigNum) {
680 if ((bigNum == majorVal) && (minorVal > smallNum)) {
683 if (bigNum == majorVal && minorVal == smallNum) {
687 return additionalNexusLatestCheck(selectedName, result);
690 // Additional Check due to Limitations from Nexus API to check if the artifact is the latest.
691 private NexusArtifact additionalNexusLatestCheck(final String selectedName, final NexusArtifact result) {
692 if (result == null) {
695 final String nextVersion = incrementVersion(result.getVersion());
696 final List<NexusArtifact> artifact = getArtifactFromNexus(selectedName, nextVersion);
697 return artifact.isEmpty() ? result : additionalNexusLatestCheck(selectedName, artifact.get(0));
700 private boolean checkRemoteSync(final String selectedName, final String version) {
701 final List<NexusArtifact> artifacts = getArtifactFromNexus(selectedName, version);
702 return artifacts.isEmpty() ? false : true;
705 private List<NexusArtifact> getArtifactFromNexus(final String selectedName, final String version) {
706 NexusRestWrapper restWrapper = null;
708 boolean flag = false;
709 while (index < repUrlList.size()) {
711 final String repUrl = repUrlList.get(0);
713 new NexusRestWrapper(repUrl.substring(0, repUrl.indexOf(repUrl.split(":[0-9]+\\/nexus")[1])),
714 repUserName, repPassword);
715 final NexusRestSearchParameters searchParameters = new NexusRestSearchParameters();
716 searchParameters.useFilterSearch(getGroupId(selectedName), getArtifactId(selectedName), version, null,
719 final List<NexusArtifact> resultList = restWrapper.findArtifact(searchParameters).getArtifactList();
720 if (resultList != null) {
724 } catch (NexusRestWrapperException | ProcessingException e) {
725 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Connection to remote Nexus has failed. "
726 + e.getMessage(), e);
728 if (null != restWrapper) {
732 Collections.rotate(repUrlList, -1);
737 return new ArrayList<>();
740 private String incrementVersion(final String version) {
741 int majorVal = Integer.parseInt(version.substring(0, version.indexOf(".")));
742 int minorVal = Integer.parseInt(version.substring(version.indexOf(".") + 1, version.lastIndexOf(".")));
749 return majorVal + "." + minorVal + version.substring(version.lastIndexOf("."));
752 private boolean checkProject(final String selectedName) {
753 return new File(PROJECTSLOCATION + File.separator + getDirectoryName(selectedName)).exists();
756 private String getDirectoryName(final String selectedName) {
757 return getArtifactId(selectedName);
761 * Will Push policies to the PolicyRepo.
763 * @throws PolicyException PolicyException related to the operation
765 public void pushRules() throws PolicyException {
766 // Check how many groups have been updated.
767 // Invoke their Maven process.
769 im.startTransaction();
770 } catch (final Exception e) {
771 LOGGER.error("Error while starting Transaction " + e);
773 if (!modifiedGroups.isEmpty()) {
774 Boolean flag = false;
775 for (final Map.Entry<String, String> entry : modifiedGroups.entrySet()) {
776 InvocationResult result = null;
777 final String group = entry.getKey();
779 LOGGER.info("PushRules: ModifiedGroups, Key: " + group + ", Value: " + entry.getValue());
780 final InvocationRequest request = new DefaultInvocationRequest();
783 request.setPomFile(new File(
784 PROJECTSLOCATION + File.separator + getArtifactId(group) + File.separator + POM_XML_FILE));
785 request.setGoals(Arrays.asList(GOALS));
786 final Invoker invoker = new DefaultInvoker();
787 result = invoker.execute(request);
788 if (result.getExecutionException() != null) {
789 LOGGER.error(result.getExecutionException());
790 } else if (result.getExitCode() != 0) {
791 LOGGER.error("Maven Invocation failure..!");
793 } catch (final Exception e) {
794 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation issue for "
795 + getArtifactId(group) + e.getMessage(), e);
797 if (result != null && result.getExitCode() == 0) {
798 LOGGER.info("Build Completed..!");
800 addNotification(group, "create");
802 addNotification(group, entry.getValue());
806 throw new PolicyException(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation failure!");
810 sendNotification(controllers);
819 * Removes a Rule from Rule Projects.
821 public void removeRule(final String name) {
822 final String controllerName = getGroupName(name);
823 if (controllerName == null) {
824 LOGGER.info("Error finding the controllerName for the given Policy: " + name);
827 syncProject(controllerName);
828 getNameAndSetRemove(controllerName, name);
831 private String getGroupName(final String name) {
832 if (policyMap.containsKey(name)) {
833 return policyMap.get(name);
836 return policyMap.containsKey(name) ? policyMap.get(name) : null;
840 private void addModifiedGroup(final String controllerName, final String operation) {
841 if (controllerName != null) {
842 modifiedGroups.put(controllerName, operation);
846 private void addNotification(final String controllerName, final String operation) {
847 final ControllerPojo controllerPojo = new ControllerPojo();
848 controllerPojo.setName(controllerName);
849 controllerPojo.setOperation(operation);
850 final HashMap<String, String> drools = new HashMap<>();
851 drools.put("groupId", getGroupId(controllerName));
852 drools.put("artifactId", getArtifactId(controllerName));
853 drools.put("version", getVersion(controllerName));
854 controllerPojo.setDrools(drools);
855 controllers.add(controllerPojo);
857 LOGGER.debug("Notification added: " + PolicyUtils.objectToJsonString(controllerPojo));
858 } catch (final JsonProcessingException e) {
859 LOGGER.error(MessageCodes.ERROR_SCHEMA_INVALID + "Json Processing Error " + e);
863 private void removedRuleModifiedGroup(final String controllerName) {
864 // This will be sending Notification to PDPD directly to Lock
865 final ControllerPojo controllerPojo = new ControllerPojo();
866 controllerPojo.setName(controllerName);
867 controllerPojo.setOperation("lock");
868 final List<ControllerPojo> controllerPojos = new ArrayList<>();
869 controllerPojos.add(controllerPojo);
870 sendNotification(controllerPojos);
873 private void sendNotification(final List<ControllerPojo> controllers) {
874 final NotificationPojo notification = new NotificationPojo();
875 final String requestId = UUID.randomUUID().toString();
876 LOGGER.info("Generating notification RequestID : " + requestId);
877 notification.setRequestId(requestId);
878 notification.setEntity("controller");
879 notification.setControllers(controllers);
881 final String notificationJson = PolicyUtils.objectToJsonString(notification);
882 LOGGER.info("Sending Notification :\n" + notificationJson);
883 sendMessage(notificationJson);
884 } catch (final Exception e) {
885 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while sending notification to PDP-D "
886 + e.getMessage(), e);
890 private void sendMessage(final String message) throws IOException, GeneralSecurityException, InterruptedException {
892 if ("dmaap".equalsIgnoreCase(notificationType)) {
893 // Sending Message through DMaaP Message Router
894 LOGGER.debug("DMAAP Publishing Message");
896 publisher.send("MyPartitionKey", message);
898 LOGGER.debug("Message Published on DMaaP :" + dmaapList.get(0) + "for Topic: " + pubTopic);
900 Thread.sleep(dmaapDelay);
903 // Sending Message through UEB interface.
904 LOGGER.debug("UEB Publishing Message");
906 final CambriaBatchingPublisher pub = pubBuilder.build();
907 pub.send("MyPartitionKey", message);
909 final List<?> stuck = pub.close(uebDelay, TimeUnit.SECONDS);
910 if (!stuck.isEmpty()) {
911 LOGGER.error(stuck.size() + " messages unsent");
913 LOGGER.debug("Clean exit; Message Published on UEB : " + uebList + "for Topic: " + pubTopic);
919 private void createPom(final String name) {
920 final Model model = new Model();
921 model.setModelVersion("4.0.0");
922 model.setGroupId(getGroupId(name));
923 model.setArtifactId(getArtifactId(name));
924 model.setVersion(getVersion(name));
926 final DistributionManagement distributionManagement = new DistributionManagement();
927 final DeploymentRepository repository = new DeploymentRepository();
928 repository.setId(repId);
929 repository.setName(repName);
930 repository.setUrl(repUrlList.get(0));
931 distributionManagement.setRepository(repository);
932 model.setDistributionManagement(distributionManagement);
933 // Dependency Management goes here.
934 List<Dependency> dependencyList = new ArrayList<>();
935 if (groupMap.get(name).size() > 1) {
936 @SuppressWarnings("unchecked")
937 final ArrayList<PEDependency> dependencies = (ArrayList<PEDependency>) groupMap.get(name).get(1);
938 for (final PEDependency dependency : dependencies) {
939 dependencyList.add(dependency.getDependency());
942 // Add Default dependencies.
943 dependencyList = getDependencies(name);
945 model.setDependencies(dependencyList);
946 Writer writer = null;
948 writer = WriterFactory.newXmlWriter(
949 new File(PROJECTSLOCATION + File.separator + getArtifactId(name) + File.separator + POM_XML_FILE));
950 final MavenXpp3Writer pomWriter = new MavenXpp3Writer();
951 pomWriter.write(writer, model);
952 } catch (final Exception e) {
953 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while creating POM for " + getArtifactId(name)
954 + e.getMessage(), e);
956 IOUtil.close(writer);
960 private List<Dependency> getDependencies(final String controllerName) {
961 // Read the Dependency Information from property file.
962 final Path file = Paths.get(DEPENDENCY_FILE);
963 if (!Files.notExists(file)) {
965 final String dependencyJson = new String(Files.readAllBytes(file), StandardCharsets.UTF_8);
966 final DependencyInfo dependencyInfo =
967 PolicyUtils.jsonStringToObject(dependencyJson, DependencyInfo.class);
968 String controller = "default";
969 if (dependencyInfo.getDependencies().containsKey(controllerName)) {
970 controller = controllerName;
972 final List<Dependency> dependencyList = new ArrayList<>();
973 for (final PEDependency dependency : dependencyInfo.getDependencies().get(controller)) {
974 dependencyList.add(dependency.getDependency());
976 return dependencyList;
977 } catch (IOException | NullPointerException e) {
978 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
979 + "Error while getting dependecy Information for controller: " + controllerName
980 + e.getMessage(), e);
983 return defaultDependencies(controllerName);
987 * Default Dependency Section. Can be changed as required.
989 * @param controllerName the controller name
990 * @return changed dependency list
992 public List<Dependency> defaultDependencies(final String controllerName) {
994 final List<Dependency> dependencyList = new ArrayList<>();
995 final String version = StringEscapeUtils.escapeJava(brmsdependencyversion);
997 final Dependency demoDependency = new Dependency();
998 demoDependency.setGroupId(DROOLS_APPS_TEMPLATE_GROUP);
999 demoDependency.setArtifactId("template.demo");
1000 demoDependency.setVersion(version);
1001 dependencyList.add(demoDependency);
1003 final Dependency controlloopDependency = new Dependency();
1004 controlloopDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1005 controlloopDependency.setArtifactId("events");
1006 controlloopDependency.setVersion(version);
1007 dependencyList.add(controlloopDependency);
1009 final Dependency restDependency = new Dependency();
1010 restDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1011 restDependency.setArtifactId("controlloop.common.model-impl.rest");
1012 restDependency.setVersion(version);
1013 dependencyList.add(restDependency);
1015 final Dependency appcDependency = new Dependency();
1016 appcDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1017 appcDependency.setArtifactId("controlloop.common.model-impl.appc");
1018 appcDependency.setVersion(version);
1019 dependencyList.add(appcDependency);
1021 final Dependency aaiDependency = new Dependency();
1022 aaiDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1023 aaiDependency.setArtifactId("controlloop.common.model-impl.aai");
1024 aaiDependency.setVersion(version);
1025 dependencyList.add(aaiDependency);
1027 final Dependency msoDependency = new Dependency();
1028 msoDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1029 msoDependency.setArtifactId("controlloop.common.model-impl.so");
1030 msoDependency.setVersion(version);
1031 dependencyList.add(msoDependency);
1033 final Dependency trafficgeneratorDependency = new Dependency();
1034 trafficgeneratorDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1035 trafficgeneratorDependency.setArtifactId("controlloop.common.model-impl.trafficgenerator");
1036 trafficgeneratorDependency.setVersion(version);
1037 dependencyList.add(trafficgeneratorDependency);
1038 return dependencyList;
1041 private void createProject(final String path, final String ksessionName) {
1042 new File(path + File.separator + RULES).mkdirs();
1043 new File(path + File.separator + META_INF).mkdirs();
1044 if (!Files.exists(Paths.get(path + File.separator + META_INF + File.separator + KMODULE_XML_FILE))) {
1045 // Hard coding XML for PDP Drools to accept our Rules.
1046 final String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "\n"
1047 + "<kmodule xmlns=\"http://jboss.org/kie/6.0.0/kmodule\">" + "\n"
1048 + "<kbase name=\"rules\" packages=\"rules\">" + "\n" + "<ksession name=\"" + ksessionName + "\"/>"
1049 + "\n" + "</kbase></kmodule>";
1050 copyDataToFile(path + File.separator + META_INF + File.separator + KMODULE_XML_FILE, xml);
1054 private void copyDataToFile(final String file, final String rule) {
1056 FileUtils.writeStringToFile(new File(file), rule);
1057 } catch (final Exception e) {
1059 XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while creating Rule for " + file + e.getMessage(),
1064 private void readGroups(final Properties config) throws PolicyException {
1065 String[] groupNames;
1066 final String groupNamesError = "groupNames property is missing or empty from the property file ";
1067 if (!config.containsKey(GROUP_NAMES) || config.getProperty(GROUP_NAMES) == null) {
1068 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + groupNamesError);
1070 if (config.getProperty(GROUP_NAMES).contains(",")) {
1071 groupNames = config.getProperty(GROUP_NAMES).replaceAll(" ", "").split(",");
1073 groupNames = new String[] {config.getProperty(GROUP_NAMES).replaceAll(" ", "")};
1075 if (groupNames == null || groupNames.length == 0) {
1076 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + groupNamesError);
1077 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + groupNamesError);
1079 groupMap = new HashMap<>();
1080 for (int counter = 0; counter < groupNames.length; counter++) {
1081 final String name = groupNames[counter];
1082 final String groupId = config.getProperty(name + ".groupID");
1083 if (groupId == null) {
1084 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1085 + ".groupID property is missing from the property file ");
1086 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1087 + ".groupID property is missing from the property file ");
1089 final String artifactId = config.getProperty(name + ".artifactID");
1090 if (artifactId == null) {
1091 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1092 + ".artifactID property is missing from the property file ");
1093 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1094 + ".artifactID property is missing from the property file ");
1096 final PEDependency dependency = new PEDependency();
1097 dependency.setArtifactId(artifactId);
1098 dependency.setGroupId(groupId);
1099 // Add to list if we got all
1100 addToGroup(name, dependency);
1104 private void addToGroup(final String name, final PEDependency dependency) {
1105 final EntityTransaction et = em.getTransaction();
1108 final TypedQuery<BrmsGroupInfo> query = em
1109 .createQuery("select b from BrmsGroupInfo as b where b.controllerName = :cn", BrmsGroupInfo.class);
1110 query.setParameter("cn", name);
1111 final List<BrmsGroupInfo> groupList = query.getResultList();
1112 BrmsGroupInfo brmsGroupInfo = null;
1113 if (!groupList.isEmpty()) {
1114 LOGGER.info("Controller name already Existing in DB. Will be updating the DB Values" + name);
1115 brmsGroupInfo = groupList.get(0);
1117 if (brmsGroupInfo == null) {
1118 brmsGroupInfo = new BrmsGroupInfo();
1120 brmsGroupInfo.setControllerName(name);
1121 brmsGroupInfo.setGroupId(dependency.getGroupId());
1122 brmsGroupInfo.setArtifactId(dependency.getArtifactId());
1123 brmsGroupInfo.setVersion(dependency.getVersion());
1124 em.persist(brmsGroupInfo);
1128 final ArrayList<Object> values = new ArrayList<>();
1129 values.add(dependency);
1130 groupMap.put(name, values);
1131 } catch (final Exception exception) {
1132 LOGGER.error("Unable add/update policy group to database for controller name: " + name, exception);
1138 private String getArtifactId(final String name) {
1139 return ((PEDependency) groupMap.get(name).get(0)).getArtifactId();
1142 private String getGroupId(final String name) {
1143 return ((PEDependency) groupMap.get(name).get(0)).getGroupId();
1146 private String getVersion(final String name) {
1147 return ((PEDependency) groupMap.get(name).get(0)).getVersion();
1150 private void getNameAndSetRemove(final String controllerName, final String policyName) {
1151 final String artifactName = getArtifactId(controllerName);
1152 final String ruleFolder = PROJECTSLOCATION + File.separator + artifactName + File.separator + "src"
1153 + File.separator + "main" + File.separator + RESOURCES + File.separator + RULES;
1154 final File file = new File(ruleFolder + File.separator + policyName + ".drl");
1155 if (file.delete()) {
1156 LOGGER.info("Deleted File.. " + file.getAbsolutePath());
1157 removePolicyFromGroup(policyName, controllerName);
1159 if (new File(ruleFolder).listFiles().length == 0) {
1160 removedRuleModifiedGroup(controllerName);
1162 // This is an update in terms of PDPD.
1163 addModifiedGroup(controllerName, "update");
1167 // Removes Policy from Memory and Database.
1168 private void removePolicyFromGroup(final String policyName, final String controllerName) {
1169 final EntityTransaction et = em.getTransaction();
1172 final TypedQuery<BrmsPolicyInfo> query =
1173 em.createQuery("select b from BrmsPolicyInfo as b where b.policyName = :pn", BrmsPolicyInfo.class);
1174 query.setParameter("pn", policyName);
1175 final List<BrmsPolicyInfo> pList = query.getResultList();
1176 BrmsPolicyInfo brmsPolicyInfo;
1177 if (!pList.isEmpty()) {
1179 brmsPolicyInfo = pList.get(0);
1180 if (brmsPolicyInfo.getControllerName().getControllerName().equals(controllerName)) {
1181 em.remove(brmsPolicyInfo);
1186 policyMap.remove(policyName);
1187 } catch (final Exception exception) {
1188 LOGGER.error("Unable remove policy from group to database for policy name: " + policyName, exception);
1194 private void setVersion(final String selectedName) {
1195 String newVersion = VERSION_0_1_0;
1197 final NexusArtifact artifact = getLatestArtifactFromNexus(selectedName);
1198 if (artifact != null) {
1199 newVersion = incrementVersion(artifact.getVersion());
1201 if (VERSION_0_1_0.equals(newVersion)) {
1204 setVersion(newVersion, selectedName);
1205 LOGGER.info("Controller: " + selectedName + "is on version: " + newVersion);
1208 private void setVersion(final String newVersion, final String controllerName) {
1209 final PEDependency userController = (PEDependency) groupMap.get(controllerName).get(0);
1210 userController.setVersion(newVersion);
1211 groupMap.get(controllerName).set(0, userController);
1214 // Return BackUpMonitor
1215 public static BackUpMonitor getBackUpMonitor() {
1222 public void rotateUrls() {
1223 if (repUrlList != null) {
1224 Collections.rotate(repUrlList, -1);
1229 * Get URL List Size.
1231 * @return URL list size
1233 public int urlListSize() {
1234 return repUrlList != null ? repUrlList.size() : 0;