Sonar cleanup in controllers etc
[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 isJunit) {
168         PolicyController.jUnit = isJunit;
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             response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
325         } catch (Exception e) {
326             policyLogger.error(
327                     XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while retriving the Function Definition data" + e);
328         }
329     }
330
331     /**
332      * Get PolicyEntity Data from db.
333      *
334      * @param scope scopeName.
335      * @param policyName policyName.
336      * @return policyEntity data.
337      */
338     public PolicyEntity getPolicyEntityData(String scope, String policyName) {
339         String key = scope + ":" + policyName;
340         List<Object> data = commonClassDao.getDataById(PolicyEntity.class, "scope:policyName", key);
341         return (PolicyEntity) data.get(0);
342     }
343
344     /**
345      * Get Policy User Roles from db.
346      *
347      * @param userId LoginID.
348      * @return list of Roles.
349      */
350     public List<String> getRolesOfUser(String userId) {
351         List<String> rolesList = new ArrayList<>();
352         List<Object> roles = commonClassDao.getDataById(Roles.class, LOGINID, userId);
353         for (Object role : roles) {
354             rolesList.add(((Roles) role).getRole());
355         }
356         return rolesList;
357     }
358
359     public List<Object> getRoles(String userId) {
360         return commonClassDao.getDataById(Roles.class, LOGINID, userId);
361     }
362
363     /**
364      * Get List of User Roles.
365      *
366      * @param request HttpServletRequest.
367      * @param response HttpServletResponse.
368      */
369     @RequestMapping(
370             value = {"/get_UserRolesData"},
371             method = {org.springframework.web.bind.annotation.RequestMethod.GET},
372             produces = MediaType.APPLICATION_JSON_VALUE)
373     public void getUserRolesEntityData(HttpServletRequest request, HttpServletResponse response) {
374         try {
375             String userId = UserUtils.getUserSession(request).getOrgUserId();
376             Map<String, Object> model = new HashMap<>();
377             ObjectMapper mapper = new ObjectMapper();
378             model.put("userRolesDatas", mapper.writeValueAsString(getRolesOfUser(userId)));
379             response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
380         } catch (Exception e) {
381             policyLogger.error("Exception Occured" + e);
382         }
383     }
384
385     /**
386      * Policy tabs Model and View.
387      *
388      * @param request Request input.
389      * @return view model.
390      */
391     @RequestMapping(value = {"/policy", "/policy/Editor"}, method = RequestMethod.GET)
392     public ModelAndView view(HttpServletRequest request) {
393         getUserRoleFromSession(request);
394         String myRequestUrl = request.getRequestURL().toString();
395         try {
396             //
397             // Set the URL for the RESTful PAP Engine
398             //
399             setPapEngine(new RESTfulPAPEngine(myRequestUrl));
400             new PDPGroupContainer(new RESTfulPAPEngine(myRequestUrl));
401         } catch (Exception e) {
402             policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Exception Occured while loading PAP" + e);
403         }
404         Map<String, Object> model = new HashMap<>();
405         return new ModelAndView("policy_Editor", "model", model);
406     }
407
408     /**
409      * Read the role from session for inserting into the database.
410      *
411      * @param request Request input for Role.
412      */
413     public void getUserRoleFromSession(HttpServletRequest request) {
414         // While user landing on Policy page, fetch the userId and Role from
415         // session.
416         // And, Query the Roles table and if user not exists or else modified
417         // update the Roles table.
418         List<String> roles;
419         List<String> newRoles = new ArrayList<>();
420         String userId = UserUtils.getUserSession(request).getOrgUserId();
421         String name = UserUtils.getUserSession(request).getFullName();
422         @SuppressWarnings("unchecked")
423         Set<UserApp> userApps = UserUtils.getUserSession(request).getUserApps();
424         for (UserApp userApp : userApps) {
425             newRoles.add(userApp.getRole().getName());
426         }
427         List<Object> userRoles = getRoles(userId);
428         List<String> filteredRoles = filterRole(newRoles);
429         if (!filteredRoles.isEmpty()) {
430             cleanUpRoles(filteredRoles, userId);
431         }
432         for (String filteredRole : filteredRoles) {
433             if (userRoles == null || userRoles.isEmpty()) {
434                 savePolicyRoles(name, filteredRole, userId);
435             } else {
436                 userRoles = getRoles(userId);
437                 Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
438                 roles = pair.second;
439                 if (!roles.contains(filteredRole)) {
440                     savePolicyRoles(name, filteredRole, userId);
441                 }
442             }
443         }
444     }
445
446     /**
447      * Build a delete query for cleaning up roles and execute it.
448      *
449      * @param filteredRoles Filtered roles list.
450      * @param userId UserID.
451      */
452     private void cleanUpRoles(List<String> filteredRoles, String userId) {
453         StringBuilder query = new StringBuilder();
454         query.append("delete from Roles where loginid = '" + userId + "'");
455         if (filteredRoles.contains(SUPERADMIN)) {
456             query.append("and not role = '" + SUPERADMIN + "'");
457         } else {
458             for (String filteredRole : filteredRoles) {
459                 query.append("and not role = '" + filteredRole + "'");
460             }
461         }
462         query.append("and id > 0");
463         commonClassDao.updateQuery(query.toString());
464     }
465
466     /**
467      * Save the Role to DB.
468      *
469      * @param name User Name.
470      * @param filteredRole Role Name.
471      * @param userId User LoginID.
472      */
473     private void savePolicyRoles(String name, String filteredRole, String userId) {
474         UserInfo userInfo = new UserInfo();
475         userInfo.setUserLoginId(userId);
476         userInfo.setUserName(name);
477         commonClassDao.save(userInfo);
478         Roles role = new Roles();
479         role.setName(name);
480         role.setRole(filteredRole);
481         role.setLoginId(userId);
482         commonClassDao.save(role);
483     }
484
485     /**
486      * Filter the list of roles hierarchy wise.
487      *
488      * @param newRoles list of roles from request.
489      * @return
490      */
491     private List<String> filterRole(List<String> newRoles) {
492         List<String> roles = new ArrayList<>();
493         boolean superCheck = false;
494         for (String role : newRoles) {
495             if ("Policy Super Guest".equalsIgnoreCase(role.trim())) {
496                 superCheck = true;
497                 roles.add("super-guest");
498             } else if ("Policy Super Editor".equalsIgnoreCase(role.trim())) {
499                 superCheck = true;
500                 roles.clear();
501                 roles.add("super-editor");
502             } else if ("Policy Super Admin".equalsIgnoreCase(role.trim())
503                     || "System Administrator".equalsIgnoreCase(role.trim())
504                     || "Standard User".equalsIgnoreCase(role.trim())) {
505                 superCheck = true;
506                 roles.clear();
507                 roles.add(SUPERADMIN);
508             }
509             if (!roles.contains(SUPERADMIN) || (POLICYGUEST.equalsIgnoreCase(role) && !superCheck)) {
510                 if ("Policy Admin".equalsIgnoreCase(role.trim())) {
511                     roles.add("admin");
512                 } else if ("Policy Editor".equalsIgnoreCase(role.trim())) {
513                     roles.add("editor");
514                 } else if (POLICYGUEST.equalsIgnoreCase(role.trim())) {
515                     roles.add("guest");
516                 }
517             }
518         }
519         return roles;
520     }
521
522     public PAPPolicyEngine getPapEngine() {
523         return papEngine;
524     }
525
526     public static void setPapEngine(PAPPolicyEngine papEngine) {
527         PolicyController.papEngine = papEngine;
528     }
529
530     /**
531      * Get UserName based on LoginID.
532      *
533      * @param createdBy loginID.
534      * @return name.
535      */
536     public String getUserName(String createdBy) {
537         String loginId = createdBy;
538         List<Object> data = commonClassDao.getDataById(UserInfo.class, LOGINID, loginId);
539         return data.get(0).toString();
540     }
541
542     /**
543      * Check if the Policy is Active or not.
544      *
545      * @param query sql query.
546      * @return boolean.
547      */
548     public static boolean getActivePolicy(String query) {
549         return !commonClassDao.getDataByQuery(query, new SimpleBindings()).isEmpty();
550     }
551
552     public void executeQuery(String query) {
553         commonClassDao.updateQuery(query);
554     }
555
556     public void saveData(Object cloneEntity) {
557         commonClassDao.save(cloneEntity);
558     }
559
560     public void updateData(Object entity) {
561         commonClassDao.update(entity);
562     }
563
564     public void deleteData(Object entity) {
565         commonClassDao.delete(entity);
566     }
567
568     public List<Object> getData(@SuppressWarnings("rawtypes") Class className) {
569         return commonClassDao.getData(className);
570     }
571
572     public PolicyVersion getPolicyEntityFromPolicyVersion(String query) {
573         return (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", query);
574     }
575
576     public List<Object> getDataByQuery(String query, SimpleBindings params) {
577         return commonClassDao.getDataByQuery(query, params);
578     }
579
580     @SuppressWarnings("rawtypes")
581     public Object getEntityItem(Class className, String columname, String key) {
582         return commonClassDao.getEntityItem(className, columname, key);
583     }
584
585     /**
586      * Watch Policy Function.
587      *
588      * @param entity PolicyVersion entity.
589      * @param policyName updated policy name.
590      * @param mode type of action rename/delete/import.
591      */
592     public void watchPolicyFunction(PolicyVersion entity, String policyName, String mode) {
593         PolicyNotificationMail email = new PolicyNotificationMail();
594         email.sendMail(entity, policyName, mode, commonClassDao);
595     }
596
597     /**
598      * Switch Version Policy Content.
599      *
600      * @param thePolicyName which is used to find associated versions.
601      * @return list of available versions based on policy name.
602      */
603     public JSONObject switchVersionPolicyContent(String thePolicyName) {
604         String policyName = thePolicyName;
605         String dbCheckName = policyName.replace("/", ".");
606         if (dbCheckName.contains("Config_")) {
607             dbCheckName = dbCheckName.replace(".Config_", ":Config_");
608         } else if (dbCheckName.contains("Action_")) {
609             dbCheckName = dbCheckName.replace(".Action_", ":Action_");
610         } else if (dbCheckName.contains("Decision_MS_")) {
611             dbCheckName = dbCheckName.replace(".Decision_MS_", ":Decision_MS_");
612         } else if (dbCheckName.contains("Decision_")) {
613             dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
614         }
615         String[] splitDbCheckName = dbCheckName.split(":");
616         String query = "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0";
617         SimpleBindings params = new SimpleBindings();
618         params.put("splitDBCheckName1", splitDbCheckName[1] + "%");
619         params.put("splitDBCheckName0", splitDbCheckName[0]);
620         List<String> av = new ArrayList<>();
621         for (Object entity : commonClassDao.getDataByQuery(query, params)) {
622             PolicyEntity policyEntity = (PolicyEntity) entity;
623             String removeExtension = policyEntity.getPolicyName().replace(".xml", "");
624             String version = removeExtension.substring(removeExtension.lastIndexOf('.') + 1);
625             String userName = getUserId(policyEntity, "@ModifiedBy:");
626             av.add(version + " | " + policyEntity.getModifiedDate() + " | " + userName);
627         }
628         if (policyName.contains("/")) {
629             policyName = policyName.replace("/", File.separator);
630         }
631         PolicyVersion entity =
632                 (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", policyName);
633         JSONObject el = new JSONObject();
634         el.put("activeVersion", entity.getActiveVersion());
635         el.put("availableVersions", av);
636         el.put("highestVersion", entity.getHigherVersion());
637         return el;
638     }
639
640     /**
641      * getUserId.
642      *
643      * @param data PolicyEntity
644      * @param value String
645      * @return String
646      */
647     public String getUserId(PolicyEntity data, String value) {
648         String userId = "";
649         String userValue = value; // Why?
650         String description = getDescription(data);
651         if (description.contains(userValue)) {
652             userId = description.substring(description.indexOf(userValue) + userValue.length(),
653                     description.lastIndexOf(userValue));
654         }
655         UserInfo userInfo = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", userId);
656         if (userInfo == null) {
657             return SUPERADMIN;
658         }
659         return userInfo.getUserName();
660     }
661
662     /**
663      * getDescription.
664      *
665      * @param data PolicyEntity
666      * @return String
667      */
668     public String getDescription(PolicyEntity data) {
669         InputStream stream = new ByteArrayInputStream(data.getPolicyData().getBytes(StandardCharsets.UTF_8));
670         Object policy = XACMLPolicyScanner.readPolicy(stream);
671         if (policy instanceof PolicySetType) {
672             return ((PolicySetType) policy).getDescription();
673         } else if (policy instanceof PolicyType) {
674             return ((PolicyType) policy).getDescription();
675         }
676         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Expecting a PolicySet/Policy/Rule object. Got: "
677                 + policy.getClass().getCanonicalName());
678         return null;
679     }
680
681     /**
682      * getUserInfo.
683      *
684      * @param data PolicyEntity
685      * @param activePolicies list of active policies
686      * @return array of String
687      */
688     public String[] getUserInfo(PolicyEntity data, List<PolicyVersion> activePolicies) {
689         String policyName = data.getScope().replace(".", File.separator) + File.separator
690                 + data.getPolicyName().substring(0, data.getPolicyName().indexOf('.'));
691         PolicyVersion polVersion =
692                 activePolicies.stream().filter(a -> policyName.equals(a.getPolicyName())).findAny().orElse(null);
693         String[] result = new String[2];
694         UserInfo userCreate = null;
695         UserInfo userModify = null;
696         if (polVersion != null) {
697             userCreate = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", polVersion.getCreatedBy());
698             userModify = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", polVersion.getModifiedBy());
699         }
700
701         result[0] = userCreate != null ? userCreate.getUserName() : SUPERADMIN;
702         result[1] = userModify != null ? userModify.getUserName() : SUPERADMIN;
703
704         return result;
705     }
706
707     public static String getLogTableLimit() {
708         return logTableLimit;
709     }
710
711     public static void setLogTableLimit(String logTableLimit) {
712         PolicyController.logTableLimit = logTableLimit;
713     }
714
715     public static String getSystemAlertTableLimit() {
716         return systemAlertTableLimit;
717     }
718
719     public static void setSystemAlertTableLimit(String systemAlertTableLimit) {
720         PolicyController.systemAlertTableLimit = systemAlertTableLimit;
721     }
722
723     public static CommonClassDao getCommonClassDao() {
724         return commonClassDao;
725     }
726
727     public static void setCommonClassDao(CommonClassDao commonClassDao) {
728         PolicyController.commonClassDao = commonClassDao;
729     }
730
731     public static Map<Datatype, List<FunctionDefinition>> getMapDatatype2Function() {
732         return mapDatatype2Function;
733     }
734
735     public static void setMapDatatype2Function(Map<Datatype, List<FunctionDefinition>> mapDatatype2Function) {
736         PolicyController.mapDatatype2Function = mapDatatype2Function;
737     }
738
739     public static Map<String, FunctionDefinition> getMapID2Function() {
740         return mapID2Function;
741     }
742
743     public static void setMapID2Function(Map<String, FunctionDefinition> mapID2Function) {
744         PolicyController.mapID2Function = mapID2Function;
745     }
746
747     public static String getSmtpHost() {
748         return smtpHost;
749     }
750
751     public static void setSmtpHost(String smtpHost) {
752         PolicyController.smtpHost = smtpHost;
753     }
754
755     public static String getSmtpPort() {
756         return smtpPort;
757     }
758
759     public static void setSmtpPort(String smtpPort) {
760         PolicyController.smtpPort = smtpPort;
761     }
762
763     public static String getSmtpUsername() {
764         return smtpUsername;
765     }
766
767     public static void setSmtpUsername(String smtpUsername) {
768         PolicyController.smtpUsername = smtpUsername;
769     }
770
771     public static String getSmtpPassword() {
772         return smtpPassword;
773     }
774
775     public static void setSmtpPassword(String smtpPassword) {
776         PolicyController.smtpPassword = smtpPassword;
777     }
778
779     public static String getSmtpApplicationName() {
780         return smtpApplicationName;
781     }
782
783     public static void setSmtpApplicationName(String smtpApplicationName) {
784         PolicyController.smtpApplicationName = smtpApplicationName;
785     }
786
787     public static String getSmtpEmailExtension() {
788         return smtpEmailExtension;
789     }
790
791     public static void setSmtpEmailExtension(String smtpEmailExtension) {
792         PolicyController.smtpEmailExtension = smtpEmailExtension;
793     }
794
795     public static String getLogdbDriver() {
796         return logdbDriver;
797     }
798
799     public static void setLogdbDriver(String logdbDriver) {
800         PolicyController.logdbDriver = logdbDriver;
801     }
802
803     public static String getLogdbUrl() {
804         return logdbUrl;
805     }
806
807     public static void setLogdbUrl(String logdbUrl) {
808         PolicyController.logdbUrl = logdbUrl;
809     }
810
811     public static String getLogdbUserName() {
812         return logdbUserName;
813     }
814
815     public static void setLogdbUserName(String logdbUserName) {
816         PolicyController.logdbUserName = logdbUserName;
817     }
818
819     public static String getLogdbPassword() {
820         return logdbPassword;
821     }
822
823     public static void setLogdbPassword(String logdbPassword) {
824         PolicyController.logdbPassword = logdbPassword;
825     }
826
827     public static String getLogdbDialect() {
828         return logdbDialect;
829     }
830
831     public static void setLogdbDialect(String logdbDialect) {
832         PolicyController.logdbDialect = logdbDialect;
833     }
834
835     public static String getXacmldbUrl() {
836         return xacmldbUrl;
837     }
838
839     public static void setXacmldbUrl(String xacmldbUrl) {
840         PolicyController.xacmldbUrl = xacmldbUrl;
841     }
842
843     public static String getXacmldbUserName() {
844         return xacmldbUserName;
845     }
846
847     public static void setXacmldbUserName(String xacmldbUserName) {
848         PolicyController.xacmldbUserName = xacmldbUserName;
849     }
850
851     public static String getXacmldbPassword() {
852         return xacmldbPassword;
853     }
854
855     public static void setXacmldbPassword(String xacmldbPassword) {
856         PolicyController.xacmldbPassword = xacmldbPassword;
857     }
858
859     public static String getAutoPushAvailable() {
860         return autoPushAvailable;
861     }
862
863     public static void setAutoPushAvailable(String autoPushAvailable) {
864         PolicyController.autoPushAvailable = autoPushAvailable;
865     }
866
867     public static String getAutoPushDSClosedLoop() {
868         return autoPushDSClosedLoop;
869     }
870
871     public static void setAutoPushDSClosedLoop(String autoPushDSClosedLoop) {
872         PolicyController.autoPushDSClosedLoop = autoPushDSClosedLoop;
873     }
874
875     public static String getAutoPushDSFirewall() {
876         return autoPushDSFirewall;
877     }
878
879     public static void setAutoPushDSFirewall(String autoPushDSFirewall) {
880         PolicyController.autoPushDSFirewall = autoPushDSFirewall;
881     }
882
883     public static String getAutoPushDSMicroservice() {
884         return autoPushDSMicroservice;
885     }
886
887     public static void setAutoPushDSMicroservice(String autoPushDSMicroservice) {
888         PolicyController.autoPushDSMicroservice = autoPushDSMicroservice;
889     }
890
891     public static String getAutoPushPDPGroup() {
892         return autoPushPDPGroup;
893     }
894
895     public static void setAutoPushPDPGroup(String autoPushPDPGroup) {
896         PolicyController.autoPushPDPGroup = autoPushPDPGroup;
897     }
898
899     public static String getPapUrl() {
900         return papUrl;
901     }
902
903     public static void setPapUrl(String papUrl) {
904         PolicyController.papUrl = papUrl;
905     }
906
907     public static String getMsOnapName() {
908         return msOnapName;
909     }
910
911     public static void setMsOnapName(String msOnapName) {
912         PolicyController.msOnapName = msOnapName;
913     }
914
915     public static String getMsPolicyName() {
916         return msPolicyName;
917     }
918
919     public static void setMsPolicyName(String msPolicyName) {
920         PolicyController.msPolicyName = msPolicyName;
921     }
922
923     public static String getConfigHome() {
924         return configHome;
925     }
926
927     public static void setConfigHome(String configHome) {
928         PolicyController.configHome = configHome;
929     }
930
931     public static String getActionHome() {
932         return actionHome;
933     }
934
935     public static void setActionHome(String actionHome) {
936         PolicyController.actionHome = actionHome;
937     }
938
939     public static Object getMapaccess() {
940         return mapAccess;
941     }
942
943     public static String getPolicydata() {
944         return policyData;
945     }
946
947     public static String getCharacterencoding() {
948         return characterEncoding;
949     }
950
951     public static String getContenttype() {
952         return contentType;
953     }
954
955     public static String getFile() {
956         return file;
957     }
958
959     /**
960      * Set File Size limit.
961      *
962      * @param uploadSize value.
963      */
964     public static void setFileSizeLimit(String uploadSize) {
965         // Default size limit is 30MB
966         if (uploadSize == null || uploadSize.isEmpty()) {
967             fileSizeLimit = 30000000;
968         } else {
969             fileSizeLimit = Long.parseLong(uploadSize);
970         }
971     }
972
973     public static long getFileSizeLimit() {
974         return fileSizeLimit;
975     }
976
977     /**
978      * Function to convert date.
979      *
980      * @param dateTimeToLive input date value.
981      * @return
982      */
983     public String convertDate(String dateTimeToLive) {
984         String formatDate = null;
985         if (dateTimeToLive.contains("-")) {
986             formatDate = dateTimeToLive.replace("-", "/");
987         }
988         return formatDate;
989     }
990 }