69444c478c6ecf7c5cb8ede752e03677ec4d7803
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / controller / PolicyController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2017-2019 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.controller;
23
24 import com.att.research.xacml.util.XACMLProperties;
25 import com.fasterxml.jackson.databind.ObjectMapper;
26 import java.io.ByteArrayInputStream;
27 import java.io.File;
28 import java.io.FileInputStream;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.util.ArrayList;
32 import java.util.HashMap;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Map.Entry;
36 import java.util.Properties;
37 import java.util.Set;
38 import java.nio.charset.StandardCharsets;
39 import javax.annotation.PostConstruct;
40 import javax.mail.MessagingException;
41 import javax.script.SimpleBindings;
42 import javax.servlet.http.HttpServletRequest;
43 import javax.servlet.http.HttpServletResponse;
44 import org.json.JSONObject;
45 import org.onap.policy.admin.PolicyNotificationMail;
46 import org.onap.policy.admin.RESTfulPAPEngine;
47 import org.onap.policy.common.logging.eelf.MessageCodes;
48 import org.onap.policy.common.logging.eelf.PolicyLogger;
49 import org.onap.policy.common.logging.flexlogger.FlexLogger;
50 import org.onap.policy.common.logging.flexlogger.Logger;
51 import org.onap.policy.model.PDPGroupContainer;
52 import org.onap.policy.model.Roles;
53 import org.onap.policy.rest.XACMLRestProperties;
54 import org.onap.policy.rest.dao.CommonClassDao;
55 import org.onap.policy.rest.jpa.Datatype;
56 import org.onap.policy.rest.jpa.FunctionDefinition;
57 import org.onap.policy.rest.jpa.PolicyEntity;
58 import org.onap.policy.rest.jpa.PolicyVersion;
59 import org.onap.policy.rest.jpa.UserInfo;
60 import org.onap.policy.utils.UserUtils.Pair;
61 import org.onap.policy.xacml.api.XACMLErrorConstants;
62 import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
63 import org.onap.policy.xacml.util.XACMLPolicyScanner;
64 import org.onap.portalsdk.core.controller.RestrictedBaseController;
65 import org.onap.portalsdk.core.domain.UserApp;
66 import org.onap.portalsdk.core.web.support.JsonMessage;
67 import org.onap.portalsdk.core.web.support.UserUtils;
68 import org.springframework.beans.factory.annotation.Autowired;
69 import org.springframework.http.MediaType;
70 import org.springframework.stereotype.Controller;
71 import org.springframework.web.bind.annotation.RequestMapping;
72 import org.springframework.web.bind.annotation.RequestMethod;
73 import org.springframework.web.servlet.ModelAndView;
74 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
75 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
76
77 @Controller
78 @RequestMapping("/")
79 public class PolicyController extends RestrictedBaseController {
80     private static final Logger policyLogger = FlexLogger.getLogger(PolicyController.class);
81
82     private static CommonClassDao commonClassDao;
83     //
84     // The PAP Engine
85     //
86     private static PAPPolicyEngine papEngine;
87
88     private static String logTableLimit;
89     private static String systemAlertTableLimit;
90     protected static Map<String, String> dropDownMap = new HashMap<>();
91
92     public static Map<String, String> getDropDownMap() {
93         return dropDownMap;
94     }
95
96     public static void setDropDownMap(Map<String, String> dropDownMap) {
97         PolicyController.dropDownMap = dropDownMap;
98     }
99
100     public static String getDomain() {
101         return XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_DOMAIN, "urn");
102     }
103
104     private static final Object mapAccess = new Object();
105     private static Map<Datatype, List<FunctionDefinition>> mapDatatype2Function = null;
106     private static Map<String, FunctionDefinition> mapID2Function = null;
107
108     // Constant variables used across Policy-sdk
109     private static final String policyData = "policyData";
110     private static final String characterEncoding = "UTF-8";
111     private static final String contentType = "application/json";
112     private static final String file = "file";
113     private static final String SUPERADMIN = "super-admin";
114     private static final String POLICYGUEST = "Policy Guest";
115     private static final String LOGINID = "loginId";
116
117     // Smtp Java Mail Properties
118     private static String smtpHost = null;
119     private static String smtpPort = null;
120     private static String smtpUsername = null;
121     private static String smtpPassword = null;
122     private static String smtpApplicationName = null;
123     private static String smtpEmailExtension = null;
124     // log db Properties
125     private static String logdbDriver = null;
126     private static String logdbUrl = null;
127     private static String logdbUserName = null;
128     private static String logdbPassword = null;
129     private static String logdbDialect = null;
130     // Xacml db properties
131     private static String xacmldbUrl = null;
132     private static String xacmldbUserName = null;
133     private static String xacmldbPassword = null;
134
135     // AutoPush feature.
136     private static String autoPushAvailable;
137     private static String autoPushDSClosedLoop;
138     private static String autoPushDSFirewall;
139     private static String autoPushDSMicroservice;
140     private static String autoPushPDPGroup;
141
142     // papURL
143     private static String papUrl;
144
145     // MicroService Model Properties
146     private static String msOnapName;
147     private static String msPolicyName;
148
149     // WebApp directories
150     private static String configHome;
151     private static String actionHome;
152
153     // File upload size
154     private static long fileSizeLimit;
155
156     private static boolean jUnit = false;
157
158     public static boolean isjUnit() {
159         return jUnit;
160     }
161
162     public static void setjUnit(boolean jUnit) {
163         PolicyController.jUnit = jUnit;
164     }
165
166     @Autowired
167     private PolicyController(CommonClassDao commonClassDao) {
168         PolicyController.commonClassDao = commonClassDao;
169     }
170
171     public PolicyController() {
172         // Empty constructor
173     }
174
175     /**
176      * init method to load the properties.
177      */
178     @PostConstruct
179     public void init() {
180         Properties prop = new Properties();
181
182         try {
183             String fileName;
184             if (jUnit) {
185                 fileName = new File(".").getCanonicalPath() + File.separator + "src" + File.separator + "test"
186                         + File.separator + "resources" + File.separator + "JSONConfig.json";
187             } else {
188                 fileName = "xacml.admin.properties";
189             }
190
191             try (InputStream input = new FileInputStream(fileName)) {
192                 // load a properties file
193                 prop.load(input);
194             }
195
196             // file upload size limit property
197             setFileSizeLimit(prop.getProperty("file.size.limit"));
198             // pap url
199             setPapUrl(prop.getProperty("xacml.rest.pap.url"));
200             // get the property values
201             setSmtpHost(prop.getProperty("onap.smtp.host"));
202             setSmtpPort(prop.getProperty("onap.smtp.port"));
203             setSmtpUsername(prop.getProperty("onap.smtp.userName"));
204             setSmtpPassword(prop.getProperty("onap.smtp.password"));
205             setSmtpApplicationName(prop.getProperty("onap.application.name"));
206             setSmtpEmailExtension(prop.getProperty("onap.smtp.emailExtension"));
207             // Log Database Properties
208             setLogdbDriver(prop.getProperty("xacml.log.db.driver"));
209             setLogdbUrl(prop.getProperty("xacml.log.db.url"));
210             setLogdbUserName(prop.getProperty("xacml.log.db.user"));
211             setLogdbPassword(prop.getProperty("xacml.log.db.password"));
212             setLogdbDialect(prop.getProperty("onap.dialect"));
213             // Xacml Database Properties
214             setXacmldbUrl(prop.getProperty("javax.persistence.jdbc.url"));
215             setXacmldbUserName(prop.getProperty("javax.persistence.jdbc.user"));
216             setXacmldbPassword(prop.getProperty("javax.persistence.jdbc.password"));
217             // AutoPuh
218             setAutoPushAvailable(prop.getProperty("xacml.automatic.push"));
219             setAutoPushDSClosedLoop(prop.getProperty("xacml.autopush.closedloop"));
220             setAutoPushDSFirewall(prop.getProperty("xacml.autopush.firewall"));
221             setAutoPushDSMicroservice(prop.getProperty("xacml.autopush.microservice"));
222             setAutoPushPDPGroup(prop.getProperty("xacml.autopush.pdpGroup"));
223             // Micro Service Properties
224             setMsOnapName(prop.getProperty("xacml.policy.msOnapName"));
225             if (getMsOnapName() == null) {
226                 setMsOnapName(prop.getProperty("xacml.policy.msEcompName"));
227             }
228             policyLogger.info("getMsOnapName => " + getMsOnapName());
229             setMsPolicyName(prop.getProperty("xacml.policy.msPolicyName"));
230             policyLogger.info("setMsPolicyName => " + getMsPolicyName());
231             // WebApp directories
232             setConfigHome(prop.getProperty("xacml.rest.config.webapps") + "Config");
233             setActionHome(prop.getProperty("xacml.rest.config.webapps") + "Action");
234             // Get the Property Values for Dashboard tab Limit
235             try {
236                 setLogTableLimit(prop.getProperty("xacml.onap.dashboard.logTableLimit"));
237                 setSystemAlertTableLimit(prop.getProperty("xacml.onap.dashboard.systemAlertTableLimit"));
238             } catch (Exception e) {
239                 policyLogger
240                         .error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Dashboard tab Property fields are missing" + e);
241                 setLogTableLimit("5000");
242                 setSystemAlertTableLimit("2000");
243             }
244             System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "xacml.admin.properties");
245         } catch (IOException ex) {
246             policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE
247                     + "Exception Occured while reading the Smtp properties from xacml.admin.properties file" + ex);
248         }
249
250         // Initialize the FunctionDefinition table at Server Start up
251         Map<Datatype, List<FunctionDefinition>> functionMap = getFunctionDatatypeMap();
252         for (Entry<Datatype, List<FunctionDefinition>> entry : functionMap.entrySet()) {
253             List<FunctionDefinition> functionDefinations = entry.getValue();
254             for (FunctionDefinition functionDef : functionDefinations) {
255                 dropDownMap.put(functionDef.getShortname(), functionDef.getXacmlid());
256             }
257         }
258
259     }
260
261     /**
262      * Get FunctionData Type from DB.
263      * 
264      * @return list of FunctionData.
265      */
266     public static Map<Datatype, List<FunctionDefinition>> getFunctionDatatypeMap() {
267         synchronized (mapAccess) {
268             if (mapDatatype2Function == null) {
269                 buildFunctionMaps();
270             }
271         }
272         return mapDatatype2Function;
273     }
274
275     /**
276      * Get Function ID.
277      * 
278      * @return Function ID.
279      */
280     public static Map<String, FunctionDefinition> getFunctionIdMap() {
281         synchronized (mapAccess) {
282             if (mapID2Function == null) {
283                 buildFunctionMaps();
284             }
285         }
286         return mapID2Function;
287     }
288
289     private static void buildFunctionMaps() {
290         mapDatatype2Function = new HashMap<>();
291         mapID2Function = new HashMap<>();
292         List<Object> functiondefinitions = commonClassDao.getData(FunctionDefinition.class);
293         for (int i = 0; i < functiondefinitions.size(); i++) {
294             FunctionDefinition value = (FunctionDefinition) functiondefinitions.get(i);
295             mapID2Function.put(value.getXacmlid(), value);
296             if (!mapDatatype2Function.containsKey(value.getDatatypeBean())) {
297                 mapDatatype2Function.put(value.getDatatypeBean(), new ArrayList<FunctionDefinition>());
298             }
299             mapDatatype2Function.get(value.getDatatypeBean()).add(value);
300         }
301     }
302
303     /**
304      * Get Functional Definition data.
305      * 
306      * @param request  HttpServletRequest.
307      * @param response HttpServletResponse.
308      */
309     @RequestMapping(value = { "/get_FunctionDefinitionDataByName" }, method = {
310             org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE)
311     public void getFunctionDefinitionData(HttpServletRequest request, HttpServletResponse response) {
312         try {
313             Map<String, Object> model = new HashMap<>();
314             ObjectMapper mapper = new ObjectMapper();
315             model.put("functionDefinitionDatas",
316                     mapper.writeValueAsString(commonClassDao.getDataByColumn(FunctionDefinition.class, "shortname")));
317             JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
318             JSONObject j = new JSONObject(msg);
319             response.getWriter().write(j.toString());
320         } catch (Exception e) {
321             policyLogger.error(
322                     XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while retriving the Function Definition data" + e);
323         }
324     }
325
326     /**
327      * Get PolicyEntity Data from db.
328      * 
329      * @param scope      scopeName.
330      * @param policyName policyName.
331      * @return policyEntity data.
332      */
333     public PolicyEntity getPolicyEntityData(String scope, String policyName) {
334         String key = scope + ":" + policyName;
335         List<Object> data = commonClassDao.getDataById(PolicyEntity.class, "scope:policyName", key);
336         return (PolicyEntity) data.get(0);
337     }
338
339     /**
340      * Get Policy User Roles from db.
341      * 
342      * @param userId LoginID.
343      * @return list of Roles.
344      */
345     public List<String> getRolesOfUser(String userId) {
346         List<String> rolesList = new ArrayList<>();
347         List<Object> roles = commonClassDao.getDataById(Roles.class, LOGINID, userId);
348         for (Object role : roles) {
349             rolesList.add(((Roles) role).getRole());
350         }
351         return rolesList;
352     }
353
354     public List<Object> getRoles(String userId) {
355         return commonClassDao.getDataById(Roles.class, LOGINID, userId);
356     }
357
358     /**
359      * Get List of User Roles.
360      * 
361      * @param request  HttpServletRequest.
362      * @param response HttpServletResponse.
363      */
364     @RequestMapping(value = { "/get_UserRolesData" }, method = {
365             org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE)
366     public void getUserRolesEntityData(HttpServletRequest request, HttpServletResponse response) {
367         try {
368             String userId = UserUtils.getUserSession(request).getOrgUserId();
369             Map<String, Object> model = new HashMap<>();
370             ObjectMapper mapper = new ObjectMapper();
371             model.put("userRolesDatas", mapper.writeValueAsString(getRolesOfUser(userId)));
372             JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
373             JSONObject j = new JSONObject(msg);
374             response.getWriter().write(j.toString());
375         } catch (Exception e) {
376             policyLogger.error("Exception Occured" + e);
377         }
378     }
379
380     /**
381      * Policy tabs Model and View.
382      * 
383      * @param request Request input.
384      * @return view model.
385      */
386     @RequestMapping(value = { "/policy", "/policy/Editor" }, method = RequestMethod.GET)
387     public ModelAndView view(HttpServletRequest request) {
388         getUserRoleFromSession(request);
389         String myRequestUrl = request.getRequestURL().toString();
390         try {
391             //
392             // Set the URL for the RESTful PAP Engine
393             //
394             setPapEngine(new RESTfulPAPEngine(myRequestUrl));
395             new PDPGroupContainer(new RESTfulPAPEngine(myRequestUrl));
396         } catch (Exception e) {
397             policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Exception Occured while loading PAP" + e);
398         }
399         Map<String, Object> model = new HashMap<>();
400         return new ModelAndView("policy_Editor", "model", model);
401     }
402
403     /**
404      * Read the role from session for inserting into the database.
405      * 
406      * @param request Request input for Role.
407      */
408     public void getUserRoleFromSession(HttpServletRequest request) {
409         // While user landing on Policy page, fetch the userId and Role from
410         // session.
411         // And, Query the Roles table and if user not exists or else modified
412         // update the Roles table.
413         List<String> roles;
414         List<String> newRoles = new ArrayList<>();
415         String userId = UserUtils.getUserSession(request).getOrgUserId();
416         String name = UserUtils.getUserSession(request).getFullName();
417         @SuppressWarnings("unchecked")
418         Set<UserApp> userApps = UserUtils.getUserSession(request).getUserApps();
419         for (UserApp userApp : userApps) {
420             newRoles.add(userApp.getRole().getName());
421         }
422         List<Object> userRoles = getRoles(userId);
423         List<String> filteredRoles = filterRole(newRoles);
424         if (!filteredRoles.isEmpty()) {
425             cleanUpRoles(filteredRoles, userId);
426         }
427         for (String filteredRole : filteredRoles) {
428             if (userRoles == null || userRoles.isEmpty()) {
429                 savePolicyRoles(name, filteredRole, userId);
430             } else {
431                 userRoles = getRoles(userId);
432                 Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
433                 roles = pair.u;
434                 if (!roles.contains(filteredRole)) {
435                     savePolicyRoles(name, filteredRole, userId);
436                 }
437             }
438         }
439     }
440
441     /**
442      * Build a delete query for cleaning up roles and execute it.
443      * 
444      * @param filteredRoles Filtered roles list.
445      * @param userId        UserID.
446      */
447     private void cleanUpRoles(List<String> filteredRoles, String userId) {
448         StringBuilder query = new StringBuilder();
449         query.append("delete from Roles where loginid = '" + userId + "'");
450         if (filteredRoles.contains(SUPERADMIN)) {
451             query.append("and not role = '" + SUPERADMIN + "'");
452         } else {
453             for (String filteredRole : filteredRoles) {
454                 query.append("and not role = '" + filteredRole + "'");
455             }
456         }
457         query.append("and id > 0");
458         commonClassDao.updateQuery(query.toString());
459     }
460
461     /**
462      * Save the Role to DB.
463      * 
464      * @param name         User Name.
465      * @param filteredRole Role Name.
466      * @param userId       User LoginID.
467      */
468     private void savePolicyRoles(String name, String filteredRole, String userId) {
469         UserInfo userInfo = new UserInfo();
470         userInfo.setUserLoginId(userId);
471         userInfo.setUserName(name);
472         commonClassDao.save(userInfo);
473         Roles role = new Roles();
474         role.setName(name);
475         role.setRole(filteredRole);
476         role.setLoginId(userId);
477         commonClassDao.save(role);
478     }
479
480     /**
481      * Filter the list of roles hierarchy wise.
482      * 
483      * @param newRoles list of roles from request.
484      * @return
485      */
486     private List<String> filterRole(List<String> newRoles) {
487         List<String> roles = new ArrayList<>();
488         boolean superCheck = false;
489         for (String role : newRoles) {
490             if ("Policy Super Guest".equalsIgnoreCase(role.trim())) {
491                 superCheck = true;
492                 roles.add("super-guest");
493             } else if ("Policy Super Editor".equalsIgnoreCase(role.trim())) {
494                 superCheck = true;
495                 roles.clear();
496                 roles.add("super-editor");
497             } else if ("Policy Super Admin".equalsIgnoreCase(role.trim())
498                     || "System Administrator".equalsIgnoreCase(role.trim())
499                     || "Standard User".equalsIgnoreCase(role.trim())) {
500                 superCheck = true;
501                 roles.clear();
502                 roles.add(SUPERADMIN);
503             }
504             if (!roles.contains(SUPERADMIN) || (POLICYGUEST.equalsIgnoreCase(role) && !superCheck)) {
505                 if ("Policy Admin".equalsIgnoreCase(role.trim())) {
506                     roles.add("admin");
507                 } else if ("Policy Editor".equalsIgnoreCase(role.trim())) {
508                     roles.add("editor");
509                 } else if (POLICYGUEST.equalsIgnoreCase(role.trim())) {
510                     roles.add("guest");
511                 }
512             }
513         }
514         return roles;
515     }
516
517     public PAPPolicyEngine getPapEngine() {
518         return papEngine;
519     }
520
521     public static void setPapEngine(PAPPolicyEngine papEngine) {
522         PolicyController.papEngine = papEngine;
523     }
524
525     /**
526      * Get UserName based on LoginID.
527      * 
528      * @param createdBy loginID.
529      * @return name.
530      */
531     public String getUserName(String createdBy) {
532         String loginId = createdBy;
533         List<Object> data = commonClassDao.getDataById(UserInfo.class, LOGINID, loginId);
534         return data.get(0).toString();
535     }
536
537     /**
538      * Check if the Policy is Active or not.
539      * 
540      * @param query sql query.
541      * @return boolean.
542      */
543     public static boolean getActivePolicy(String query) {
544         return !commonClassDao.getDataByQuery(query, new SimpleBindings()).isEmpty();
545     }
546
547     public void executeQuery(String query) {
548         commonClassDao.updateQuery(query);
549     }
550
551     public void saveData(Object cloneEntity) {
552         commonClassDao.save(cloneEntity);
553     }
554
555     public void updateData(Object entity) {
556         commonClassDao.update(entity);
557     }
558
559     public void deleteData(Object entity) {
560         commonClassDao.delete(entity);
561     }
562
563     public List<Object> getData(@SuppressWarnings("rawtypes") Class className) {
564         return commonClassDao.getData(className);
565     }
566
567     public PolicyVersion getPolicyEntityFromPolicyVersion(String query) {
568         return (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", query);
569     }
570
571     public List<Object> getDataByQuery(String query, SimpleBindings params) {
572         return commonClassDao.getDataByQuery(query, params);
573     }
574
575     @SuppressWarnings("rawtypes")
576     public Object getEntityItem(Class className, String columname, String key) {
577         return commonClassDao.getEntityItem(className, columname, key);
578     }
579
580     /**
581      * Watch Policy Function.
582      * 
583      * @param entity     PolicyVersion entity.
584      * @param policyName updated policy name.
585      * @param mode       type of action rename/delete/import.
586      */
587     public void watchPolicyFunction(PolicyVersion entity, String policyName, String mode) {
588         PolicyNotificationMail email = new PolicyNotificationMail();
589         try {
590             email.sendMail(entity, policyName, mode, commonClassDao);
591         } catch (MessagingException e) {
592             policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR
593                     + "Excepton Occured while Renaming/Deleting a Policy or Scope" + e);
594         }
595     }
596
597     /**
598      * Switch Version Policy Content.
599      * 
600      * @param pName which is used to find associated versions.
601      * @return list of available versions based on policy name.
602      */
603     public JSONObject switchVersionPolicyContent(String pName) {
604         String policyName = pName;
605         String dbCheckName = policyName.replace("/", ".");
606         if (dbCheckName.contains("Config_")) {
607             dbCheckName = dbCheckName.replace(".Config_", ":Config_");
608         } else if (dbCheckName.contains("Action_")) {
609             dbCheckName = dbCheckName.replace(".Action_", ":Action_");
610         } else if (dbCheckName.contains("Decision_MS_")) {
611             dbCheckName = dbCheckName.replace(".Decision_MS_", ":Decision_MS_");
612         } else if (dbCheckName.contains("Decision_")) {
613             dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
614         }
615         String[] splitDbCheckName = dbCheckName.split(":");
616         String query = "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0";
617         SimpleBindings params = new SimpleBindings();
618         params.put("splitDBCheckName1", splitDbCheckName[1] + "%");
619         params.put("splitDBCheckName0", splitDbCheckName[0]);
620         List<Object> policyEntity = commonClassDao.getDataByQuery(query, params);
621         List<String> av = new ArrayList<>();
622         for (Object entity : policyEntity) {
623             PolicyEntity pEntity = (PolicyEntity) entity;
624             String removeExtension = pEntity.getPolicyName().replace(".xml", "");
625             String version = removeExtension.substring(removeExtension.lastIndexOf('.') + 1);
626             String userName = getUserId(pEntity, "@ModifiedBy:");
627             av.add(version + " | " + pEntity.getModifiedDate() + " | " + userName);
628         }
629         if (policyName.contains("/")) {
630             policyName = policyName.replace("/", File.separator);
631         }
632         PolicyVersion entity = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName",
633                 policyName);
634         JSONObject el = new JSONObject();
635         el.put("activeVersion", entity.getActiveVersion());
636         el.put("availableVersions", av);
637         el.put("highestVersion", entity.getHigherVersion());
638         return el;
639     }
640
641     public String getUserId(PolicyEntity data, String value) {
642         String userId = "";
643         String uValue = value;
644         String description = getDescription(data);
645         if (description.contains(uValue)) {
646             userId = description.substring(description.indexOf(uValue) + uValue.length(),
647                     description.lastIndexOf(uValue));
648         }
649         UserInfo userInfo = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", userId);
650         if (userInfo == null) {
651             return SUPERADMIN;
652         }
653         return userInfo.getUserName();
654     }
655
656     public String getDescription(PolicyEntity data) {
657         InputStream stream = new ByteArrayInputStream(data.getPolicyData().getBytes(StandardCharsets.UTF_8));
658         Object policy = XACMLPolicyScanner.readPolicy(stream);
659         if (policy instanceof PolicySetType) {
660             return ((PolicySetType) policy).getDescription();
661         } else if (policy instanceof PolicyType) {
662             return ((PolicyType) policy).getDescription();
663         } else {
664             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Expecting a PolicySet/Policy/Rule object. Got: "
665                     + policy.getClass().getCanonicalName());
666             return null;
667         }
668     }
669
670     public String[] getUserInfo(PolicyEntity data, List<PolicyVersion> activePolicies) {
671         String policyName = data.getScope().replace(".", File.separator) + File.separator
672                 + data.getPolicyName().substring(0, data.getPolicyName().indexOf('.'));
673         PolicyVersion pVersion = activePolicies.stream().filter(a -> policyName.equals(a.getPolicyName())).findAny()
674                 .orElse(null);
675         String[] result = new String[2];
676
677         UserInfo userCreate = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", pVersion.getCreatedBy());
678         UserInfo userModify = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", pVersion.getModifiedBy());
679         result[0] = userCreate != null ? userCreate.getUserName() : "super-admin";
680         result[1] = userModify != null ? userModify.getUserName() : "super-admin";
681
682         return result;
683     }
684
685     public static String getLogTableLimit() {
686         return logTableLimit;
687     }
688
689     public static void setLogTableLimit(String logTableLimit) {
690         PolicyController.logTableLimit = logTableLimit;
691     }
692
693     public static String getSystemAlertTableLimit() {
694         return systemAlertTableLimit;
695     }
696
697     public static void setSystemAlertTableLimit(String systemAlertTableLimit) {
698         PolicyController.systemAlertTableLimit = systemAlertTableLimit;
699     }
700
701     public static CommonClassDao getCommonClassDao() {
702         return commonClassDao;
703     }
704
705     public static void setCommonClassDao(CommonClassDao commonClassDao) {
706         PolicyController.commonClassDao = commonClassDao;
707     }
708
709     public static Map<Datatype, List<FunctionDefinition>> getMapDatatype2Function() {
710         return mapDatatype2Function;
711     }
712
713     public static void setMapDatatype2Function(Map<Datatype, List<FunctionDefinition>> mapDatatype2Function) {
714         PolicyController.mapDatatype2Function = mapDatatype2Function;
715     }
716
717     public static Map<String, FunctionDefinition> getMapID2Function() {
718         return mapID2Function;
719     }
720
721     public static void setMapID2Function(Map<String, FunctionDefinition> mapID2Function) {
722         PolicyController.mapID2Function = mapID2Function;
723     }
724
725     public static String getSmtpHost() {
726         return smtpHost;
727     }
728
729     public static void setSmtpHost(String smtpHost) {
730         PolicyController.smtpHost = smtpHost;
731     }
732
733     public static String getSmtpPort() {
734         return smtpPort;
735     }
736
737     public static void setSmtpPort(String smtpPort) {
738         PolicyController.smtpPort = smtpPort;
739     }
740
741     public static String getSmtpUsername() {
742         return smtpUsername;
743     }
744
745     public static void setSmtpUsername(String smtpUsername) {
746         PolicyController.smtpUsername = smtpUsername;
747     }
748
749     public static String getSmtpPassword() {
750         return smtpPassword;
751     }
752
753     public static void setSmtpPassword(String smtpPassword) {
754         PolicyController.smtpPassword = smtpPassword;
755     }
756
757     public static String getSmtpApplicationName() {
758         return smtpApplicationName;
759     }
760
761     public static void setSmtpApplicationName(String smtpApplicationName) {
762         PolicyController.smtpApplicationName = smtpApplicationName;
763     }
764
765     public static String getSmtpEmailExtension() {
766         return smtpEmailExtension;
767     }
768
769     public static void setSmtpEmailExtension(String smtpEmailExtension) {
770         PolicyController.smtpEmailExtension = smtpEmailExtension;
771     }
772
773     public static String getLogdbDriver() {
774         return logdbDriver;
775     }
776
777     public static void setLogdbDriver(String logdbDriver) {
778         PolicyController.logdbDriver = logdbDriver;
779     }
780
781     public static String getLogdbUrl() {
782         return logdbUrl;
783     }
784
785     public static void setLogdbUrl(String logdbUrl) {
786         PolicyController.logdbUrl = logdbUrl;
787     }
788
789     public static String getLogdbUserName() {
790         return logdbUserName;
791     }
792
793     public static void setLogdbUserName(String logdbUserName) {
794         PolicyController.logdbUserName = logdbUserName;
795     }
796
797     public static String getLogdbPassword() {
798         return logdbPassword;
799     }
800
801     public static void setLogdbPassword(String logdbPassword) {
802         PolicyController.logdbPassword = logdbPassword;
803     }
804
805     public static String getLogdbDialect() {
806         return logdbDialect;
807     }
808
809     public static void setLogdbDialect(String logdbDialect) {
810         PolicyController.logdbDialect = logdbDialect;
811     }
812
813     public static String getXacmldbUrl() {
814         return xacmldbUrl;
815     }
816
817     public static void setXacmldbUrl(String xacmldbUrl) {
818         PolicyController.xacmldbUrl = xacmldbUrl;
819     }
820
821     public static String getXacmldbUserName() {
822         return xacmldbUserName;
823     }
824
825     public static void setXacmldbUserName(String xacmldbUserName) {
826         PolicyController.xacmldbUserName = xacmldbUserName;
827     }
828
829     public static String getXacmldbPassword() {
830         return xacmldbPassword;
831     }
832
833     public static void setXacmldbPassword(String xacmldbPassword) {
834         PolicyController.xacmldbPassword = xacmldbPassword;
835     }
836
837     public static String getAutoPushAvailable() {
838         return autoPushAvailable;
839     }
840
841     public static void setAutoPushAvailable(String autoPushAvailable) {
842         PolicyController.autoPushAvailable = autoPushAvailable;
843     }
844
845     public static String getAutoPushDSClosedLoop() {
846         return autoPushDSClosedLoop;
847     }
848
849     public static void setAutoPushDSClosedLoop(String autoPushDSClosedLoop) {
850         PolicyController.autoPushDSClosedLoop = autoPushDSClosedLoop;
851     }
852
853     public static String getAutoPushDSFirewall() {
854         return autoPushDSFirewall;
855     }
856
857     public static void setAutoPushDSFirewall(String autoPushDSFirewall) {
858         PolicyController.autoPushDSFirewall = autoPushDSFirewall;
859     }
860
861     public static String getAutoPushDSMicroservice() {
862         return autoPushDSMicroservice;
863     }
864
865     public static void setAutoPushDSMicroservice(String autoPushDSMicroservice) {
866         PolicyController.autoPushDSMicroservice = autoPushDSMicroservice;
867     }
868
869     public static String getAutoPushPDPGroup() {
870         return autoPushPDPGroup;
871     }
872
873     public static void setAutoPushPDPGroup(String autoPushPDPGroup) {
874         PolicyController.autoPushPDPGroup = autoPushPDPGroup;
875     }
876
877     public static String getPapUrl() {
878         return papUrl;
879     }
880
881     public static void setPapUrl(String papUrl) {
882         PolicyController.papUrl = papUrl;
883     }
884
885     public static String getMsOnapName() {
886         return msOnapName;
887     }
888
889     public static void setMsOnapName(String msOnapName) {
890         PolicyController.msOnapName = msOnapName;
891     }
892
893     public static String getMsPolicyName() {
894         return msPolicyName;
895     }
896
897     public static void setMsPolicyName(String msPolicyName) {
898         PolicyController.msPolicyName = msPolicyName;
899     }
900
901     public static String getConfigHome() {
902         return configHome;
903     }
904
905     public static void setConfigHome(String configHome) {
906         PolicyController.configHome = configHome;
907     }
908
909     public static String getActionHome() {
910         return actionHome;
911     }
912
913     public static void setActionHome(String actionHome) {
914         PolicyController.actionHome = actionHome;
915     }
916
917     public static Object getMapaccess() {
918         return mapAccess;
919     }
920
921     public static String getPolicydata() {
922         return policyData;
923     }
924
925     public static String getCharacterencoding() {
926         return characterEncoding;
927     }
928
929     public static String getContenttype() {
930         return contentType;
931     }
932
933     public static String getFile() {
934         return file;
935     }
936
937     /**
938      * Set File Size limit.
939      * 
940      * @param uploadSize value.
941      */
942     public static void setFileSizeLimit(String uploadSize) {
943         // Default size limit is 30MB
944         if (uploadSize == null || uploadSize.isEmpty()) {
945             fileSizeLimit = 30000000;
946         } else {
947             fileSizeLimit = Long.parseLong(uploadSize);
948         }
949     }
950
951     public static long getFileSizeLimit() {
952         return fileSizeLimit;
953     }
954
955     /**
956      * Function to convert date.
957      * 
958      * @param dateTTL input date value.
959      * @return
960      */
961     public String convertDate(String dateTTL) {
962         String formateDate = null;
963         if (dateTTL.contains("-")) {
964             formateDate = dateTTL.replace("-", "/");
965         }
966         return formateDate;
967     }
968 }