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