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