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