Policy:Blocker
[policy/engine.git] / BRMSGateway / src / main / java / org / onap / policy / brmsInterface / 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.brmsInterface;
22
23 import java.io.File;
24 import java.io.FileInputStream;
25 import java.io.FileOutputStream;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.Writer;
29 import java.net.URL;
30 import java.nio.channels.Channels;
31 import java.nio.channels.ReadableByteChannel;
32 import java.nio.charset.StandardCharsets;
33 import java.nio.file.Files;
34 import java.nio.file.Path;
35 import java.nio.file.Paths;
36 import java.security.GeneralSecurityException;
37 import java.util.ArrayList;
38 import java.util.Arrays;
39 import java.util.Collections;
40 import java.util.Enumeration;
41 import java.util.HashMap;
42 import java.util.List;
43 import java.util.Map;
44 import java.util.Properties;
45 import java.util.UUID;
46 import java.util.concurrent.TimeUnit;
47 import java.util.jar.JarEntry;
48 import java.util.jar.JarFile;
49
50 import javax.persistence.EntityManager;
51 import javax.persistence.EntityManagerFactory;
52 import javax.persistence.EntityTransaction;
53 import javax.persistence.Persistence;
54 import javax.persistence.Query;
55
56 import org.apache.commons.io.FileUtils;
57 import org.apache.commons.lang.StringEscapeUtils;
58 import org.apache.maven.model.Dependency;
59 import org.apache.maven.model.DeploymentRepository;
60 import org.apache.maven.model.DistributionManagement;
61 import org.apache.maven.model.Model;
62 import org.apache.maven.model.io.xpp3.MavenXpp3Writer;
63 import org.apache.maven.shared.invoker.DefaultInvocationRequest;
64 import org.apache.maven.shared.invoker.DefaultInvoker;
65 import org.apache.maven.shared.invoker.InvocationRequest;
66 import org.apache.maven.shared.invoker.InvocationResult;
67 import org.apache.maven.shared.invoker.Invoker;
68 import org.codehaus.plexus.util.IOUtil;
69 import org.codehaus.plexus.util.WriterFactory;
70 import org.eclipse.persistence.config.PersistenceUnitProperties;
71 import org.onap.policy.api.PEDependency;
72 import org.onap.policy.api.PolicyException;
73 import org.onap.policy.brmsInterface.jpa.BRMSGroupInfo;
74 import org.onap.policy.brmsInterface.jpa.BRMSPolicyInfo;
75 import org.onap.policy.brmsInterface.jpa.DependencyInfo;
76 import org.onap.policy.common.im.IntegrityMonitor;
77 import org.onap.policy.common.logging.eelf.MessageCodes;
78 import org.onap.policy.common.logging.eelf.PolicyLogger;
79 import org.onap.policy.common.logging.flexlogger.FlexLogger;
80 import org.onap.policy.common.logging.flexlogger.Logger;
81 import org.onap.policy.utils.BackUpHandler;
82 import org.onap.policy.utils.BackUpMonitor;
83 import org.onap.policy.utils.BusPublisher;
84 import org.onap.policy.utils.PolicyUtils;
85 import org.onap.policy.xacml.api.XACMLErrorConstants;
86 import org.sonatype.nexus.client.NexusClient;
87 import org.sonatype.nexus.client.NexusClientException;
88 import org.sonatype.nexus.client.NexusConnectionException;
89 import org.sonatype.nexus.client.rest.NexusRestClient;
90 import org.sonatype.nexus.rest.model.NexusArtifact;
91
92 import com.att.nsa.cambria.client.CambriaBatchingPublisher;
93 import com.att.nsa.cambria.client.CambriaClientBuilders;
94 import com.att.nsa.cambria.client.CambriaClientBuilders.PublisherBuilder;
95 import com.fasterxml.jackson.core.JsonProcessingException;
96
97 /**
98  * BRMSPush: Application responsible to push policies to the BRMS PDP Policy Repository (PR). Mavenize and push policy
99  * to PR
100  * 
101  * @version 1.0
102  */
103
104 @SuppressWarnings("deprecation")
105 public class BRMSPush {
106     private static final String GROUP_NAMES = "groupNames";
107         private static final String DROOLS_APPS_TEMPLATE_GROUP = "org.onap.policy.drools-applications.controlloop.templates";
108         private static final String DROOLS_APPS_MODEL_GROUP    = "org.onap.policy.drools-applications.controlloop.common.model-impl";
109         private static final String META_INF = "META-INF";
110         private static final String KMODULE_XML_FILE = "kmodule.xml";
111         private static final String POM_XML_FILE = "pom.xml";
112         private static final String VERSION_0_1_0 = "0.1.0";
113         private static final String RULES = "rules";
114         private static final String RESOURCES = "resources";
115         private static final Logger LOGGER = FlexLogger.getLogger(BRMSPush.class.getName());
116     private static final String PROJECTSLOCATION = "RuleProjects";
117     private static final String[] GOALS = { "clean", "deploy" };
118     private static final String DEFAULT_VERSION = "1.2.0-SNAPSHOT";
119     private static final String DEPENDENCY_FILE = "dependency.json";
120     private static final String BRMSPERSISTENCE = "brmsEclipselink.persistencexml";
121
122     private static Map<String, String> modifiedGroups = new HashMap<>();
123     private static IntegrityMonitor im;
124     private static BackUpMonitor bm;
125     private String defaultName = null;
126     private String repID = null;
127     private String repName = null;
128     private ArrayList<String> repURLs = null;
129     private String repUserName = null;
130     private String repPassword = null;
131     private String policyKeyID = null;
132     private boolean createFlag = false;
133     private String uebList = null;
134     private List<String> dmaapList = null;
135     private String pubTopic = null;
136     private PublisherBuilder pubBuilder = null;
137     protected BusPublisher publisher = null;
138     private Long uebDelay = Long.parseLong("20");
139     private Long dmaapDelay = Long.parseLong("5000");
140     private String notificationType = null;
141     private ArrayList<ControllerPOJO> controllers;
142     private HashMap<String, ArrayList<Object>> groupMap = new HashMap<>();
143     private Map<String, String> policyMap = new HashMap<>();
144     private String brmsdependencyversion;
145     private EntityManager em;
146     private boolean syncFlag = false;
147
148     public BRMSPush(String propertiesFile, BackUpHandler handler) throws PolicyException {
149         if(propertiesFile==null || handler==null){
150             throw new PolicyException("Error no propertiesFile or handler");
151         }
152         Properties config = new Properties();
153         Path file = Paths.get(propertiesFile);
154         if (Files.notExists(file)) {
155             LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Config File doesn't Exist in the specified Path "
156                     + file.toString());
157             throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
158                     + "Config File doesn't Exist in the specified Path " + file.toString());
159         } else {
160             if (file.toString().endsWith(".properties")) {
161                 // Grab the Properties.
162                 setProperty(file, config, handler);
163             }
164         }
165     }
166
167     private void setProperty(Path file, Properties config, BackUpHandler handler) throws PolicyException {
168         InputStream in;
169         try {
170             in = new FileInputStream(file.toFile());
171             config.load(in);
172         } catch (IOException e) {
173             LOGGER.error(
174                     XACMLErrorConstants.ERROR_DATA_ISSUE + "Data/File Read Error while reading from the property file.",
175                     e);
176             throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
177                     + "Data/File Read Error while reading from the property file.");
178         }
179         LOGGER.info("Trying to set up IntegrityMonitor");
180         String resourceName = null;
181         try {
182             LOGGER.info("Trying to set up IntegrityMonitor");
183             resourceName = config.getProperty("RESOURCE_NAME");
184             if (resourceName == null) {
185                 LOGGER.warn("RESOURCE_NAME is missing setting default value. ");
186                 resourceName = "brmsgw_pdp01";
187             }
188             resourceName = resourceName.trim();
189             setIntegrityMonitor(IntegrityMonitor.getInstance(resourceName, config));
190         } catch (Exception e) {
191             LOGGER.error("Error starting Integerity Monitor: " + e);
192         }
193         LOGGER.info("Trying to set up BackUpMonitor");
194         try {
195             setBackupMonitor(BackUpMonitor.getInstance(BackUpMonitor.ResourceNode.BRMS.toString(), resourceName, config,
196                     handler));
197         } catch (Exception e) {
198             LOGGER.error("Error starting BackUpMonitor: " + e);
199         }
200         if(!config.containsKey(BRMSPERSISTENCE)){
201             config.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, "META-INF/persistenceBRMS.xml");
202         } else {
203             config.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, config.getProperty(BRMSPERSISTENCE,"META-INF/persistenceBRMS.xml"));
204         }
205         EntityManagerFactory emf = Persistence.createEntityManagerFactory("BRMSGW", config);
206         em = emf.createEntityManager();
207         defaultName = config.getProperty("defaultName");
208         if (defaultName == null) {
209             LOGGER.error(
210                     XACMLErrorConstants.ERROR_DATA_ISSUE + "defaultName property is missing from the property file ");
211             throw new PolicyException(
212                     XACMLErrorConstants.ERROR_DATA_ISSUE + "defaultName property is missing from the property file");
213         }
214         defaultName = defaultName.trim();
215         repID = config.getProperty("repositoryID");
216         if (repID == null) {
217             LOGGER.error(
218                     XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryID property is missing from the property file ");
219             throw new PolicyException(
220                     XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryID property is missing from the property file ");
221         }
222         repID = repID.trim();
223         repName = config.getProperty("repositoryName");
224         if (repName == null) {
225             LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
226                     + "repositoryName property is missing from the property file ");
227             throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
228                     + "repositoryName property is missing from the property file ");
229         }
230         repName = repName.trim();
231         String repURL = config.getProperty("repositoryURL");
232         if (repURL == null) {
233             LOGGER.error(
234                     XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryURL property is missing from the property file ");
235             throw new PolicyException(
236                     XACMLErrorConstants.ERROR_DATA_ISSUE + "repositoryURL property is missing from the property file ");
237         }
238         if (repURL.contains(",")) {
239             repURLs = new ArrayList<>(Arrays.asList(repURL.trim().split(",")));
240         } else {
241             repURLs = new ArrayList<>();
242             repURLs.add(repURL);
243         }
244         repUserName = config.getProperty("repositoryUsername");
245         repPassword = config.getProperty("repositoryPassword");
246         if (repUserName == null || repPassword == null) {
247             LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
248                     + "repostoryUserName and respositoryPassword properties are required.");
249             throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
250                     + "repostoryUserName and respositoryPassword properties are required.");
251         }
252         repUserName = repUserName.trim();
253         repPassword = repPassword.trim();
254         policyKeyID = config.getProperty("policyKeyID");
255         if (policyKeyID == null) {
256             LOGGER.error(
257                     XACMLErrorConstants.ERROR_DATA_ISSUE + "policyKeyID property is missing from the property file ");
258             throw new PolicyException(
259                     XACMLErrorConstants.ERROR_DATA_ISSUE + "policyKeyID property is missing from the property file ");
260         }
261         policyKeyID = policyKeyID.trim();
262         String syncF = config.getProperty("sync", "false").trim();
263         syncFlag = Boolean.parseBoolean(syncF);
264         if (syncFlag) {
265             PolicyLogger.info("SYNC Flag is turned ON. DB will be given Priority.");
266         }
267         brmsdependencyversion = config.getProperty("brms.dependency.version");
268         if (brmsdependencyversion == null) {
269             LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
270                     + "brmsdependencyversion property is missing from the property file, Using default Version.");
271             brmsdependencyversion = DEFAULT_VERSION;
272         }
273         brmsdependencyversion = brmsdependencyversion.trim();
274         readGroups(config);
275
276         // Setup Publisher
277         notificationType = config.getProperty("NOTIFICATION_TYPE");
278         if ("dmaap".equalsIgnoreCase(notificationType)) {
279
280             LOGGER.info("Notification Type being used is DMaaP... creating instance of BusPublisher.");
281             // Setting up the Publisher for DMaaP MR
282             String dmaapServers = config.getProperty("NOTIFICATION_SERVERS");
283             pubTopic = config.getProperty("NOTIFICATION_TOPIC");
284             String aafLogin = config.getProperty("CLIENT_ID").trim();
285             String aafPassword = config.getProperty("CLIENT_KEY").trim();
286
287             if (dmaapServers == null || pubTopic == null) {
288                 LOGGER.error(
289                         XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file ");
290                 throw new PolicyException(
291                         XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file ");
292             }
293
294             dmaapServers = dmaapServers.trim();
295             pubTopic = pubTopic.trim();
296
297             if (dmaapServers.contains(",")) {
298                 dmaapList = new ArrayList<>(Arrays.asList(dmaapServers.split("\\s*,\\s*")));
299             } else {
300                 dmaapList = new ArrayList<>();
301                 dmaapList.add(dmaapServers);
302             }
303
304             this.publisher = new BusPublisher.DmaapPublisherWrapper(this.dmaapList, this.pubTopic, aafLogin,
305                     aafPassword);
306
307             String dDelay = config.getProperty("NOTIFICATION_DELAY");
308             if (dDelay != null && !dDelay.isEmpty()) {
309                 dDelay = dDelay.trim();
310                 try {
311                     dmaapDelay = Long.parseLong(dDelay);
312                 } catch (NumberFormatException e) {
313                     LOGGER.error("DMAAP_DELAY not a long format number" + e);
314                 }
315             }
316             LOGGER.info("DMAAP BusPublisher is created.");
317
318         } else {
319             LOGGER.info("Notification Type being used is UEB... creating instance of PublisherBuilder.");
320             // Setting up the Publisher for UEB
321             uebList = config.getProperty("NOTIFICATION_SERVERS");
322             pubTopic = config.getProperty("NOTIFICATION_TOPIC");
323             String apiKey = config.getProperty("UEB_API_KEY");
324             String apiSecret = config.getProperty("UEB_API_SECRET");
325             if (uebList == null || pubTopic == null) {
326                 LOGGER.error(
327                         XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file ");
328                 throw new PolicyException(
329                         XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file ");
330             }
331             uebList = uebList.trim();
332             pubTopic = pubTopic.trim();
333             pubBuilder = new CambriaClientBuilders.PublisherBuilder();
334             pubBuilder.usingHosts(uebList).onTopic(pubTopic);
335             if (apiKey != null && !apiKey.isEmpty() && apiSecret != null && !apiSecret.isEmpty()) {
336                 apiKey = apiKey.trim();
337                 apiSecret = apiSecret.trim();
338                 pubBuilder.authenticatedBy(apiKey, apiSecret);
339             }
340             String uDelay = config.getProperty("NOTIFICATION_DELAY");
341             if (uDelay != null && !uDelay.isEmpty()) {
342                 uDelay = uDelay.trim();
343                 try {
344                     uebDelay = Long.parseLong(uDelay);
345                 } catch (NumberFormatException e) {
346                     LOGGER.error("UEB_DELAY not a long format number" + e);
347                 }
348             }
349             LOGGER.info("UEB PublisherBuilder is created.");
350
351         }
352
353     }
354
355     private static void setBackupMonitor(BackUpMonitor instance) {
356         bm = instance;
357     }
358
359     private static void setIntegrityMonitor(IntegrityMonitor instance) {
360         im = instance;
361     }
362
363     /**
364      * Will Initialize the variables required for BRMSPush.
365      */
366     public void initiate(boolean flag) {
367         resetModifiedGroups();
368         controllers = new ArrayList<>();
369         try {
370             bm.updateNotification();
371         } catch (Exception e) {
372             LOGGER.error("Error while updating Notification: " + e.getMessage(), e);
373         }
374         if (flag)
375             syncGroupInfo();
376     }
377     
378     public void resetDS(){
379         resetModifiedGroups();
380         controllers = new ArrayList<>();
381     }
382
383     private static void resetModifiedGroups() {
384         modifiedGroups = new HashMap<>();
385     }
386
387     /**
388      * Will Add rules to projects. Creates necessary folders if required.
389      */
390     public void addRule(String name, String rule, Map<String, String> responseAttributes) {
391         // 1 check the response Attributes and determine if this belongs to any projects.
392         // 2 if not create folder
393         // 3 create pom.
394         // 4 copy the rule.
395         // 5 store the groups that have been updated.
396         String kSessionName = null;
397         String selectedName = null;
398         if (!responseAttributes.isEmpty()) {
399             // Pick selected Value
400             String userControllerName = null;
401             ArrayList<PEDependency> userDependencies = new ArrayList<>();
402             for (Map.Entry<String, String> entry: responseAttributes.entrySet()) {
403                 String key = entry.getKey();
404                 String value = entry.getValue();
405                 if (key.equals(policyKeyID)) {
406                     selectedName = value;
407                 }
408                 // kmodule configurations
409                 else if ("kSessionName".equals(key)) {
410                     kSessionName = value;
411                 }
412                 // Check User Specific values.
413                 if ("$controller:".equals(key)) {
414                     try {
415                         PEDependency dependency = PolicyUtils.jsonStringToObject(value,
416                                 PEDependency.class);
417                         userControllerName = key.replaceFirst("$controller:", "");
418                         LOGGER.info("addRule: userControllerName - " + userControllerName + ", dependency: - " + dependency);
419                         addToGroup(userControllerName, dependency);
420                     } catch (Exception e) {
421                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while resolving Controller: " + e);
422                     }
423
424                 } else if ("$dependency$".equals(key) && value.startsWith("[") && value.endsWith("]")) {
425                     value = value.substring(1, value.length() - 1).trim();
426                     List<String> dependencyStrings = Arrays.asList(value.split("},{"));
427                     for (String dependencyString : dependencyStrings) {
428                         try {
429                             userDependencies
430                                     .add(PolicyUtils.jsonStringToObject(dependencyString, PEDependency.class));
431                         } catch (Exception e) {
432                             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
433                                     + "Error while resolving Dependencies: " + e);
434                         }
435                     }
436                 }
437             }
438             if (userControllerName != null) {
439                 // Adding custom dependencies here.
440                 ArrayList<Object> values = groupMap.get(userControllerName);
441                 values.add(userDependencies);
442                 groupMap.put(userControllerName, values);
443                 selectedName = userControllerName;
444             }
445         }
446         // If no Match then pick Default.
447         if (selectedName == null) {
448             selectedName = defaultName;
449         }
450         if (groupMap.containsKey(selectedName)) {
451             // If the key is not got as parameters set by the user, setting the default value for kSessionName as
452             // closedLoop
453             if (kSessionName == null) {
454                 LOGGER.info("kSessionName is null, selectedName is  : " + selectedName );
455                 if (selectedName == defaultName) {
456                     kSessionName = "closedloop";
457                 } else {
458                     kSessionName = "closedloop-" + selectedName;
459                 }
460             }
461             // create directories if missing.
462             manageProject(selectedName, kSessionName, name, rule);
463             addModifiedGroup(selectedName, "update"); // Will check for Create Later after generating the Pom.
464         }
465     }
466
467     private void syncGroupInfo() {
468         // Sync DB to JMemory.
469         EntityTransaction et = em.getTransaction();
470         et.begin();
471         Query query = em.createQuery("select b from BRMSGroupInfo AS b");
472         List<?> bList = query.getResultList();
473         if (bList.size() != groupMap.size()) {
474             for (Object value : bList) {
475                 BRMSGroupInfo brmsGroupInfo = (BRMSGroupInfo) value;
476                 PEDependency dependency = new PEDependency();
477                 dependency.setArtifactId(brmsGroupInfo.getArtifactId());
478                 dependency.setGroupId(brmsGroupInfo.getGroupId());
479                 dependency.setVersion(brmsGroupInfo.getVersion());
480                 ArrayList<Object> values = new ArrayList<>();
481                 values.add(dependency);
482                 groupMap.put(brmsGroupInfo.getControllerName(), values);
483             }
484         }
485         query = em.createQuery("select g from BRMSPolicyInfo AS g");
486         bList = query.getResultList();
487         if (bList.size() != policyMap.size()) {
488             for (Object value : bList) {
489                 BRMSPolicyInfo brmsPolicyInfo = (BRMSPolicyInfo) value;
490                 policyMap.put(brmsPolicyInfo.getPolicyName(), brmsPolicyInfo.getControllerName().getControllerName());
491             }
492         }
493         et.commit();
494         LOGGER.info("Updated Local Memory values with values from database.");
495     }
496
497     private void manageProject(String selectedName, String kSessionName, String name, String rule) {
498         // Check if the Project is in Sync. If not get the latest Version.
499         syncProject(selectedName);
500         createProject(PROJECTSLOCATION + File.separator + getArtifactID(selectedName) + File.separator + "src"
501                 + File.separator + "main" + File.separator + RESOURCES, kSessionName);
502         copyDataToFile(PROJECTSLOCATION + File.separator + getArtifactID(selectedName) + File.separator + "src"
503                 + File.separator + "main" + File.separator + RESOURCES + File.separator + RULES + File.separator
504                 + name + ".drl", rule);
505         addToPolicy(name, selectedName);
506     }
507
508     /*
509      * Add Policy to JMemory and DataBase.
510      */
511     private void addToPolicy(String policyName, String controllerName) {
512         policyMap.put(policyName, controllerName);
513         EntityTransaction et = em.getTransaction();
514         et.begin();
515         Query query = em.createQuery("select b from BRMSPolicyInfo as b where b.policyName = :pn");
516         query.setParameter("pn", policyName);
517         List<?> pList = query.getResultList();
518         boolean create = false;
519         BRMSPolicyInfo brmsPolicyInfo = new BRMSPolicyInfo();
520         if (!pList.isEmpty()) {
521             // Already exists.
522             brmsPolicyInfo = (BRMSPolicyInfo) pList.get(0);
523             if (!brmsPolicyInfo.getControllerName().getControllerName().equals(controllerName)) {
524                 create = true;
525             }
526         } else {
527             create = true;
528         }
529         if (create) {
530             query = em.createQuery("select b from BRMSGroupInfo as b where b.controllerName = :cn");
531             query.setParameter("cn", controllerName);
532             List<?> bList = query.getResultList();
533             BRMSGroupInfo brmsGroupInfo = new BRMSGroupInfo();
534             if (!bList.isEmpty()) {
535                 brmsGroupInfo = (BRMSGroupInfo) bList.get(0);
536             }
537             brmsPolicyInfo.setPolicyName(policyName);
538             brmsPolicyInfo.setControllerName(brmsGroupInfo);
539             em.persist(brmsPolicyInfo);
540             em.flush();
541         }
542         et.commit();
543     }
544
545     private void syncProject(String selectedName) {
546         boolean projectExists = checkProject(selectedName);
547         if (projectExists) {
548             String version;
549             version = getVersion(selectedName);
550             if (version == null) {
551                 LOGGER.error("Error getting local version for the given Controller Name:" + selectedName
552                         + " going with Default value");
553                 version = VERSION_0_1_0;
554             }
555             String nextVersion = incrementVersion(version);
556             boolean outOfSync = checkRemoteSync(selectedName, nextVersion);
557             if (!outOfSync) {
558                 return;
559             }
560         }
561         // We are out of Sync or Project is not Present.
562         downloadProject(selectedName);
563     }
564
565     private void downloadProject(String selectedName) {
566         NexusArtifact artifact = getLatestArtifactFromNexus(selectedName);
567         if (artifact == null)
568             return;
569         String dirName = getDirectoryName(selectedName);
570         URL website;
571         String fileName = "rule.jar";
572         try {
573             website = new URL(artifact.getResourceURI());
574             try( ReadableByteChannel rbc = Channels.newChannel(website.openStream());
575                         FileOutputStream fos = new FileOutputStream(fileName)){
576                 fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
577                 extractJar(fileName, dirName);
578                 new File(fileName).delete();
579             }catch (IOException e) {
580          LOGGER.error("Error while downloading the project to File System. " + e.getMessage(), e);
581                         }
582           
583         } catch (IOException e1) {
584             LOGGER.error("Error while retrieve the artifact. " + e1.getMessage(), e1);
585         }
586     }
587
588     private void extractJar(String jarFileName, String artifactId) throws IOException {
589         JarFile jar = new JarFile(jarFileName);
590         Enumeration<?> enumEntries = jar.entries();
591         while (enumEntries.hasMoreElements()) {
592             JarEntry file = (JarEntry) enumEntries.nextElement();
593             File f = null;
594             String fileName = file.getName().substring(file.getName().lastIndexOf("/") + 1);
595             if (file.getName().endsWith(".drl")) {
596                 String path = PROJECTSLOCATION + File.separator + artifactId + File.separator + "src" + File.separator
597                         + "main" + File.separator + RESOURCES + File.separator + RULES;
598                 new File(path).mkdirs();
599                 if (syncFlag && policyMap.containsKey(fileName.replace(".drl", ""))) {
600                     f = new File(path + File.separator + fileName);
601                 } else {
602                     f = new File(path + File.separator + fileName);
603                 }
604             } else if (file.getName().endsWith(POM_XML_FILE)) {
605                 String path = PROJECTSLOCATION + File.separator + artifactId;
606                 new File(path).mkdirs();
607                 f = new File(path + File.separator + fileName);
608             } else if (file.getName().endsWith(KMODULE_XML_FILE)) {
609                 String path = PROJECTSLOCATION + File.separator + artifactId + File.separator + "src" + File.separator
610                         + "main" + File.separator + RESOURCES + File.separator + META_INF;
611                 new File(path).mkdirs();
612                 f = new File(path + File.separator + fileName);
613             }
614             if (f != null) {
615                 InputStream is = jar.getInputStream(file);
616                 FileOutputStream fos = new FileOutputStream(f);
617                 while (is.available() > 0) {
618                     fos.write(is.read());
619                 }
620                 fos.close();
621                 is.close();
622                 LOGGER.info(fileName + " Created..");
623             }
624         }
625         jar.close();
626     }
627
628     private NexusArtifact getLatestArtifactFromNexus(String selectedName) {
629         List<NexusArtifact> artifacts = getArtifactFromNexus(selectedName, null);
630         int bigNum = 0;
631         int smallNum = 0;
632         NexusArtifact result = null;
633         for (NexusArtifact artifact : artifacts) {
634             int majorVal = Integer.parseInt(artifact.getVersion().substring(0, artifact.getVersion().indexOf(".")));
635             int minorVal = Integer.parseInt(artifact.getVersion().substring(artifact.getVersion().indexOf(".") + 1,
636                     artifact.getVersion().lastIndexOf(".")));
637             if (majorVal > bigNum) {
638                 bigNum = majorVal;
639                 smallNum = minorVal;
640             }
641             if ((bigNum == majorVal) && (minorVal > smallNum)) {
642                 smallNum = minorVal;
643             }
644             if (bigNum == majorVal && minorVal == smallNum) {
645                 result = artifact;
646             }
647         }
648         return additionalNexusLatestCheck(selectedName, result);
649     }
650
651     // Additional Check due to Limitations from Nexus API to check if the artifact is the latest.
652     private NexusArtifact additionalNexusLatestCheck(String selectedName, NexusArtifact result) {
653         if(result==null){
654             return result;
655         }
656         String nextVersion = incrementVersion(result.getVersion());
657         List<NexusArtifact> artifact = getArtifactFromNexus(selectedName, nextVersion);
658         return artifact.isEmpty() ? result : additionalNexusLatestCheck(selectedName, artifact.get(0));
659     }
660
661     private boolean checkRemoteSync(String selectedName, String version) {
662         List<NexusArtifact> artifacts = getArtifactFromNexus(selectedName, version);
663         return artifacts.isEmpty() ? false : true;
664     }
665
666     private List<NexusArtifact> getArtifactFromNexus(String selectedName, String version) {
667         final NexusClient client = new NexusRestClient();
668         int i = 0;
669         boolean flag = false;
670         while (i < repURLs.size()) {
671             try {
672                 String repURL = repURLs.get(0);
673                 client.connect(repURL.substring(0, repURL.indexOf(repURL.split(":[0-9]+\\/nexus")[1])), repUserName,
674                         repPassword);
675                 final NexusArtifact template = new NexusArtifact();
676                 template.setGroupId(getGroupID(selectedName));
677                 template.setArtifactId(getArtifactID(selectedName));
678                 if (version != null) {
679                     template.setVersion(version);
680                 }
681                 List<NexusArtifact> resultList = client.searchByGAV(template);
682                 if (resultList != null) {
683                     flag = true;
684                     return resultList;
685                 }
686             } catch (NexusClientException | NexusConnectionException | NullPointerException e) {
687                 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Connection to remote Nexus has failed. "
688                         + e.getMessage(), e);
689             } finally {
690                 try {
691                     client.disconnect();
692                 } catch (NexusClientException | NexusConnectionException e) {
693                     LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "failed to disconnect Connection from Nexus."
694                             + e.getMessage(), e);
695                 }
696                 if (!flag) {
697                     Collections.rotate(repURLs, -1);
698                     i++;
699                 }
700             }
701         }
702         return new ArrayList<>();
703     }
704
705     private void setVersion(String selectedName) {
706         String newVersion = VERSION_0_1_0;
707         createFlag = false;
708         NexusArtifact artifact = getLatestArtifactFromNexus(selectedName);
709         if (artifact != null) {
710             newVersion = incrementVersion(artifact.getVersion());
711         }
712         if (VERSION_0_1_0.equals(newVersion)) {
713             createFlag = true;
714         }
715         setVersion(newVersion, selectedName);
716         LOGGER.info("Controller: " + selectedName + "is on version: " + newVersion);
717     }
718
719     private String incrementVersion(String version) {
720         int majorVal = Integer.parseInt(version.substring(0, version.indexOf(".")));
721         int minorVal = Integer.parseInt(version.substring(version.indexOf(".") + 1, version.lastIndexOf(".")));
722         if (minorVal >= 9) {
723             majorVal += 1;
724             minorVal = 0;
725         } else {
726             minorVal += 1;
727         }
728         return majorVal + "." + minorVal + version.substring(version.lastIndexOf("."));
729     }
730
731     private boolean checkProject(String selectedName) {
732         return new File(PROJECTSLOCATION + File.separator + getDirectoryName(selectedName)).exists();
733     }
734
735     private String getDirectoryName(String selectedName) {
736         return getArtifactID(selectedName);
737     }
738
739     /**
740      * Will Push policies to the PolicyRepo.
741      * 
742      * @param notificationType
743      *            <String> type of notification Type.
744      * @throws PolicyException
745      */
746     public void pushRules() throws PolicyException {
747         // Check how many groups have been updated.
748         // Invoke their Maven process.
749         try {
750             im.startTransaction();
751         } catch (Exception e) {
752             LOGGER.error("Error while starting Transaction " + e);
753         }
754         if (!modifiedGroups.isEmpty()) {
755             Boolean flag = false;
756             for (Map.Entry<String, String> entry : modifiedGroups.entrySet()) {
757                 InvocationResult result = null;
758                 String group = entry.getKey();
759                 try {
760                         LOGGER.info("PushRules: ModifiedGroups, Key: " + group + ", Value: " + entry.getValue());
761                     InvocationRequest request = new DefaultInvocationRequest();
762                     setVersion(group);
763                     createPom(group);
764                     request.setPomFile(new File(
765                             PROJECTSLOCATION + File.separator + getArtifactID(group) + File.separator + POM_XML_FILE));
766                     request.setGoals(Arrays.asList(GOALS));
767                     Invoker invoker = new DefaultInvoker();
768                     result = invoker.execute(request);
769                     if (result.getExecutionException() != null) {
770                         LOGGER.error(result.getExecutionException());
771                     } else if (result.getExitCode() != 0) {
772                         LOGGER.error("Maven Invocation failure..!");
773                     }
774                 } catch (Exception e) {
775                     LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation issue for "
776                             + getArtifactID(group) + e.getMessage(), e);
777                 }
778                 if (result != null && result.getExitCode() == 0) {
779                     LOGGER.info("Build Completed..!");
780                     if (createFlag) {
781                         addNotification(group, "create");
782                     } else {
783                         addNotification(group, entry.getValue());
784                     }
785                     flag = true;
786                 } else {
787                     throw new PolicyException(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation failure!");
788                 }
789             }
790             if (flag) {
791                 sendNotification(controllers);
792             }
793         }
794         if (im != null) {
795             im.endTransaction();
796         }
797     }
798
799     /**
800      * Removes a Rule from Rule Projects.
801      */
802     public void removeRule(String name) {
803         String controllerName = getGroupName(name);
804         if (controllerName == null) {
805             LOGGER.info("Error finding the controllerName for the given Policy: " + name);
806             return;
807         }
808         syncProject(controllerName);
809         getNameAndSetRemove(controllerName, name);
810     }
811
812     private String getGroupName(String name) {
813         if (policyMap.containsKey(name)) {
814             return policyMap.get(name);
815         } else {
816             syncGroupInfo();
817             return policyMap.containsKey(name) ? policyMap.get(name) : null;
818         }
819     }
820
821     private void addModifiedGroup(String controllerName, String operation) {
822         if (controllerName != null) {
823             modifiedGroups.put(controllerName, operation);
824         }
825     }
826
827     private void addNotification(String controllerName, String operation) {
828         ControllerPOJO controllerPOJO = new ControllerPOJO();
829         controllerPOJO.setName(controllerName);
830         controllerPOJO.setOperation(operation);
831         HashMap<String, String> drools = new HashMap<>();
832         drools.put("groupId", getGroupID(controllerName));
833         drools.put("artifactId", getArtifactID(controllerName));
834         drools.put("version", getVersion(controllerName));
835         controllerPOJO.setDrools(drools);
836         controllers.add(controllerPOJO);
837         try {
838             LOGGER.debug("Notification added: " + PolicyUtils.objectToJsonString(controllerPOJO));
839         } catch (JsonProcessingException e) {
840             LOGGER.error(MessageCodes.ERROR_SCHEMA_INVALID + "Json Processing Error " + e);
841         }
842     }
843
844     private void removedRuleModifiedGroup(String controllerName) {
845         // This will be sending Notification to PDPD directly to Lock
846         ControllerPOJO controllerPOJO = new ControllerPOJO();
847         controllerPOJO.setName(controllerName);
848         controllerPOJO.setOperation("lock");
849         List<ControllerPOJO> controllerPojos = new ArrayList<>();
850         controllerPojos.add(controllerPOJO);
851         sendNotification(controllerPojos);
852     }
853
854     private void sendNotification(List<ControllerPOJO> controllers) {
855         NotificationPOJO notification = new NotificationPOJO();
856         String requestId = UUID.randomUUID().toString();
857         LOGGER.info("Generating notification RequestID : " + requestId);
858         notification.setRequestID(requestId);
859         notification.setEntity("controller");
860         notification.setControllers(controllers);
861         try {
862             String notificationJson = PolicyUtils.objectToJsonString(notification);
863             LOGGER.info("Sending Notification :\n" + notificationJson);
864             sendMessage(notificationJson);
865         } catch (Exception e) {
866             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while sending notification to PDP-D "
867                     + e.getMessage(), e);
868         }
869     }
870
871     private void sendMessage(String message) throws IOException, GeneralSecurityException, InterruptedException {
872
873         if ("dmaap".equalsIgnoreCase(notificationType)) {
874             // Sending Message through DMaaP Message Router
875             LOGGER.debug("DMAAP Publishing Message");
876
877             publisher.send("MyPartitionKey", message);
878
879             LOGGER.debug("Message Published on DMaaP :" + dmaapList.get(0) + "for Topic: " + pubTopic);
880
881             Thread.sleep(dmaapDelay);
882             publisher.close();
883         } else {
884             // Sending Message through UEB interface.
885             LOGGER.debug("UEB Publishing Message");
886
887             CambriaBatchingPublisher pub = pubBuilder.build();
888             pub.send("MyPartitionKey", message);
889
890             final List<?> stuck = pub.close(uebDelay, TimeUnit.SECONDS);
891             if (!stuck.isEmpty()) {
892                 LOGGER.error(stuck.size() + " messages unsent");
893             } else {
894                 LOGGER.debug("Clean exit; Message Published on UEB : " + uebList + "for Topic: " + pubTopic);
895             }
896         }
897
898     }
899
900     private void createPom(String name) {
901         Model model = new Model();
902         model.setModelVersion("4.0.0");
903         model.setGroupId(getGroupID(name));
904         model.setArtifactId(getArtifactID(name));
905         model.setVersion(getVersion(name));
906         model.setName(name);
907         DistributionManagement distributionManagement = new DistributionManagement();
908         DeploymentRepository repository = new DeploymentRepository();
909         repository.setId(repID);
910         repository.setName(repName);
911         repository.setUrl(repURLs.get(0));
912         distributionManagement.setRepository(repository);
913         model.setDistributionManagement(distributionManagement);
914         // Dependency Management goes here.
915         List<Dependency> dependencyList = new ArrayList<>();
916         if (groupMap.get(name).size() > 1) {
917             @SuppressWarnings("unchecked")
918             ArrayList<PEDependency> dependencies = (ArrayList<PEDependency>) groupMap.get(name).get(1);
919             for (PEDependency dependency : dependencies) {
920                 dependencyList.add(dependency.getDependency());
921             }
922         } else {
923             // Add Default dependencies.
924             dependencyList = getDependencies(name);
925         }
926         model.setDependencies(dependencyList);
927         Writer writer = null;
928         try {
929             writer = WriterFactory.newXmlWriter(
930                     new File(PROJECTSLOCATION + File.separator + getArtifactID(name) + File.separator + POM_XML_FILE));
931             MavenXpp3Writer pomWriter = new MavenXpp3Writer();
932             pomWriter.write(writer, model);
933         } catch (Exception e) {
934             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while creating POM for " + getArtifactID(name)
935                     + e.getMessage(), e);
936         } finally {
937             IOUtil.close(writer);
938         }
939     }
940
941     private List<Dependency> getDependencies(String controllerName) {
942         // Read the Dependency Information from property file.
943         Path file = Paths.get(DEPENDENCY_FILE);
944         if (!Files.notExists(file)) {
945             try {
946                 String dependencyJSON = new String(Files.readAllBytes(file), StandardCharsets.UTF_8);
947                 DependencyInfo dependencyInfo = PolicyUtils.jsonStringToObject(dependencyJSON, DependencyInfo.class);
948                 String controller = "default";
949                 if (dependencyInfo.getDependencies().containsKey(controllerName)) {
950                     controller = controllerName;
951                 }
952                 List<Dependency> dependencyList = new ArrayList<>();
953                 for (PEDependency dependency : dependencyInfo.getDependencies().get(controller)) {
954                     dependencyList.add(dependency.getDependency());
955                 }
956                 return dependencyList;
957             } catch (IOException | NullPointerException e) {
958                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
959                         + "Error while getting dependecy Information for controller: " + controllerName
960                         + e.getMessage(), e);
961             }
962         }
963         return defaultDependencies(controllerName);
964     }
965
966     // Default Dependency Section. Can be changed as required.
967     public List<Dependency> defaultDependencies(String controllerName) {
968
969         List<Dependency> dependencyList = new ArrayList<>();
970         String version = StringEscapeUtils.escapeJava(brmsdependencyversion);
971
972         Dependency demoDependency = new Dependency();
973         demoDependency.setGroupId(DROOLS_APPS_TEMPLATE_GROUP);
974         demoDependency.setArtifactId("template.demo");
975         demoDependency.setVersion(version);
976         dependencyList.add(demoDependency);
977
978         Dependency controlloopDependency = new Dependency();
979         controlloopDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
980         controlloopDependency.setArtifactId("events");
981         controlloopDependency.setVersion(version);
982         dependencyList.add(controlloopDependency);
983
984         Dependency restDependency = new Dependency();
985         restDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
986         restDependency.setArtifactId("controlloop.common.model-impl.rest");
987         restDependency.setVersion(version);
988         dependencyList.add(restDependency);
989
990         Dependency appcDependency = new Dependency();
991         appcDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
992         appcDependency.setArtifactId("controlloop.common.model-impl.appc");
993         appcDependency.setVersion(version);
994         dependencyList.add(appcDependency);
995
996         Dependency aaiDependency = new Dependency();
997         aaiDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
998         aaiDependency.setArtifactId("controlloop.common.model-impl.aai");
999         aaiDependency.setVersion(version);
1000         dependencyList.add(aaiDependency);
1001
1002         Dependency msoDependency = new Dependency();
1003         msoDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1004         msoDependency.setArtifactId("controlloop.common.model-impl.so");
1005         msoDependency.setVersion(version);
1006         dependencyList.add(msoDependency);
1007
1008         Dependency trafficgeneratorDependency = new Dependency();
1009         trafficgeneratorDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1010         trafficgeneratorDependency.setArtifactId("controlloop.common.model-impl.trafficgenerator");
1011         trafficgeneratorDependency.setVersion(version);
1012         dependencyList.add(trafficgeneratorDependency);
1013         return dependencyList;
1014     }
1015
1016     private void createProject(String path, String ksessionName) {
1017         new File(path + File.separator + RULES).mkdirs();
1018         new File(path + File.separator + META_INF).mkdirs();
1019         if (!Files.exists(Paths.get(path + File.separator + META_INF + File.separator + KMODULE_XML_FILE))) {
1020             // Hard coding XML for PDP Drools to accept our Rules.
1021             String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "\n"
1022                     + "<kmodule xmlns=\"http://jboss.org/kie/6.0.0/kmodule\">" + "\n"
1023                     + "<kbase name=\"rules\" packages=\"rules\">" + "\n" + "<ksession name=\"" + ksessionName + "\"/>"
1024                     + "\n" + "</kbase></kmodule>";
1025             copyDataToFile(path + File.separator + META_INF + File.separator + KMODULE_XML_FILE, xml);
1026         }
1027     }
1028
1029     private void copyDataToFile(String file, String rule) {
1030         try {
1031             FileUtils.writeStringToFile(new File(file), rule);
1032         } catch (Exception e) {
1033             LOGGER.error(
1034                     XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while creating Rule for " + file + e.getMessage(),
1035                     e);
1036         }
1037     }
1038
1039     private void readGroups(Properties config) throws PolicyException {
1040         String[] groupNames;
1041         String groupNamesError = "groupNames property is missing or empty from the property file ";
1042                 if (!config.containsKey(GROUP_NAMES) || config.getProperty(GROUP_NAMES)==null){
1043             throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
1044                     + groupNamesError);
1045         }
1046         if (config.getProperty(GROUP_NAMES).contains(",")) {
1047             groupNames = config.getProperty(GROUP_NAMES).replaceAll(" ", "").split(",");
1048         } else {
1049             groupNames = new String[] { config.getProperty(GROUP_NAMES).replaceAll(" ", "") };
1050         }
1051         if (groupNames == null || groupNames.length == 0) {
1052             LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
1053                     + groupNamesError);
1054             throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
1055                     + groupNamesError);
1056         }
1057         groupMap = new HashMap<>();
1058         for (int counter = 0; counter < groupNames.length; counter++) {
1059             String name = groupNames[counter];
1060             String groupID = config.getProperty(name + ".groupID");
1061             if (groupID == null) {
1062                 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1063                         + ".groupID property is missing from the property file ");
1064                 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1065                         + ".groupID property is missing from the property file ");
1066             }
1067             String artifactID = config.getProperty(name + ".artifactID");
1068             if (artifactID == null) {
1069                 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1070                         + ".artifactID property is missing from the property file ");
1071                 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1072                         + ".artifactID property is missing from the property file ");
1073             }
1074             PEDependency dependency = new PEDependency();
1075             dependency.setArtifactId(artifactID);
1076             dependency.setGroupId(groupID);
1077             // Add to list if we got all
1078             addToGroup(name, dependency);
1079         }
1080     }
1081
1082     private void addToGroup(String name, PEDependency dependency) {
1083         ArrayList<Object> values = new ArrayList<>();
1084         values.add(dependency);
1085         groupMap.put(name, values);
1086         EntityTransaction et = em.getTransaction();
1087         et.begin();
1088         Query query = em.createQuery("select b from BRMSGroupInfo as b where b.controllerName = :cn");
1089         query.setParameter("cn", name);
1090         List<?> groupList = query.getResultList();
1091         BRMSGroupInfo brmsGroupInfo = null;
1092         if (!groupList.isEmpty()) {
1093             LOGGER.info("Controller name already Existing in DB. Will be updating the DB Values" + name);
1094             brmsGroupInfo = (BRMSGroupInfo) groupList.get(0);
1095         }
1096         if (brmsGroupInfo == null) {
1097             brmsGroupInfo = new BRMSGroupInfo();
1098         }
1099         brmsGroupInfo.setControllerName(name);
1100         brmsGroupInfo.setGroupId(dependency.getGroupId());
1101         brmsGroupInfo.setArtifactId(dependency.getArtifactId());
1102         brmsGroupInfo.setVersion(dependency.getVersion());
1103         em.persist(brmsGroupInfo);
1104         em.flush();
1105         et.commit();
1106     }
1107
1108     private String getArtifactID(String name) {
1109         return ((PEDependency) groupMap.get(name).get(0)).getArtifactId();
1110     }
1111
1112     private String getGroupID(String name) {
1113         return ((PEDependency) groupMap.get(name).get(0)).getGroupId();
1114     }
1115
1116     private String getVersion(String name) {
1117         return ((PEDependency) groupMap.get(name).get(0)).getVersion();
1118     }
1119
1120     private void getNameAndSetRemove(String controllerName, String policyName) {
1121         String artifactName = getArtifactID(controllerName);
1122         String ruleFolder = PROJECTSLOCATION + File.separator + artifactName + File.separator + "src" + File.separator
1123                 + "main" + File.separator + RESOURCES + File.separator + RULES;
1124         File file = new File(ruleFolder + File.separator + policyName + ".drl");
1125         if (file.delete()) {
1126             LOGGER.info("Deleted File.. " + file.getAbsolutePath());
1127             removePolicyFromGroup(policyName, controllerName);
1128         }
1129         if (new File(ruleFolder).listFiles().length == 0) {
1130             removedRuleModifiedGroup(controllerName);
1131         } else {
1132             // This is an update in terms of PDPD.
1133             addModifiedGroup(controllerName, "update");
1134         }
1135     }
1136
1137     // Removes Policy from Memory and Database.
1138     private void removePolicyFromGroup(String policyName, String controllerName) {
1139         policyMap.remove(policyName);
1140         EntityTransaction et = em.getTransaction();
1141         et.begin();
1142         Query query = em.createQuery("select b from BRMSPolicyInfo as b where b.policyName = :pn");
1143         query.setParameter("pn", policyName);
1144         List<?> pList = query.getResultList();
1145         BRMSPolicyInfo brmsPolicyInfo;
1146         if (!pList.isEmpty()) {
1147             // Already exists.
1148             brmsPolicyInfo = (BRMSPolicyInfo) pList.get(0);
1149             if (brmsPolicyInfo.getControllerName().getControllerName().equals(controllerName)) {
1150                 em.remove(brmsPolicyInfo);
1151                 em.flush();
1152             }
1153         }
1154         et.commit();
1155     }
1156
1157     private void setVersion(String newVersion, String controllerName) {
1158         PEDependency userController = (PEDependency) groupMap.get(controllerName).get(0);
1159         userController.setVersion(newVersion);
1160         groupMap.get(controllerName).set(0, userController);
1161     }
1162
1163     // Return BackUpMonitor
1164     public static BackUpMonitor getBackUpMonitor() {
1165         return bm;
1166     }
1167
1168     public void rotateURLs() {
1169         if (repURLs != null) {
1170             Collections.rotate(repURLs, -1);
1171         }
1172     }
1173
1174     public int urlListSize() {
1175         if (repURLs != null) {
1176             return repURLs.size();
1177         } else
1178             return 0;
1179     }
1180 }