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