Update Policy Engine to 1.2.3-SNAPSHOT
[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  * ================================================================================
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.onap.policy.brms.api;
22
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;
27
28 import java.io.File;
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;
34 import java.net.URL;
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;
48 import java.util.Map;
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;
55
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;
62
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;
76
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).
101  * Mavenize and push policy 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.2.3";
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);
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                 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                     try {
428                         final PEDependency dependency = PolicyUtils.jsonStringToObject(value, PEDependency.class);
429                         userControllerName = key.replaceFirst("$controller:", "");
430                         LOGGER.info("addRule: userControllerName - " + userControllerName + ", dependency: - "
431                                 + dependency);
432                         addToGroup(userControllerName, dependency);
433                     } catch (final Exception e) {
434                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while resolving Controller: " + e);
435                     }
436
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) {
441                         try {
442                             userDependencies.add(PolicyUtils.jsonStringToObject(dependencyString, PEDependency.class));
443                         } catch (final Exception e) {
444                             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while resolving Dependencies: "
445                                     + e);
446                         }
447                     }
448                 }
449             }
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;
456             }
457         }
458         // If no Match then pick Default.
459         if (selectedName == null) {
460             selectedName = defaultName;
461         }
462         if (groupMap.containsKey(selectedName)) {
463             // If the key is not got as parameters set by the user, setting the default value for
464             // kSessionName as
465             // closedLoop
466             if (ksessionName == null) {
467                 LOGGER.info("kSessionName is null, selectedName is  : " + selectedName);
468                 if (selectedName.equalsIgnoreCase(defaultName)) {
469                     ksessionName = "closedloop";
470                 } else {
471                     ksessionName = "closedloop-" + selectedName;
472                 }
473             }
474             // create directories if missing.
475             manageProject(selectedName, ksessionName, name, rule);
476
477             // Will check for Create Later after generating the Pom.
478             addModifiedGroup(selectedName, "update");
479         }
480     }
481
482     private void syncGroupInfo() {
483         // Sync DB to JMemory.
484         final EntityTransaction et = em.getTransaction();
485         try {
486             et.begin();
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);
499                 }
500             }
501
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());
509                 }
510             }
511             et.commit();
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);
515             et.rollback();
516             throw exception;
517         }
518     }
519
520     private void manageProject(final String selectedName, final String ksessionName, final String name,
521             final String rule) {
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
528                 + ".drl", rule);
529         addToPolicy(name, selectedName);
530     }
531
532     /*
533      * Add Policy to JMemory and DataBase.
534      */
535     private void addToPolicy(final String policyName, final String controllerName) {
536
537         final EntityTransaction et = em.getTransaction();
538         try {
539             et.begin();
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()) {
547                 // Already exists.
548                 brmsPolicyInfo = policyInfoResultList.get(0);
549                 if (!brmsPolicyInfo.getControllerName().getControllerName().equals(controllerName)) {
550                     create = true;
551                 }
552             } else {
553                 create = true;
554             }
555             if (create) {
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);
563                 }
564                 brmsPolicyInfo.setPolicyName(policyName);
565                 brmsPolicyInfo.setControllerName(brmsGroupInfo);
566                 em.persist(brmsPolicyInfo);
567                 em.flush();
568             }
569             et.commit();
570
571             policyMap.put(policyName, controllerName);
572         } catch (final Exception exception) {
573             LOGGER.error("Unable add policy to database", exception);
574             et.rollback();
575             throw exception;
576         }
577     }
578
579     private void syncProject(final String selectedName) {
580         final boolean projectExists = checkProject(selectedName);
581         if (projectExists) {
582             String version;
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;
588             }
589             final String nextVersion = incrementVersion(version);
590             final boolean outOfSync = checkRemoteSync(selectedName, nextVersion);
591             if (!outOfSync) {
592                 return;
593             }
594         }
595         // We are out of Sync or Project is not Present.
596         downloadProject(selectedName);
597     }
598
599     private void downloadProject(final String selectedName) {
600         final NexusArtifact artifact = getLatestArtifactFromNexus(selectedName);
601         if (artifact == null) {
602             return;
603         }
604         final String dirName = getDirectoryName(selectedName);
605         URL website;
606         final String fileName = "rule.jar";
607         try {
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);
616             }
617
618         } catch (final IOException e1) {
619             LOGGER.error("Error while retrieve the artifact. " + e1.getMessage(), e1);
620         }
621     }
622
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();
628                 File file = null;
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);
636                     } else {
637                         file = new File(path + File.separator + fileName);
638                     }
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);
648                 }
649                 if (file != null) {
650                     try (InputStream is = jar.getInputStream(jarEntry);
651                             FileOutputStream fos = new FileOutputStream(file)) {
652                         while (is.available() > 0) {
653                             fos.write(is.read());
654                         }
655                         LOGGER.info(fileName + " Created..");
656                     } catch (final IOException e) {
657                         LOGGER.info("exception Occured" + e);
658                     }
659                 }
660             }
661         } catch (final IOException e) {
662             LOGGER.info("exception Occured" + e);
663         }
664     }
665
666     private NexusArtifact getLatestArtifactFromNexus(final String selectedName) {
667         final List<NexusArtifact> artifacts = getArtifactFromNexus(selectedName, null);
668         int bigNum = 0;
669         int smallNum = 0;
670         NexusArtifact result = null;
671         for (final NexusArtifact artifact : artifacts) {
672             final int majorVal =
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) {
677                 bigNum = majorVal;
678                 smallNum = minorVal;
679             }
680             if ((bigNum == majorVal) && (minorVal > smallNum)) {
681                 smallNum = minorVal;
682             }
683             if (bigNum == majorVal && minorVal == smallNum) {
684                 result = artifact;
685             }
686         }
687         return additionalNexusLatestCheck(selectedName, result);
688     }
689
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) {
693             return result;
694         }
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));
698     }
699
700     private boolean checkRemoteSync(final String selectedName, final String version) {
701         final List<NexusArtifact> artifacts = getArtifactFromNexus(selectedName, version);
702         return artifacts.isEmpty() ? false : true;
703     }
704
705     private List<NexusArtifact> getArtifactFromNexus(final String selectedName, final String version) {
706         NexusRestWrapper restWrapper = null;
707         int index = 0;
708         boolean flag = false;
709         while (index < repUrlList.size()) {
710             try {
711                 final String repUrl = repUrlList.get(0);
712                 restWrapper =
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,
717                         null);
718
719                 final List<NexusArtifact> resultList = restWrapper.findArtifact(searchParameters).getArtifactList();
720                 if (resultList != null) {
721                     flag = true;
722                     return resultList;
723                 }
724             } catch (NexusRestWrapperException | ProcessingException e) {
725                 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Connection to remote Nexus has failed. "
726                         + e.getMessage(), e);
727             } finally {
728                 if (null != restWrapper) {
729                     restWrapper.close();
730                 }
731                 if (!flag) {
732                     Collections.rotate(repUrlList, -1);
733                     index++;
734                 }
735             }
736         }
737         return new ArrayList<>();
738     }
739
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(".")));
743         if (minorVal >= 9) {
744             majorVal += 1;
745             minorVal = 0;
746         } else {
747             minorVal += 1;
748         }
749         return majorVal + "." + minorVal + version.substring(version.lastIndexOf("."));
750     }
751
752     private boolean checkProject(final String selectedName) {
753         return new File(PROJECTSLOCATION + File.separator + getDirectoryName(selectedName)).exists();
754     }
755
756     private String getDirectoryName(final String selectedName) {
757         return getArtifactId(selectedName);
758     }
759
760     /**
761      * Will Push policies to the PolicyRepo.
762      * 
763      * @throws PolicyException PolicyException related to the operation
764      */
765     public void pushRules() throws PolicyException {
766         // Check how many groups have been updated.
767         // Invoke their Maven process.
768         try {
769             im.startTransaction();
770         } catch (final Exception e) {
771             LOGGER.error("Error while starting Transaction " + e);
772         }
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();
778                 try {
779                     LOGGER.info("PushRules: ModifiedGroups, Key: " + group + ", Value: " + entry.getValue());
780                     final InvocationRequest request = new DefaultInvocationRequest();
781                     setVersion(group);
782                     createPom(group);
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..!");
792                     }
793                 } catch (final Exception e) {
794                     LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation issue for "
795                             + getArtifactId(group) + e.getMessage(), e);
796                 }
797                 if (result != null && result.getExitCode() == 0) {
798                     LOGGER.info("Build Completed..!");
799                     if (createFlag) {
800                         addNotification(group, "create");
801                     } else {
802                         addNotification(group, entry.getValue());
803                     }
804                     flag = true;
805                 } else {
806                     throw new PolicyException(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation failure!");
807                 }
808             }
809             if (flag) {
810                 sendNotification(controllers);
811             }
812         }
813         if (im != null) {
814             im.endTransaction();
815         }
816     }
817
818     /**
819      * Removes a Rule from Rule Projects.
820      */
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);
825             return;
826         }
827         syncProject(controllerName);
828         getNameAndSetRemove(controllerName, name);
829     }
830
831     private String getGroupName(final String name) {
832         if (policyMap.containsKey(name)) {
833             return policyMap.get(name);
834         } else {
835             syncGroupInfo();
836             return policyMap.containsKey(name) ? policyMap.get(name) : null;
837         }
838     }
839
840     private void addModifiedGroup(final String controllerName, final String operation) {
841         if (controllerName != null) {
842             modifiedGroups.put(controllerName, operation);
843         }
844     }
845
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);
856         try {
857             LOGGER.debug("Notification added: " + PolicyUtils.objectToJsonString(controllerPojo));
858         } catch (final JsonProcessingException e) {
859             LOGGER.error(MessageCodes.ERROR_SCHEMA_INVALID + "Json Processing Error " + e);
860         }
861     }
862
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);
871     }
872
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);
880         try {
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);
887         }
888     }
889
890     private void sendMessage(final String message) throws IOException, GeneralSecurityException, InterruptedException {
891
892         if ("dmaap".equalsIgnoreCase(notificationType)) {
893             // Sending Message through DMaaP Message Router
894             LOGGER.debug("DMAAP Publishing Message");
895
896             publisher.send("MyPartitionKey", message);
897
898             LOGGER.debug("Message Published on DMaaP :" + dmaapList.get(0) + "for Topic: " + pubTopic);
899
900             Thread.sleep(dmaapDelay);
901             publisher.close();
902         } else {
903             // Sending Message through UEB interface.
904             LOGGER.debug("UEB Publishing Message");
905
906             final CambriaBatchingPublisher pub = pubBuilder.build();
907             pub.send("MyPartitionKey", message);
908
909             final List<?> stuck = pub.close(uebDelay, TimeUnit.SECONDS);
910             if (!stuck.isEmpty()) {
911                 LOGGER.error(stuck.size() + " messages unsent");
912             } else {
913                 LOGGER.debug("Clean exit; Message Published on UEB : " + uebList + "for Topic: " + pubTopic);
914             }
915         }
916
917     }
918
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));
925         model.setName(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());
940             }
941         } else {
942             // Add Default dependencies.
943             dependencyList = getDependencies(name);
944         }
945         model.setDependencies(dependencyList);
946         Writer writer = null;
947         try {
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);
955         } finally {
956             IOUtil.close(writer);
957         }
958     }
959
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)) {
964             try {
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;
971                 }
972                 final List<Dependency> dependencyList = new ArrayList<>();
973                 for (final PEDependency dependency : dependencyInfo.getDependencies().get(controller)) {
974                     dependencyList.add(dependency.getDependency());
975                 }
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);
981             }
982         }
983         return defaultDependencies(controllerName);
984     }
985
986     /**
987      * Default Dependency Section. Can be changed as required.
988      * 
989      * @param controllerName the controller name
990      * @return changed dependency list
991      */
992     public List<Dependency> defaultDependencies(final String controllerName) {
993
994         final List<Dependency> dependencyList = new ArrayList<>();
995         final String version = StringEscapeUtils.escapeJava(brmsdependencyversion);
996
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);
1002
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);
1008
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);
1014
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);
1020
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);
1026
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);
1032
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;
1039     }
1040
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);
1051         }
1052     }
1053
1054     private void copyDataToFile(final String file, final String rule) {
1055         try {
1056             FileUtils.writeStringToFile(new File(file), rule);
1057         } catch (final Exception e) {
1058             LOGGER.error(
1059                     XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while creating Rule for " + file + e.getMessage(),
1060                     e);
1061         }
1062     }
1063
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);
1069         }
1070         if (config.getProperty(GROUP_NAMES).contains(",")) {
1071             groupNames = config.getProperty(GROUP_NAMES).replaceAll(" ", "").split(",");
1072         } else {
1073             groupNames = new String[] {config.getProperty(GROUP_NAMES).replaceAll(" ", "")};
1074         }
1075         if (groupNames == null || groupNames.length == 0) {
1076             LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + groupNamesError);
1077             throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + groupNamesError);
1078         }
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 ");
1088             }
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 ");
1095             }
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);
1101         }
1102     }
1103
1104     private void addToGroup(final String name, final PEDependency dependency) {
1105         final EntityTransaction et = em.getTransaction();
1106         try {
1107             et.begin();
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);
1116             }
1117             if (brmsGroupInfo == null) {
1118                 brmsGroupInfo = new BrmsGroupInfo();
1119             }
1120             brmsGroupInfo.setControllerName(name);
1121             brmsGroupInfo.setGroupId(dependency.getGroupId());
1122             brmsGroupInfo.setArtifactId(dependency.getArtifactId());
1123             brmsGroupInfo.setVersion(dependency.getVersion());
1124             em.persist(brmsGroupInfo);
1125             em.flush();
1126             et.commit();
1127
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);
1133             et.rollback();
1134             throw exception;
1135         }
1136     }
1137
1138     private String getArtifactId(final String name) {
1139         return ((PEDependency) groupMap.get(name).get(0)).getArtifactId();
1140     }
1141
1142     private String getGroupId(final String name) {
1143         return ((PEDependency) groupMap.get(name).get(0)).getGroupId();
1144     }
1145
1146     private String getVersion(final String name) {
1147         return ((PEDependency) groupMap.get(name).get(0)).getVersion();
1148     }
1149
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);
1158         }
1159         if (new File(ruleFolder).listFiles().length == 0) {
1160             removedRuleModifiedGroup(controllerName);
1161         } else {
1162             // This is an update in terms of PDPD.
1163             addModifiedGroup(controllerName, "update");
1164         }
1165     }
1166
1167     // Removes Policy from Memory and Database.
1168     private void removePolicyFromGroup(final String policyName, final String controllerName) {
1169         final EntityTransaction et = em.getTransaction();
1170         try {
1171             et.begin();
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()) {
1178                 // Already exists.
1179                 brmsPolicyInfo = pList.get(0);
1180                 if (brmsPolicyInfo.getControllerName().getControllerName().equals(controllerName)) {
1181                     em.remove(brmsPolicyInfo);
1182                     em.flush();
1183                 }
1184             }
1185             et.commit();
1186             policyMap.remove(policyName);
1187         } catch (final Exception exception) {
1188             LOGGER.error("Unable remove policy from group to database for policy name: " + policyName, exception);
1189             et.rollback();
1190             throw exception;
1191         }
1192     }
1193
1194     private void setVersion(final String selectedName) {
1195         String newVersion = VERSION_0_1_0;
1196         createFlag = false;
1197         final NexusArtifact artifact = getLatestArtifactFromNexus(selectedName);
1198         if (artifact != null) {
1199             newVersion = incrementVersion(artifact.getVersion());
1200         }
1201         if (VERSION_0_1_0.equals(newVersion)) {
1202             createFlag = true;
1203         }
1204         setVersion(newVersion, selectedName);
1205         LOGGER.info("Controller: " + selectedName + "is on version: " + newVersion);
1206     }
1207
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);
1212     }
1213
1214     // Return BackUpMonitor
1215     public static BackUpMonitor getBackUpMonitor() {
1216         return bm;
1217     }
1218
1219     /**
1220      * Rotate URLs list.
1221      */
1222     public void rotateUrls() {
1223         if (repUrlList != null) {
1224             Collections.rotate(repUrlList, -1);
1225         }
1226     }
1227
1228     /**
1229      * Get URL List Size.
1230      * 
1231      * @return URL list size
1232      */
1233     public int urlListSize() {
1234         return repUrlList != null ? repUrlList.size() : 0;
1235     }
1236 }