Merge "Update installation documentation"
[policy/engine.git] / BRMSGateway / src / main / java / org / onap / policy / brms / api / BrmsPush.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
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
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
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=========================================================
20  */
21
22 package org.onap.policy.brms.api;
23
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;
28
29 import java.io.File;
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;
35 import java.net.URL;
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;
49 import java.util.Map;
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;
56
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;
63
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;
98
99 /**
100  * BRMSPush: Application responsible to push policies to the BRMS PDP Policy Repository (PR). Mavenize and push policy
101  * to PR
102  *
103  * @version 1.0
104  */
105
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";
124
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;
150
151     /**
152      * Responsible to push policies to the BRMS PDP Policy Repository (PR).
153      *
154      * @param propertiesFile the properties file
155      * @param handler the {@link BackUpHandler}
156      * @throws PolicyException PolicyException related to the operation
157      */
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");
161         }
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 "
166                     + file.toString());
167             throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
168                     + "Config File doesn't Exist in the specified Path " + file.toString());
169         } else {
170             if (file.toString().endsWith(".properties")) {
171                 // Grab the Properties.
172                 setProperty(file, config, handler);
173             }
174         }
175     }
176
177     private void setProperty(final Path file, final Properties config, final BackUpHandler handler)
178             throws PolicyException {
179         InputStream in;
180         try {
181             in = new FileInputStream(file.toFile());
182             config.load(in);
183         } catch (final IOException e) {
184             LOGGER.error(
185                     XACMLErrorConstants.ERROR_DATA_ISSUE + "Data/File Read Error while reading from the property file.",
186                     e);
187             throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
188                     + "Data/File Read Error while reading from the property file.");
189         }
190         LOGGER.info("Trying to set up IntegrityMonitor");
191         String resourceName = null;
192         try {
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";
198             }
199             resourceName = resourceName.trim();
200             setIntegrityMonitor(IntegrityMonitor.getInstance(resourceName, config));
201         } catch (final Exception e) {
202             LOGGER.error("Error starting Integerity Monitor: " + e);
203         }
204         LOGGER.info("Trying to set up BackUpMonitor");
205         try {
206             setBackupMonitor(BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), resourceName, config,
207                     handler));
208         } catch (final Exception e) {
209             LOGGER.error("Error starting BackUpMonitor: " + e);
210         }
211         if (!config.containsKey(BRMSPERSISTENCE)) {
212             config.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, "META-INF/persistenceBRMS.xml");
213         } else {
214             config.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML,
215                     config.getProperty(BRMSPERSISTENCE, "META-INF/persistenceBRMS.xml"));
216         }
217         final EntityManagerFactory emf = Persistence.createEntityManagerFactory("BRMSGW", config);
218         em = emf.createEntityManager();
219         defaultName = config.getProperty("defaultName");
220         if (defaultName == null) {
221             LOGGER.error(
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");
225         }
226         defaultName = defaultName.trim();
227         repId = config.getProperty("repositoryID");
228         if (repId == null) {
229             LOGGER.error(
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 ");
233         }
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 ");
241         }
242         repName = repName.trim();
243         final String repUrl = config.getProperty("repositoryURL");
244         if (repUrl == null) {
245             LOGGER.error(
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 ");
249         }
250         if (repUrl.contains(",")) {
251             repUrlList = new ArrayList<>(Arrays.asList(repUrl.trim().split(",")));
252         } else {
253             repUrlList = new ArrayList<>();
254             repUrlList.add(repUrl);
255         }
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.");
263         }
264         repUserName = repUserName.trim();
265         repPassword = repPassword.trim();
266         policyKeyId = config.getProperty("policyKeyID");
267         if (policyKeyId == null) {
268             LOGGER.error(
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 ");
272         }
273         policyKeyId = policyKeyId.trim();
274         final String syncF = config.getProperty("sync", "false").trim();
275         syncFlag = Boolean.parseBoolean(syncF);
276         if (syncFlag) {
277             PolicyLogger.info("SYNC Flag is turned ON. DB will be given Priority.");
278         }
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;
284         }
285         brmsdependencyversion = brmsdependencyversion.trim();
286         readGroups(config);
287
288         // Setup Publisher
289         notificationType = config.getProperty("NOTIFICATION_TYPE");
290         if ("dmaap".equalsIgnoreCase(notificationType)) {
291
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();
298
299             if (dmaapServers == null || pubTopic == null) {
300                 LOGGER.error(
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 ");
304             }
305
306             dmaapServers = dmaapServers.trim();
307             pubTopic = pubTopic.trim();
308
309             if (dmaapServers.contains(",")) {
310                 dmaapList = new ArrayList<>(Arrays.asList(dmaapServers.split("\\s*,\\s*")));
311             } else {
312                 dmaapList = new ArrayList<>();
313                 dmaapList.add(dmaapServers);
314             }
315
316             this.publisher =
317                     new BusPublisher.DmaapPublisherWrapper(this.dmaapList, this.pubTopic, aafLogin, aafPassword);
318
319             String notificationDelay = config.getProperty("NOTIFICATION_DELAY");
320             if (notificationDelay != null && !notificationDelay.isEmpty()) {
321                 notificationDelay = notificationDelay.trim();
322                 try {
323                     dmaapDelay = Long.parseLong(notificationDelay);
324                 } catch (final NumberFormatException e) {
325                     LOGGER.error("DMAAP_DELAY not a long format number" + e);
326                 }
327             }
328             LOGGER.info("DMAAP BusPublisher is created.");
329
330         } else {
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) {
336                 LOGGER.error(
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 ");
340             }
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);
351             }
352             String notificationDelay = config.getProperty("NOTIFICATION_DELAY");
353             if (notificationDelay != null && !notificationDelay.isEmpty()) {
354                 notificationDelay = notificationDelay.trim();
355                 try {
356                     uebDelay = Long.parseLong(notificationDelay);
357                 } catch (final NumberFormatException e) {
358                     LOGGER.error("UEB_DELAY not a long format number" + e);
359                 }
360             }
361             LOGGER.info("UEB PublisherBuilder is created.");
362
363         }
364
365     }
366
367     private static void setBackupMonitor(final BackUpMonitor instance) {
368         bm = instance;
369     }
370
371     private static void setIntegrityMonitor(final IntegrityMonitor instance) {
372         im = instance;
373     }
374
375     /**
376      * Will Initialize the variables required for BRMSPush.
377      */
378     public void initiate(final boolean flag) {
379         resetModifiedGroups();
380         controllers = new ArrayList<>();
381         try {
382             bm.updateNotification();
383         } catch (final Exception e) {
384             LOGGER.error("Error while updating Notification: " + e.getMessage(), e);
385         }
386         if (flag) {
387             syncGroupInfo();
388         }
389     }
390
391     public void resetDs() {
392         resetModifiedGroups();
393         controllers = new ArrayList<>();
394     }
395
396     private static void resetModifiedGroups() {
397         modifiedGroups = new HashMap<>();
398     }
399
400     /**
401      * Will Add rules to projects. Creates necessary folders if required.
402      */
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
406         // 3 create pom.
407         // 4 copy the rule.
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;
420                 }
421                 // kmodule configurations
422                 else if ("kSessionName".equals(key)) {
423                     ksessionName = value;
424                 }
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);
430                 }
431             }
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;
438             }
439         }
440         // If no Match then pick Default.
441         if (selectedName == null) {
442             selectedName = defaultName;
443         }
444         if (groupMap.containsKey(selectedName)) {
445             // If the key is not got as parameters set by the user, setting the default value for
446             // kSessionName as
447             // closedLoop
448             if (ksessionName == null) {
449                 LOGGER.info("kSessionName is null, selectedName is  : " + selectedName);
450                 if (selectedName.equalsIgnoreCase(defaultName)) {
451                     ksessionName = "closedloop";
452                 } else {
453                     ksessionName = "closedloop-" + selectedName;
454                 }
455             }
456             // create directories if missing.
457             manageProject(selectedName, ksessionName, name, rule);
458
459             // Will check for Create Later after generating the Pom.
460             addModifiedGroup(selectedName, "update");
461         }
462     }
463
464     private String getUserControllerName(final String key, final String value) {
465         String userControllerName = null;
466         // Check User Specific values.
467         try {
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);
474         }
475         return userControllerName;
476     }
477
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) {
483             try {
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);
487             }
488         }
489     }
490
491     private void syncGroupInfo() {
492         // Sync DB to JMemory.
493         final EntityTransaction et = em.getTransaction();
494         try {
495             et.begin();
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);
508                 }
509             }
510
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());
518                 }
519             }
520             et.commit();
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);
524             et.rollback();
525             throw exception;
526         }
527     }
528
529     private void manageProject(final String selectedName, final String ksessionName, final String name,
530             final String rule) {
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
537                 + ".drl", rule);
538         addToPolicy(name, selectedName);
539     }
540
541     /*
542      * Add Policy to JMemory and DataBase.
543      */
544     private void addToPolicy(final String policyName, final String controllerName) {
545
546         final EntityTransaction et = em.getTransaction();
547         try {
548             et.begin();
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()) {
556                 // Already exists.
557                 brmsPolicyInfo = policyInfoResultList.get(0);
558                 if (!brmsPolicyInfo.getControllerName().getControllerName().equals(controllerName)) {
559                     create = true;
560                 }
561             } else {
562                 create = true;
563             }
564             if (create) {
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);
572                 }
573                 brmsPolicyInfo.setPolicyName(policyName);
574                 brmsPolicyInfo.setControllerName(brmsGroupInfo);
575                 em.persist(brmsPolicyInfo);
576                 em.flush();
577             }
578             et.commit();
579
580             policyMap.put(policyName, controllerName);
581         } catch (final Exception exception) {
582             LOGGER.error("Unable add policy to database", exception);
583             et.rollback();
584             throw exception;
585         }
586     }
587
588     private void syncProject(final String selectedName) {
589         final boolean projectExists = checkProject(selectedName);
590         if (projectExists) {
591             String version;
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;
597             }
598             final String nextVersion = incrementVersion(version);
599             final boolean outOfSync = checkRemoteSync(selectedName, nextVersion);
600             if (!outOfSync) {
601                 return;
602             }
603         }
604         // We are out of Sync or Project is not Present.
605         downloadProject(selectedName);
606     }
607
608     private void downloadProject(final String selectedName) {
609         final NexusArtifact artifact = getLatestArtifactFromNexus(selectedName);
610         if (artifact == null) {
611             return;
612         }
613         final String dirName = getDirectoryName(selectedName);
614         URL website;
615         final String fileName = "rule.jar";
616         try {
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);
625             }
626
627         } catch (final IOException e1) {
628             LOGGER.error("Error while retrieve the artifact. " + e1.getMessage(), e1);
629         }
630     }
631
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);
637             }
638         } catch (final IOException e) {
639             LOGGER.info("exception Occured" + e);
640         }
641     }
642
643     private void parseJarContents(final String artifactId, final JarFile jar, final Enumeration<?> enumEntries) {
644         final JarEntry jarEntry = (JarEntry) enumEntries.nextElement();
645         File file = null;
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);
653             } else {
654                 file = new File(path + File.separator + fileName);
655             }
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);
665         }
666         if (file != null) {
667             try (InputStream is = jar.getInputStream(jarEntry); FileOutputStream fos = new FileOutputStream(file)) {
668                 while (is.available() > 0) {
669                     fos.write(is.read());
670                 }
671                 LOGGER.info(fileName + " Created..");
672             } catch (final IOException e) {
673                 LOGGER.info("exception Occured" + e);
674             }
675         }
676     }
677
678     private NexusArtifact getLatestArtifactFromNexus(final String selectedName) {
679         final List<NexusArtifact> artifacts = getArtifactFromNexus(selectedName, null);
680         int bigNum = 0;
681         int smallNum = 0;
682         NexusArtifact result = null;
683         for (final NexusArtifact artifact : artifacts) {
684             final int majorVal =
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) {
689                 bigNum = majorVal;
690                 smallNum = minorVal;
691             }
692             if ((bigNum == majorVal) && (minorVal > smallNum)) {
693                 smallNum = minorVal;
694             }
695             if (bigNum == majorVal && minorVal == smallNum) {
696                 result = artifact;
697             }
698         }
699         return additionalNexusLatestCheck(selectedName, result);
700     }
701
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) {
705             return result;
706         }
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));
710     }
711
712     private boolean checkRemoteSync(final String selectedName, final String version) {
713         final List<NexusArtifact> artifacts = getArtifactFromNexus(selectedName, version);
714         return artifacts.isEmpty() ? false : true;
715     }
716
717     private List<NexusArtifact> getArtifactFromNexus(final String selectedName, final String version) {
718         NexusRestWrapper restWrapper = null;
719         int index = 0;
720         boolean flag = false;
721         while (index < repUrlList.size()) {
722             try {
723                 final String repUrl = repUrlList.get(0);
724                 restWrapper =
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,
729                         null);
730
731                 final List<NexusArtifact> resultList = restWrapper.findArtifact(searchParameters).getArtifactList();
732                 if (resultList != null) {
733                     flag = true;
734                     return resultList;
735                 }
736             } catch (NexusRestWrapperException | ProcessingException e) {
737                 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Connection to remote Nexus has failed. "
738                         + e.getMessage(), e);
739             } finally {
740                 if (null != restWrapper) {
741                     restWrapper.close();
742                 }
743                 if (!flag) {
744                     Collections.rotate(repUrlList, -1);
745                     index++;
746                 }
747             }
748         }
749         return new ArrayList<>();
750     }
751
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(".")));
755         if (minorVal >= 9) {
756             majorVal += 1;
757             minorVal = 0;
758         } else {
759             minorVal += 1;
760         }
761         return majorVal + "." + minorVal + version.substring(version.lastIndexOf("."));
762     }
763
764     private boolean checkProject(final String selectedName) {
765         return new File(PROJECTSLOCATION + File.separator + getDirectoryName(selectedName)).exists();
766     }
767
768     private String getDirectoryName(final String selectedName) {
769         return getArtifactId(selectedName);
770     }
771
772     /**
773      * Will Push policies to the PolicyRepo.
774      *
775      * @throws PolicyException PolicyException related to the operation
776      */
777     public void pushRules() throws PolicyException {
778         // Check how many groups have been updated.
779         // Invoke their Maven process.
780         try {
781             im.startTransaction();
782         } catch (final Exception e) {
783             LOGGER.error("Error while starting Transaction " + e);
784         }
785         if (!modifiedGroups.isEmpty()) {
786             if (buildAndGenerateJarFile()) {
787                 sendNotification(controllers);
788             }
789         }
790         if (im != null) {
791             im.endTransaction();
792         }
793     }
794
795     /**
796      * Removes a Rule from Rule Projects.
797      */
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);
802             return;
803         }
804         syncProject(controllerName);
805         getNameAndSetRemove(controllerName, name);
806     }
807
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();
813             try {
814                 LOGGER.info("PushRules: ModifiedGroups, Key: " + group + ", Value: " + entry.getValue());
815                 final InvocationRequest request = new DefaultInvocationRequest();
816                 setVersion(group);
817                 createPom(group);
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..!");
827                 }
828             } catch (final Exception e) {
829                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation issue for "
830                         + getArtifactId(group) + e.getMessage(), e);
831             }
832             if (result != null && result.getExitCode() == 0) {
833                 LOGGER.info("Build Completed..!");
834                 if (createFlag) {
835                     addNotification(group, "create");
836                 } else {
837                     addNotification(group, entry.getValue());
838                 }
839                 flag = true;
840             } else {
841                 throw new PolicyException(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation failure!");
842             }
843         }
844         return flag;
845     }
846
847     private String getGroupName(final String name) {
848         if (policyMap.containsKey(name)) {
849             return policyMap.get(name);
850         } else {
851             syncGroupInfo();
852             return policyMap.containsKey(name) ? policyMap.get(name) : null;
853         }
854     }
855
856     private void addModifiedGroup(final String controllerName, final String operation) {
857         if (controllerName != null) {
858             modifiedGroups.put(controllerName, operation);
859         }
860     }
861
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);
872         try {
873             LOGGER.debug("Notification added: " + PolicyUtils.objectToJsonString(controllerPojo));
874         } catch (final JsonProcessingException e) {
875             LOGGER.error(MessageCodes.ERROR_SCHEMA_INVALID + "Json Processing Error " + e);
876         }
877     }
878
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);
887     }
888
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);
896         try {
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);
903         }
904     }
905
906     private void sendMessage(final String message) throws IOException, GeneralSecurityException, InterruptedException {
907
908         if ("dmaap".equalsIgnoreCase(notificationType)) {
909             // Sending Message through DMaaP Message Router
910             LOGGER.debug("DMAAP Publishing Message");
911
912             publisher.send("MyPartitionKey", message);
913
914             LOGGER.debug("Message Published on DMaaP :" + dmaapList.get(0) + "for Topic: " + pubTopic);
915
916             Thread.sleep(dmaapDelay);
917             publisher.close();
918         } else {
919             // Sending Message through UEB interface.
920             LOGGER.debug("UEB Publishing Message");
921
922             final CambriaBatchingPublisher pub = pubBuilder.build();
923             pub.send("MyPartitionKey", message);
924
925             final List<?> stuck = pub.close(uebDelay, TimeUnit.SECONDS);
926             if (!stuck.isEmpty()) {
927                 LOGGER.error(stuck.size() + " messages unsent");
928             } else {
929                 LOGGER.debug("Clean exit; Message Published on UEB : " + uebList + "for Topic: " + pubTopic);
930             }
931         }
932
933     }
934
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));
941         model.setName(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());
956             }
957         } else {
958             // Add Default dependencies.
959             dependencyList = getDependencies(name);
960         }
961         model.setDependencies(dependencyList);
962         Writer writer = null;
963         try {
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);
971         } finally {
972             IOUtil.close(writer);
973         }
974     }
975
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)) {
980             try {
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;
987                 }
988                 final List<Dependency> dependencyList = new ArrayList<>();
989                 for (final PEDependency dependency : dependencyInfo.getDependencies().get(controller)) {
990                     dependencyList.add(dependency.getDependency());
991                 }
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);
997             }
998         }
999         return defaultDependencies(controllerName);
1000     }
1001
1002     /**
1003      * Default Dependency Section. Can be changed as required.
1004      *
1005      * @param controllerName the controller name
1006      * @return changed dependency list
1007      */
1008     public List<Dependency> defaultDependencies(final String controllerName) {
1009
1010         final List<Dependency> dependencyList = new ArrayList<>();
1011         final String version = StringEscapeUtils.escapeJava(brmsdependencyversion);
1012
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);
1018
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);
1024
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);
1030
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);
1036
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);
1042
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);
1048
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;
1055     }
1056
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);
1067         }
1068     }
1069
1070     private void copyDataToFile(final String file, final String rule) {
1071         try {
1072             FileUtils.writeStringToFile(new File(file), rule);
1073         } catch (final Exception e) {
1074             LOGGER.error(
1075                     XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while creating Rule for " + file + e.getMessage(),
1076                     e);
1077         }
1078     }
1079
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);
1085         }
1086         if (config.getProperty(GROUP_NAMES).contains(",")) {
1087             groupNames = config.getProperty(GROUP_NAMES).replaceAll(" ", "").split(",");
1088         } else {
1089             groupNames = new String[] { config.getProperty(GROUP_NAMES).replaceAll(" ", "") };
1090         }
1091         if (groupNames == null || groupNames.length == 0) {
1092             LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + groupNamesError);
1093             throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + groupNamesError);
1094         }
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 ");
1104             }
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 ");
1111             }
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);
1117         }
1118     }
1119
1120     private void addToGroup(final String name, final PEDependency dependency) {
1121         final EntityTransaction et = em.getTransaction();
1122         try {
1123             et.begin();
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);
1132             }
1133             if (brmsGroupInfo == null) {
1134                 brmsGroupInfo = new BrmsGroupInfo();
1135             }
1136             brmsGroupInfo.setControllerName(name);
1137             brmsGroupInfo.setGroupId(dependency.getGroupId());
1138             brmsGroupInfo.setArtifactId(dependency.getArtifactId());
1139             brmsGroupInfo.setVersion(dependency.getVersion());
1140             em.persist(brmsGroupInfo);
1141             em.flush();
1142             et.commit();
1143
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);
1149             et.rollback();
1150             throw exception;
1151         }
1152     }
1153
1154     private String getArtifactId(final String name) {
1155         return ((PEDependency) groupMap.get(name).get(0)).getArtifactId();
1156     }
1157
1158     private String getGroupId(final String name) {
1159         return ((PEDependency) groupMap.get(name).get(0)).getGroupId();
1160     }
1161
1162     private String getVersion(final String name) {
1163         return ((PEDependency) groupMap.get(name).get(0)).getVersion();
1164     }
1165
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);
1174         }
1175         if (new File(ruleFolder).listFiles().length == 0) {
1176             removedRuleModifiedGroup(controllerName);
1177         } else {
1178             // This is an update in terms of PDPD.
1179             addModifiedGroup(controllerName, "update");
1180         }
1181     }
1182
1183     // Removes Policy from Memory and Database.
1184     private void removePolicyFromGroup(final String policyName, final String controllerName) {
1185         final EntityTransaction et = em.getTransaction();
1186         try {
1187             et.begin();
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()) {
1194                 // Already exists.
1195                 brmsPolicyInfo = pList.get(0);
1196                 if (brmsPolicyInfo.getControllerName().getControllerName().equals(controllerName)) {
1197                     em.remove(brmsPolicyInfo);
1198                     em.flush();
1199                 }
1200             }
1201             et.commit();
1202             policyMap.remove(policyName);
1203         } catch (final Exception exception) {
1204             LOGGER.error("Unable remove policy from group to database for policy name: " + policyName, exception);
1205             et.rollback();
1206             throw exception;
1207         }
1208     }
1209
1210     private void setVersion(final String selectedName) {
1211         String newVersion = VERSION_0_1_0;
1212         createFlag = false;
1213         final NexusArtifact artifact = getLatestArtifactFromNexus(selectedName);
1214         if (artifact != null) {
1215             newVersion = incrementVersion(artifact.getVersion());
1216         }
1217         if (VERSION_0_1_0.equals(newVersion)) {
1218             createFlag = true;
1219         }
1220         setVersion(newVersion, selectedName);
1221         LOGGER.info("Controller: " + selectedName + "is on version: " + newVersion);
1222     }
1223
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);
1228     }
1229
1230     // Return BackUpMonitor
1231     public static BackUpMonitor getBackUpMonitor() {
1232         return bm;
1233     }
1234
1235     /**
1236      * Rotate URLs list.
1237      */
1238     public void rotateUrls() {
1239         if (repUrlList != null) {
1240             Collections.rotate(repUrlList, -1);
1241         }
1242     }
1243
1244     /**
1245      * Get URL List Size.
1246      *
1247      * @return URL list size
1248      */
1249     public int urlListSize() {
1250         return repUrlList != null ? repUrlList.size() : 0;
1251     }
1252 }