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