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