Merge "Fix issues reported by 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             Boolean flag;
791             flag = buildAndGenerateJarFile();
792             if (flag) {
793                 sendNotification(controllers);
794             }
795         }
796         if (im != null) {
797             im.endTransaction();
798         }
799     }
800
801     /**
802      * Removes a Rule from Rule Projects.
803      */
804     public void removeRule(final String name) {
805         final String controllerName = getGroupName(name);
806         if (controllerName == null) {
807             LOGGER.info("Error finding the controllerName for the given Policy: " + name);
808             return;
809         }
810         syncProject(controllerName);
811         getNameAndSetRemove(controllerName, name);
812     }
813
814     private Boolean buildAndGenerateJarFile() throws PolicyException {
815         Boolean flag = false;
816         for (final Map.Entry<String, String> entry : modifiedGroups.entrySet()) {
817             InvocationResult result = null;
818             final String group = entry.getKey();
819             try {
820                 LOGGER.info("PushRules: ModifiedGroups, Key: " + group + ", Value: " + entry.getValue());
821                 final InvocationRequest request = new DefaultInvocationRequest();
822                 setVersion(group);
823                 createPom(group);
824                 request.setPomFile(new File(
825                         PROJECTSLOCATION + File.separator + getArtifactId(group) + File.separator + POM_XML_FILE));
826                 request.setGoals(Arrays.asList(GOALS));
827                 final Invoker invoker = new DefaultInvoker();
828                 result = invoker.execute(request);
829                 if (result.getExecutionException() != null) {
830                     LOGGER.error(result.getExecutionException());
831                 } else if (result.getExitCode() != 0) {
832                     LOGGER.error("Maven Invocation failure..!");
833                 }
834             } catch (final Exception e) {
835                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation issue for "
836                         + getArtifactId(group) + e.getMessage(), e);
837             }
838             if (result != null && result.getExitCode() == 0) {
839                 LOGGER.info("Build Completed..!");
840                 if (createFlag) {
841                     addNotification(group, "create");
842                 } else {
843                     addNotification(group, entry.getValue());
844                 }
845                 flag = true;
846             } else {
847                 throw new PolicyException(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Maven Invocation failure!");
848             }
849         }
850         return flag;
851     }
852
853     private String getGroupName(final String name) {
854         if (policyMap.containsKey(name)) {
855             return policyMap.get(name);
856         } else {
857             syncGroupInfo();
858             return policyMap.containsKey(name) ? policyMap.get(name) : null;
859         }
860     }
861
862     private void addModifiedGroup(final String controllerName, final String operation) {
863         if (controllerName != null) {
864             modifiedGroups.put(controllerName, operation);
865         }
866     }
867
868     private void addNotification(final String controllerName, final String operation) {
869         final ControllerPojo controllerPojo = new ControllerPojo();
870         controllerPojo.setName(controllerName);
871         controllerPojo.setOperation(operation);
872         final HashMap<String, String> drools = new HashMap<>();
873         drools.put("groupId", getGroupId(controllerName));
874         drools.put("artifactId", getArtifactId(controllerName));
875         drools.put("version", getVersion(controllerName));
876         controllerPojo.setDrools(drools);
877         controllers.add(controllerPojo);
878         try {
879             LOGGER.debug("Notification added: " + PolicyUtils.objectToJsonString(controllerPojo));
880         } catch (final JsonProcessingException e) {
881             LOGGER.error(MessageCodes.ERROR_SCHEMA_INVALID + "Json Processing Error " + e);
882         }
883     }
884
885     private void removedRuleModifiedGroup(final String controllerName) {
886         // This will be sending Notification to PDPD directly to Lock
887         final ControllerPojo controllerPojo = new ControllerPojo();
888         controllerPojo.setName(controllerName);
889         controllerPojo.setOperation("lock");
890         final List<ControllerPojo> controllerPojos = new ArrayList<>();
891         controllerPojos.add(controllerPojo);
892         sendNotification(controllerPojos);
893     }
894
895     private void sendNotification(final List<ControllerPojo> controllers) {
896         final NotificationPojo notification = new NotificationPojo();
897         final String requestId = UUID.randomUUID().toString();
898         LOGGER.info("Generating notification RequestID : " + requestId);
899         notification.setRequestId(requestId);
900         notification.setEntity("controller");
901         notification.setControllers(controllers);
902         try {
903             final String notificationJson = PolicyUtils.objectToJsonString(notification);
904             LOGGER.info("Sending Notification :\n" + notificationJson);
905             sendMessage(notificationJson);
906         } catch (final Exception e) {
907             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while sending notification to PDP-D "
908                     + e.getMessage(), e);
909         }
910     }
911
912     private void sendMessage(final String message) throws IOException, GeneralSecurityException, InterruptedException {
913
914         if ("dmaap".equalsIgnoreCase(notificationType)) {
915             // Sending Message through DMaaP Message Router
916             LOGGER.debug("DMAAP Publishing Message");
917
918             publisher.send("MyPartitionKey", message);
919
920             LOGGER.debug("Message Published on DMaaP :" + dmaapList.get(0) + "for Topic: " + pubTopic);
921
922             Thread.sleep(dmaapDelay);
923             publisher.close();
924         } else {
925             // Sending Message through UEB interface.
926             LOGGER.debug("UEB Publishing Message");
927
928             final CambriaBatchingPublisher pub = pubBuilder.build();
929             pub.send("MyPartitionKey", message);
930
931             final List<?> stuck = pub.close(uebDelay, TimeUnit.SECONDS);
932             if (!stuck.isEmpty()) {
933                 LOGGER.error(stuck.size() + " messages unsent");
934             } else {
935                 LOGGER.debug("Clean exit; Message Published on UEB : " + uebList + "for Topic: " + pubTopic);
936             }
937         }
938
939     }
940
941     private void createPom(final String name) {
942         final Model model = new Model();
943         model.setModelVersion("4.0.0");
944         model.setGroupId(getGroupId(name));
945         model.setArtifactId(getArtifactId(name));
946         model.setVersion(getVersion(name));
947         model.setName(name);
948         final DistributionManagement distributionManagement = new DistributionManagement();
949         final DeploymentRepository repository = new DeploymentRepository();
950         repository.setId(repId);
951         repository.setName(repName);
952         repository.setUrl(repUrlList.get(0));
953         distributionManagement.setRepository(repository);
954         model.setDistributionManagement(distributionManagement);
955         // Dependency Management goes here.
956         List<Dependency> dependencyList = new ArrayList<>();
957         if (groupMap.get(name).size() > 1) {
958             @SuppressWarnings("unchecked")
959             final ArrayList<PEDependency> dependencies = (ArrayList<PEDependency>) groupMap.get(name).get(1);
960             for (final PEDependency dependency : dependencies) {
961                 dependencyList.add(dependency.getDependency());
962             }
963         } else {
964             // Add Default dependencies.
965             dependencyList = getDependencies(name);
966         }
967         model.setDependencies(dependencyList);
968         Writer writer = null;
969         try {
970             writer = WriterFactory.newXmlWriter(
971                     new File(PROJECTSLOCATION + File.separator + getArtifactId(name) + File.separator + POM_XML_FILE));
972             final MavenXpp3Writer pomWriter = new MavenXpp3Writer();
973             pomWriter.write(writer, model);
974         } catch (final Exception e) {
975             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while creating POM for " + getArtifactId(name)
976                     + e.getMessage(), e);
977         } finally {
978             IOUtil.close(writer);
979         }
980     }
981
982     private List<Dependency> getDependencies(final String controllerName) {
983         // Read the Dependency Information from property file.
984         final Path file = Paths.get(DEPENDENCY_FILE);
985         if (!Files.notExists(file)) {
986             try {
987                 final String dependencyJson = new String(Files.readAllBytes(file), StandardCharsets.UTF_8);
988                 final DependencyInfo dependencyInfo =
989                         PolicyUtils.jsonStringToObject(dependencyJson, DependencyInfo.class);
990                 String controller = "default";
991                 if (dependencyInfo.getDependencies().containsKey(controllerName)) {
992                     controller = controllerName;
993                 }
994                 final List<Dependency> dependencyList = new ArrayList<>();
995                 for (final PEDependency dependency : dependencyInfo.getDependencies().get(controller)) {
996                     dependencyList.add(dependency.getDependency());
997                 }
998                 return dependencyList;
999             } catch (IOException | NullPointerException e) {
1000                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW
1001                         + "Error while getting dependecy Information for controller: " + controllerName
1002                         + e.getMessage(), e);
1003             }
1004         }
1005         return defaultDependencies(controllerName);
1006     }
1007
1008     /**
1009      * Default Dependency Section. Can be changed as required.
1010      * 
1011      * @param controllerName the controller name
1012      * @return changed dependency list
1013      */
1014     public List<Dependency> defaultDependencies(final String controllerName) {
1015
1016         final List<Dependency> dependencyList = new ArrayList<>();
1017         final String version = StringEscapeUtils.escapeJava(brmsdependencyversion);
1018
1019         final Dependency demoDependency = new Dependency();
1020         demoDependency.setGroupId(DROOLS_APPS_TEMPLATE_GROUP);
1021         demoDependency.setArtifactId("template.demo");
1022         demoDependency.setVersion(version);
1023         dependencyList.add(demoDependency);
1024
1025         final Dependency controlloopDependency = new Dependency();
1026         controlloopDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1027         controlloopDependency.setArtifactId("events");
1028         controlloopDependency.setVersion(version);
1029         dependencyList.add(controlloopDependency);
1030
1031         final Dependency restDependency = new Dependency();
1032         restDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1033         restDependency.setArtifactId("controlloop.common.model-impl.rest");
1034         restDependency.setVersion(version);
1035         dependencyList.add(restDependency);
1036
1037         final Dependency appcDependency = new Dependency();
1038         appcDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1039         appcDependency.setArtifactId("controlloop.common.model-impl.appc");
1040         appcDependency.setVersion(version);
1041         dependencyList.add(appcDependency);
1042
1043         final Dependency aaiDependency = new Dependency();
1044         aaiDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1045         aaiDependency.setArtifactId("controlloop.common.model-impl.aai");
1046         aaiDependency.setVersion(version);
1047         dependencyList.add(aaiDependency);
1048
1049         final Dependency msoDependency = new Dependency();
1050         msoDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1051         msoDependency.setArtifactId("controlloop.common.model-impl.so");
1052         msoDependency.setVersion(version);
1053         dependencyList.add(msoDependency);
1054
1055         final Dependency trafficgeneratorDependency = new Dependency();
1056         trafficgeneratorDependency.setGroupId(DROOLS_APPS_MODEL_GROUP);
1057         trafficgeneratorDependency.setArtifactId("controlloop.common.model-impl.trafficgenerator");
1058         trafficgeneratorDependency.setVersion(version);
1059         dependencyList.add(trafficgeneratorDependency);
1060         return dependencyList;
1061     }
1062
1063     private void createProject(final String path, final String ksessionName) {
1064         new File(path + File.separator + RULES).mkdirs();
1065         new File(path + File.separator + META_INF).mkdirs();
1066         if (!Files.exists(Paths.get(path + File.separator + META_INF + File.separator + KMODULE_XML_FILE))) {
1067             // Hard coding XML for PDP Drools to accept our Rules.
1068             final String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "\n"
1069                     + "<kmodule xmlns=\"http://jboss.org/kie/6.0.0/kmodule\">" + "\n"
1070                     + "<kbase name=\"rules\" packages=\"rules\">" + "\n" + "<ksession name=\"" + ksessionName + "\"/>"
1071                     + "\n" + "</kbase></kmodule>";
1072             copyDataToFile(path + File.separator + META_INF + File.separator + KMODULE_XML_FILE, xml);
1073         }
1074     }
1075
1076     private void copyDataToFile(final String file, final String rule) {
1077         try {
1078             FileUtils.writeStringToFile(new File(file), rule);
1079         } catch (final Exception e) {
1080             LOGGER.error(
1081                     XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while creating Rule for " + file + e.getMessage(),
1082                     e);
1083         }
1084     }
1085
1086     private void readGroups(final Properties config) throws PolicyException {
1087         String[] groupNames;
1088         final String groupNamesError = "groupNames property is missing or empty from the property file ";
1089         if (!config.containsKey(GROUP_NAMES) || config.getProperty(GROUP_NAMES) == null) {
1090             throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + groupNamesError);
1091         }
1092         if (config.getProperty(GROUP_NAMES).contains(",")) {
1093             groupNames = config.getProperty(GROUP_NAMES).replaceAll(" ", "").split(",");
1094         } else {
1095             groupNames = new String[] {config.getProperty(GROUP_NAMES).replaceAll(" ", "")};
1096         }
1097         if (groupNames == null || groupNames.length == 0) {
1098             LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + groupNamesError);
1099             throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + groupNamesError);
1100         }
1101         groupMap = new HashMap<>();
1102         for (int counter = 0; counter < groupNames.length; counter++) {
1103             final String name = groupNames[counter];
1104             final String groupId = config.getProperty(name + ".groupID");
1105             if (groupId == null) {
1106                 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1107                         + ".groupID property is missing from the property file ");
1108                 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1109                         + ".groupID property is missing from the property file ");
1110             }
1111             final String artifactId = config.getProperty(name + ".artifactID");
1112             if (artifactId == null) {
1113                 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1114                         + ".artifactID property is missing from the property file ");
1115                 throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + name
1116                         + ".artifactID property is missing from the property file ");
1117             }
1118             final PEDependency dependency = new PEDependency();
1119             dependency.setArtifactId(artifactId);
1120             dependency.setGroupId(groupId);
1121             // Add to list if we got all
1122             addToGroup(name, dependency);
1123         }
1124     }
1125
1126     private void addToGroup(final String name, final PEDependency dependency) {
1127         final EntityTransaction et = em.getTransaction();
1128         try {
1129             et.begin();
1130             final TypedQuery<BrmsGroupInfo> query = em
1131                     .createQuery("select b from BrmsGroupInfo as b where b.controllerName = :cn", BrmsGroupInfo.class);
1132             query.setParameter("cn", name);
1133             final List<BrmsGroupInfo> groupList = query.getResultList();
1134             BrmsGroupInfo brmsGroupInfo = null;
1135             if (!groupList.isEmpty()) {
1136                 LOGGER.info("Controller name already Existing in DB. Will be updating the DB Values" + name);
1137                 brmsGroupInfo = groupList.get(0);
1138             }
1139             if (brmsGroupInfo == null) {
1140                 brmsGroupInfo = new BrmsGroupInfo();
1141             }
1142             brmsGroupInfo.setControllerName(name);
1143             brmsGroupInfo.setGroupId(dependency.getGroupId());
1144             brmsGroupInfo.setArtifactId(dependency.getArtifactId());
1145             brmsGroupInfo.setVersion(dependency.getVersion());
1146             em.persist(brmsGroupInfo);
1147             em.flush();
1148             et.commit();
1149
1150             final ArrayList<Object> values = new ArrayList<>();
1151             values.add(dependency);
1152             groupMap.put(name, values);
1153         } catch (final Exception exception) {
1154             LOGGER.error("Unable add/update policy group to database for controller name: " + name, exception);
1155             et.rollback();
1156             throw exception;
1157         }
1158     }
1159
1160     private String getArtifactId(final String name) {
1161         return ((PEDependency) groupMap.get(name).get(0)).getArtifactId();
1162     }
1163
1164     private String getGroupId(final String name) {
1165         return ((PEDependency) groupMap.get(name).get(0)).getGroupId();
1166     }
1167
1168     private String getVersion(final String name) {
1169         return ((PEDependency) groupMap.get(name).get(0)).getVersion();
1170     }
1171
1172     private void getNameAndSetRemove(final String controllerName, final String policyName) {
1173         final String artifactName = getArtifactId(controllerName);
1174         final String ruleFolder = PROJECTSLOCATION + File.separator + artifactName + File.separator + "src"
1175                 + File.separator + "main" + File.separator + RESOURCES + File.separator + RULES;
1176         final File file = new File(ruleFolder + File.separator + policyName + ".drl");
1177         if (file.delete()) {
1178             LOGGER.info("Deleted File.. " + file.getAbsolutePath());
1179             removePolicyFromGroup(policyName, controllerName);
1180         }
1181         if (new File(ruleFolder).listFiles().length == 0) {
1182             removedRuleModifiedGroup(controllerName);
1183         } else {
1184             // This is an update in terms of PDPD.
1185             addModifiedGroup(controllerName, "update");
1186         }
1187     }
1188
1189     // Removes Policy from Memory and Database.
1190     private void removePolicyFromGroup(final String policyName, final String controllerName) {
1191         final EntityTransaction et = em.getTransaction();
1192         try {
1193             et.begin();
1194             final TypedQuery<BrmsPolicyInfo> query =
1195                     em.createQuery("select b from BrmsPolicyInfo as b where b.policyName = :pn", BrmsPolicyInfo.class);
1196             query.setParameter("pn", policyName);
1197             final List<BrmsPolicyInfo> pList = query.getResultList();
1198             BrmsPolicyInfo brmsPolicyInfo;
1199             if (!pList.isEmpty()) {
1200                 // Already exists.
1201                 brmsPolicyInfo = pList.get(0);
1202                 if (brmsPolicyInfo.getControllerName().getControllerName().equals(controllerName)) {
1203                     em.remove(brmsPolicyInfo);
1204                     em.flush();
1205                 }
1206             }
1207             et.commit();
1208             policyMap.remove(policyName);
1209         } catch (final Exception exception) {
1210             LOGGER.error("Unable remove policy from group to database for policy name: " + policyName, exception);
1211             et.rollback();
1212             throw exception;
1213         }
1214     }
1215
1216     private void setVersion(final String selectedName) {
1217         String newVersion = VERSION_0_1_0;
1218         createFlag = false;
1219         final NexusArtifact artifact = getLatestArtifactFromNexus(selectedName);
1220         if (artifact != null) {
1221             newVersion = incrementVersion(artifact.getVersion());
1222         }
1223         if (VERSION_0_1_0.equals(newVersion)) {
1224             createFlag = true;
1225         }
1226         setVersion(newVersion, selectedName);
1227         LOGGER.info("Controller: " + selectedName + "is on version: " + newVersion);
1228     }
1229
1230     private void setVersion(final String newVersion, final String controllerName) {
1231         final PEDependency userController = (PEDependency) groupMap.get(controllerName).get(0);
1232         userController.setVersion(newVersion);
1233         groupMap.get(controllerName).set(0, userController);
1234     }
1235
1236     // Return BackUpMonitor
1237     public static BackUpMonitor getBackUpMonitor() {
1238         return bm;
1239     }
1240
1241     /**
1242      * Rotate URLs list.
1243      */
1244     public void rotateUrls() {
1245         if (repUrlList != null) {
1246             Collections.rotate(repUrlList, -1);
1247         }
1248     }
1249
1250     /**
1251      * Get URL List Size.
1252      * 
1253      * @return URL list size
1254      */
1255     public int urlListSize() {
1256         return repUrlList != null ? repUrlList.size() : 0;
1257     }
1258 }