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