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