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