Fix Sonar Issues policy/engine POLICY-SDK-APP module
[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.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 java.nio.charset.StandardCharsets;
40 import javax.annotation.PostConstruct;
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         email.sendMail(entity, policyName, mode, commonClassDao);
590     }
591
592     /**
593      * Switch Version Policy Content.
594      * 
595      * @param pName which is used to find associated versions.
596      * @return list of available versions based on policy name.
597      */
598     public JSONObject switchVersionPolicyContent(String pName) {
599         String policyName = pName;
600         String dbCheckName = policyName.replace("/", ".");
601         if (dbCheckName.contains("Config_")) {
602             dbCheckName = dbCheckName.replace(".Config_", ":Config_");
603         } else if (dbCheckName.contains("Action_")) {
604             dbCheckName = dbCheckName.replace(".Action_", ":Action_");
605         } else if (dbCheckName.contains("Decision_MS_")) {
606             dbCheckName = dbCheckName.replace(".Decision_MS_", ":Decision_MS_");
607         } else if (dbCheckName.contains("Decision_")) {
608             dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
609         }
610         String[] splitDbCheckName = dbCheckName.split(":");
611         String query = "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0";
612         SimpleBindings params = new SimpleBindings();
613         params.put("splitDBCheckName1", splitDbCheckName[1] + "%");
614         params.put("splitDBCheckName0", splitDbCheckName[0]);
615         List<Object> policyEntity = commonClassDao.getDataByQuery(query, params);
616         List<String> av = new ArrayList<>();
617         for (Object entity : policyEntity) {
618             PolicyEntity pEntity = (PolicyEntity) entity;
619             String removeExtension = pEntity.getPolicyName().replace(".xml", "");
620             String version = removeExtension.substring(removeExtension.lastIndexOf('.') + 1);
621             String userName = getUserId(pEntity, "@ModifiedBy:");
622             av.add(version + " | " + pEntity.getModifiedDate() + " | " + userName);
623         }
624         if (policyName.contains("/")) {
625             policyName = policyName.replace("/", File.separator);
626         }
627         PolicyVersion entity = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName",
628                 policyName);
629         JSONObject el = new JSONObject();
630         el.put("activeVersion", entity.getActiveVersion());
631         el.put("availableVersions", av);
632         el.put("highestVersion", entity.getHigherVersion());
633         return el;
634     }
635
636     public String getUserId(PolicyEntity data, String value) {
637         String userId = "";
638         String uValue = value;
639         String description = getDescription(data);
640         if (description.contains(uValue)) {
641             userId = description.substring(description.indexOf(uValue) + uValue.length(),
642                     description.lastIndexOf(uValue));
643         }
644         UserInfo userInfo = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", userId);
645         if (userInfo == null) {
646             return SUPERADMIN;
647         }
648         return userInfo.getUserName();
649     }
650
651     public String getDescription(PolicyEntity data) {
652         InputStream stream = new ByteArrayInputStream(data.getPolicyData().getBytes(StandardCharsets.UTF_8));
653         Object policy = XACMLPolicyScanner.readPolicy(stream);
654         if (policy instanceof PolicySetType) {
655             return ((PolicySetType) policy).getDescription();
656         } else if (policy instanceof PolicyType) {
657             return ((PolicyType) policy).getDescription();
658         } else {
659             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Expecting a PolicySet/Policy/Rule object. Got: "
660                     + policy.getClass().getCanonicalName());
661             return null;
662         }
663     }
664
665     public String[] getUserInfo(PolicyEntity data, List<PolicyVersion> activePolicies) {
666         String policyName = data.getScope().replace(".", File.separator) + File.separator
667                 + data.getPolicyName().substring(0, data.getPolicyName().indexOf('.'));
668         PolicyVersion pVersion = activePolicies.stream().filter(a -> policyName.equals(a.getPolicyName())).findAny()
669                 .orElse(null);
670         String[] result = new String[2];
671
672         UserInfo userCreate = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", pVersion.getCreatedBy());
673         UserInfo userModify = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", pVersion.getModifiedBy());
674         result[0] = userCreate != null ? userCreate.getUserName() : "super-admin";
675         result[1] = userModify != null ? userModify.getUserName() : "super-admin";
676
677         return result;
678     }
679
680     public static String getLogTableLimit() {
681         return logTableLimit;
682     }
683
684     public static void setLogTableLimit(String logTableLimit) {
685         PolicyController.logTableLimit = logTableLimit;
686     }
687
688     public static String getSystemAlertTableLimit() {
689         return systemAlertTableLimit;
690     }
691
692     public static void setSystemAlertTableLimit(String systemAlertTableLimit) {
693         PolicyController.systemAlertTableLimit = systemAlertTableLimit;
694     }
695
696     public static CommonClassDao getCommonClassDao() {
697         return commonClassDao;
698     }
699
700     public static void setCommonClassDao(CommonClassDao commonClassDao) {
701         PolicyController.commonClassDao = commonClassDao;
702     }
703
704     public static Map<Datatype, List<FunctionDefinition>> getMapDatatype2Function() {
705         return mapDatatype2Function;
706     }
707
708     public static void setMapDatatype2Function(Map<Datatype, List<FunctionDefinition>> mapDatatype2Function) {
709         PolicyController.mapDatatype2Function = mapDatatype2Function;
710     }
711
712     public static Map<String, FunctionDefinition> getMapID2Function() {
713         return mapID2Function;
714     }
715
716     public static void setMapID2Function(Map<String, FunctionDefinition> mapID2Function) {
717         PolicyController.mapID2Function = mapID2Function;
718     }
719
720     public static String getSmtpHost() {
721         return smtpHost;
722     }
723
724     public static void setSmtpHost(String smtpHost) {
725         PolicyController.smtpHost = smtpHost;
726     }
727
728     public static String getSmtpPort() {
729         return smtpPort;
730     }
731
732     public static void setSmtpPort(String smtpPort) {
733         PolicyController.smtpPort = smtpPort;
734     }
735
736     public static String getSmtpUsername() {
737         return smtpUsername;
738     }
739
740     public static void setSmtpUsername(String smtpUsername) {
741         PolicyController.smtpUsername = smtpUsername;
742     }
743
744     public static String getSmtpPassword() {
745         return smtpPassword;
746     }
747
748     public static void setSmtpPassword(String smtpPassword) {
749         PolicyController.smtpPassword = smtpPassword;
750     }
751
752     public static String getSmtpApplicationName() {
753         return smtpApplicationName;
754     }
755
756     public static void setSmtpApplicationName(String smtpApplicationName) {
757         PolicyController.smtpApplicationName = smtpApplicationName;
758     }
759
760     public static String getSmtpEmailExtension() {
761         return smtpEmailExtension;
762     }
763
764     public static void setSmtpEmailExtension(String smtpEmailExtension) {
765         PolicyController.smtpEmailExtension = smtpEmailExtension;
766     }
767
768     public static String getLogdbDriver() {
769         return logdbDriver;
770     }
771
772     public static void setLogdbDriver(String logdbDriver) {
773         PolicyController.logdbDriver = logdbDriver;
774     }
775
776     public static String getLogdbUrl() {
777         return logdbUrl;
778     }
779
780     public static void setLogdbUrl(String logdbUrl) {
781         PolicyController.logdbUrl = logdbUrl;
782     }
783
784     public static String getLogdbUserName() {
785         return logdbUserName;
786     }
787
788     public static void setLogdbUserName(String logdbUserName) {
789         PolicyController.logdbUserName = logdbUserName;
790     }
791
792     public static String getLogdbPassword() {
793         return logdbPassword;
794     }
795
796     public static void setLogdbPassword(String logdbPassword) {
797         PolicyController.logdbPassword = logdbPassword;
798     }
799
800     public static String getLogdbDialect() {
801         return logdbDialect;
802     }
803
804     public static void setLogdbDialect(String logdbDialect) {
805         PolicyController.logdbDialect = logdbDialect;
806     }
807
808     public static String getXacmldbUrl() {
809         return xacmldbUrl;
810     }
811
812     public static void setXacmldbUrl(String xacmldbUrl) {
813         PolicyController.xacmldbUrl = xacmldbUrl;
814     }
815
816     public static String getXacmldbUserName() {
817         return xacmldbUserName;
818     }
819
820     public static void setXacmldbUserName(String xacmldbUserName) {
821         PolicyController.xacmldbUserName = xacmldbUserName;
822     }
823
824     public static String getXacmldbPassword() {
825         return xacmldbPassword;
826     }
827
828     public static void setXacmldbPassword(String xacmldbPassword) {
829         PolicyController.xacmldbPassword = xacmldbPassword;
830     }
831
832     public static String getAutoPushAvailable() {
833         return autoPushAvailable;
834     }
835
836     public static void setAutoPushAvailable(String autoPushAvailable) {
837         PolicyController.autoPushAvailable = autoPushAvailable;
838     }
839
840     public static String getAutoPushDSClosedLoop() {
841         return autoPushDSClosedLoop;
842     }
843
844     public static void setAutoPushDSClosedLoop(String autoPushDSClosedLoop) {
845         PolicyController.autoPushDSClosedLoop = autoPushDSClosedLoop;
846     }
847
848     public static String getAutoPushDSFirewall() {
849         return autoPushDSFirewall;
850     }
851
852     public static void setAutoPushDSFirewall(String autoPushDSFirewall) {
853         PolicyController.autoPushDSFirewall = autoPushDSFirewall;
854     }
855
856     public static String getAutoPushDSMicroservice() {
857         return autoPushDSMicroservice;
858     }
859
860     public static void setAutoPushDSMicroservice(String autoPushDSMicroservice) {
861         PolicyController.autoPushDSMicroservice = autoPushDSMicroservice;
862     }
863
864     public static String getAutoPushPDPGroup() {
865         return autoPushPDPGroup;
866     }
867
868     public static void setAutoPushPDPGroup(String autoPushPDPGroup) {
869         PolicyController.autoPushPDPGroup = autoPushPDPGroup;
870     }
871
872     public static String getPapUrl() {
873         return papUrl;
874     }
875
876     public static void setPapUrl(String papUrl) {
877         PolicyController.papUrl = papUrl;
878     }
879
880     public static String getMsOnapName() {
881         return msOnapName;
882     }
883
884     public static void setMsOnapName(String msOnapName) {
885         PolicyController.msOnapName = msOnapName;
886     }
887
888     public static String getMsPolicyName() {
889         return msPolicyName;
890     }
891
892     public static void setMsPolicyName(String msPolicyName) {
893         PolicyController.msPolicyName = msPolicyName;
894     }
895
896     public static String getConfigHome() {
897         return configHome;
898     }
899
900     public static void setConfigHome(String configHome) {
901         PolicyController.configHome = configHome;
902     }
903
904     public static String getActionHome() {
905         return actionHome;
906     }
907
908     public static void setActionHome(String actionHome) {
909         PolicyController.actionHome = actionHome;
910     }
911
912     public static Object getMapaccess() {
913         return mapAccess;
914     }
915
916     public static String getPolicydata() {
917         return policyData;
918     }
919
920     public static String getCharacterencoding() {
921         return characterEncoding;
922     }
923
924     public static String getContenttype() {
925         return contentType;
926     }
927
928     public static String getFile() {
929         return file;
930     }
931
932     /**
933      * Set File Size limit.
934      * 
935      * @param uploadSize value.
936      */
937     public static void setFileSizeLimit(String uploadSize) {
938         // Default size limit is 30MB
939         if (uploadSize == null || uploadSize.isEmpty()) {
940             fileSizeLimit = 30000000;
941         } else {
942             fileSizeLimit = Long.parseLong(uploadSize);
943         }
944     }
945
946     public static long getFileSizeLimit() {
947         return fileSizeLimit;
948     }
949
950     /**
951      * Function to convert date.
952      * 
953      * @param dateTTL input date value.
954      * @return
955      */
956     public String convertDate(String dateTTL) {
957         String formateDate = null;
958         if (dateTTL.contains("-")) {
959             formateDate = dateTTL.replace("-", "/");
960         }
961         return formateDate;
962     }
963 }