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