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