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