aboutsummaryrefslogtreecommitdiffstats
path: root/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java
blob: 700aa3a578ed16fb5256a0e9fe221d0079b1388c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
/*-
 * ============LICENSE_START=======================================================
 * ONAP Policy Engine
 * ================================================================================
 * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
 * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
 * Modifications Copyright (C) 2019 Bell Canada
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.controller;

import com.att.research.xacml.util.XACMLProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import javax.annotation.PostConstruct;
import javax.script.SimpleBindings;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
import org.json.JSONObject;
import org.onap.policy.admin.PolicyNotificationMail;
import org.onap.policy.admin.RESTfulPAPEngine;
import org.onap.policy.common.logging.eelf.MessageCodes;
import org.onap.policy.common.logging.eelf.PolicyLogger;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.model.PDPGroupContainer;
import org.onap.policy.model.Roles;
import org.onap.policy.rest.XACMLRestProperties;
import org.onap.policy.rest.dao.CommonClassDao;
import org.onap.policy.rest.jpa.Datatype;
import org.onap.policy.rest.jpa.FunctionDefinition;
import org.onap.policy.rest.jpa.PolicyEntity;
import org.onap.policy.rest.jpa.PolicyVersion;
import org.onap.policy.rest.jpa.UserInfo;
import org.onap.policy.utils.PeCryptoUtils;
import org.onap.policy.utils.UserUtils.Pair;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
import org.onap.policy.xacml.util.XACMLPolicyScanner;
import org.onap.portalsdk.core.controller.RestrictedBaseController;
import org.onap.portalsdk.core.domain.UserApp;
import org.onap.portalsdk.core.web.support.JsonMessage;
import org.onap.portalsdk.core.web.support.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/")
public class PolicyController extends RestrictedBaseController {
    private static final Logger policyLogger = FlexLogger.getLogger(PolicyController.class);

    private static CommonClassDao commonClassDao;
    //
    // The PAP Engine
    //
    private static PAPPolicyEngine papEngine;

    private static String logTableLimit;
    private static String systemAlertTableLimit;
    protected static Map<String, String> dropDownMap = new HashMap<>();

    public static Map<String, String> getDropDownMap() {
        return dropDownMap;
    }

    public static void setDropDownMap(Map<String, String> dropDownMap) {
        PolicyController.dropDownMap = dropDownMap;
    }

    public static String getDomain() {
        return XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_DOMAIN, "urn");
    }

    private static final Object mapAccess = new Object();
    private static Map<Datatype, List<FunctionDefinition>> mapDatatype2Function = null;
    private static Map<String, FunctionDefinition> mapID2Function = null;

    // Constant variables used across Policy-sdk
    private static final String policyData = "policyData";
    private static final String characterEncoding = "UTF-8";
    private static final String contentType = "application/json";
    private static final String file = "file";
    private static final String SUPERADMIN = "super-admin";
    private static final String POLICYGUEST = "Policy Guest";
    private static final String LOGINID = "loginId";

    // Smtp Java Mail Properties
    private static String smtpHost = null;
    private static String smtpPort = null;
    private static String smtpUsername = null;
    private static String smtpPassword = null;
    private static String smtpApplicationName = null;
    private static String smtpEmailExtension = null;
    // log db Properties
    private static String logdbDriver = null;
    private static String logdbUrl = null;
    private static String logdbUserName = null;
    private static String logdbPassword = null;
    private static String logdbDialect = null;
    // Xacml db properties
    private static String xacmldbUrl = null;
    private static String xacmldbUserName = null;
    private static String xacmldbPassword = null;

    // AutoPush feature.
    private static String autoPushAvailable;
    private static String autoPushDSClosedLoop;
    private static String autoPushDSFirewall;
    private static String autoPushDSMicroservice;
    private static String autoPushPDPGroup;

    // papURL
    private static String papUrl;

    // MicroService Model Properties
    private static String msOnapName;
    private static String msPolicyName;

    // WebApp directories
    private static String configHome;
    private static String actionHome;

    // File upload size
    private static long fileSizeLimit;

    private static boolean jUnit = false;

    public static boolean isjUnit() {
        return jUnit;
    }

    public static void setjUnit(boolean jUnit) {
        PolicyController.jUnit = jUnit;
    }

    @Autowired
    private PolicyController(CommonClassDao commonClassDao) {
        PolicyController.commonClassDao = commonClassDao;
    }

    public PolicyController() {
        // Empty constructor
    }

    /**
     * init method to load the properties.
     */
    @PostConstruct
    public void init() {
        Properties prop = new Properties();

        try {
            String fileName;
            if (jUnit) {
                fileName = new File(".").getCanonicalPath() + File.separator + "src"
                        + File.separator + "test" + File.separator + "resources" + File.separator
                        + "JSONConfig.json";
            } else {
                fileName = "xacml.admin.properties";
            }

            try (InputStream input = new FileInputStream(fileName)) {
                // load a properties file
                prop.load(input);
            }

            // file upload size limit property
            setFileSizeLimit(prop.getProperty("file.size.limit"));
            // pap url
            setPapUrl(prop.getProperty("xacml.rest.pap.url"));
            // get the property values
            setSmtpHost(prop.getProperty("onap.smtp.host"));
            setSmtpPort(prop.getProperty("onap.smtp.port"));
            setSmtpUsername(prop.getProperty("onap.smtp.userName"));
            setSmtpPassword(prop.getProperty("onap.smtp.password"));
            setSmtpApplicationName(prop.getProperty("onap.application.name"));
            setSmtpEmailExtension(prop.getProperty("onap.smtp.emailExtension"));
            // Log Database Properties
            setLogdbDriver(prop.getProperty("xacml.log.db.driver"));
            setLogdbUrl(prop.getProperty("xacml.log.db.url"));
            setLogdbUserName(prop.getProperty("xacml.log.db.user"));
            setLogdbPassword(PeCryptoUtils.decrypt(prop.getProperty("xacml.log.db.password")));
            setLogdbDialect(prop.getProperty("onap.dialect"));
            // Xacml Database Properties
            setXacmldbUrl(prop.getProperty("javax.persistence.jdbc.url"));
            setXacmldbUserName(prop.getProperty("javax.persistence.jdbc.user"));
            setXacmldbPassword(PeCryptoUtils.decrypt(prop.getProperty("javax.persistence.jdbc.password")));
            // AutoPuh
            setAutoPushAvailable(prop.getProperty("xacml.automatic.push"));
            setAutoPushDSClosedLoop(prop.getProperty("xacml.autopush.closedloop"));
            setAutoPushDSFirewall(prop.getProperty("xacml.autopush.firewall"));
            setAutoPushDSMicroservice(prop.getProperty("xacml.autopush.microservice"));
            setAutoPushPDPGroup(prop.getProperty("xacml.autopush.pdpGroup"));
            // Micro Service Properties
            setMsOnapName(prop.getProperty("xacml.policy.msOnapName"));
            if (getMsOnapName() == null) {
                setMsOnapName(prop.getProperty("xacml.policy.msEcompName"));
            }
            policyLogger.info("getMsOnapName => " + getMsOnapName());
            setMsPolicyName(prop.getProperty("xacml.policy.msPolicyName"));
            policyLogger.info("setMsPolicyName => " + getMsPolicyName());
            // WebApp directories
            setConfigHome(prop.getProperty("xacml.rest.config.webapps") + "Config");
            setActionHome(prop.getProperty("xacml.rest.config.webapps") + "Action");
            // Get the Property Values for Dashboard tab Limit
            try {
                setLogTableLimit(prop.getProperty("xacml.onap.dashboard.logTableLimit"));
                setSystemAlertTableLimit(
                        prop.getProperty("xacml.onap.dashboard.systemAlertTableLimit"));
            } catch (Exception e) {
                policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE
                        + "Dashboard tab Property fields are missing" + e);
                setLogTableLimit("5000");
                setSystemAlertTableLimit("2000");
            }
            System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "xacml.admin.properties");
        } catch (IOException ex) {
            policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE
                    + "Exception Occured while reading the Smtp properties from xacml.admin.properties file"
                    + ex);
        }

        // Initialize the FunctionDefinition table at Server Start up
        Map<Datatype, List<FunctionDefinition>> functionMap = getFunctionDatatypeMap();
        for (Entry<Datatype, List<FunctionDefinition>> entry : functionMap.entrySet()) {
            List<FunctionDefinition> functionDefinations = entry.getValue();
            for (FunctionDefinition functionDef : functionDefinations) {
                dropDownMap.put(functionDef.getShortname(), functionDef.getXacmlid());
            }
        }

    }

    /**
     * Get FunctionData Type from DB.
     *
     * @return list of FunctionData.
     */
    public static Map<Datatype, List<FunctionDefinition>> getFunctionDatatypeMap() {
        synchronized (mapAccess) {
            if (mapDatatype2Function == null) {
                buildFunctionMaps();
            }
        }
        return mapDatatype2Function;
    }

    /**
     * Get Function ID.
     *
     * @return Function ID.
     */
    public static Map<String, FunctionDefinition> getFunctionIdMap() {
        synchronized (mapAccess) {
            if (mapID2Function == null) {
                buildFunctionMaps();
            }
        }
        return mapID2Function;
    }

    private static void buildFunctionMaps() {
        mapDatatype2Function = new HashMap<>();
        mapID2Function = new HashMap<>();
        List<Object> functiondefinitions = commonClassDao.getData(FunctionDefinition.class);
        for (int i = 0; i < functiondefinitions.size(); i++) {
            FunctionDefinition value = (FunctionDefinition) functiondefinitions.get(i);
            mapID2Function.put(value.getXacmlid(), value);
            if (!mapDatatype2Function.containsKey(value.getDatatypeBean())) {
                mapDatatype2Function.put(value.getDatatypeBean(),
                        new ArrayList<FunctionDefinition>());
            }
            mapDatatype2Function.get(value.getDatatypeBean()).add(value);
        }
    }

    /**
     * Get Functional Definition data.
     *
     * @param request HttpServletRequest.
     * @param response HttpServletResponse.
     */
    @RequestMapping(value = {"/get_FunctionDefinitionDataByName"},
            method = {org.springframework.web.bind.annotation.RequestMethod.GET},
            produces = MediaType.APPLICATION_JSON_VALUE)
    public void getFunctionDefinitionData(HttpServletRequest request,
            HttpServletResponse response) {
        try {
            Map<String, Object> model = new HashMap<>();
            ObjectMapper mapper = new ObjectMapper();
            model.put("functionDefinitionDatas", mapper.writeValueAsString(
                    commonClassDao.getDataByColumn(FunctionDefinition.class, "shortname")));
            JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
            JSONObject j = new JSONObject(msg);
            response.getWriter().write(j.toString());
        } catch (Exception e) {
            policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE
                    + "Error while retriving the Function Definition data" + e);
        }
    }

    /**
     * Get PolicyEntity Data from db.
     *
     * @param scope scopeName.
     * @param policyName policyName.
     * @return policyEntity data.
     */
    public PolicyEntity getPolicyEntityData(String scope, String policyName) {
        String key = scope + ":" + policyName;
        List<Object> data = commonClassDao.getDataById(PolicyEntity.class, "scope:policyName", key);
        return (PolicyEntity) data.get(0);
    }

    /**
     * Get Policy User Roles from db.
     *
     * @param userId LoginID.
     * @return list of Roles.
     */
    public List<String> getRolesOfUser(String userId) {
        List<String> rolesList = new ArrayList<>();
        List<Object> roles = commonClassDao.getDataById(Roles.class, LOGINID, userId);
        for (Object role : roles) {
            rolesList.add(((Roles) role).getRole());
        }
        return rolesList;
    }

    public List<Object> getRoles(String userId) {
        return commonClassDao.getDataById(Roles.class, LOGINID, userId);
    }

    /**
     * Get List of User Roles.
     *
     * @param request HttpServletRequest.
     * @param response HttpServletResponse.
     */
    @RequestMapping(value = {"/get_UserRolesData"},
            method = {org.springframework.web.bind.annotation.RequestMethod.GET},
            produces = MediaType.APPLICATION_JSON_VALUE)
    public void getUserRolesEntityData(HttpServletRequest request, HttpServletResponse response) {
        try {
            String userId = UserUtils.getUserSession(request).getOrgUserId();
            Map<String, Object> model = new HashMap<>();
            ObjectMapper mapper = new ObjectMapper();
            model.put("userRolesDatas", mapper.writeValueAsString(getRolesOfUser(userId)));
            JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
            JSONObject j = new JSONObject(msg);
            response.getWriter().write(j.toString());
        } catch (Exception e) {
            policyLogger.error("Exception Occured" + e);
        }
    }

    /**
     * Policy tabs Model and View.
     *
     * @param request Request input.
     * @return view model.
     */
    @RequestMapping(value = {"/policy", "/policy/Editor"}, method = RequestMethod.GET)
    public ModelAndView view(HttpServletRequest request) {
        getUserRoleFromSession(request);
        String myRequestUrl = request.getRequestURL().toString();
        try {
            //
            // Set the URL for the RESTful PAP Engine
            //
            setPapEngine(new RESTfulPAPEngine(myRequestUrl));
            new PDPGroupContainer(new RESTfulPAPEngine(myRequestUrl));
        } catch (Exception e) {
            policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR
                    + "Exception Occured while loading PAP" + e);
        }
        Map<String, Object> model = new HashMap<>();
        return new ModelAndView("policy_Editor", "model", model);
    }

    /**
     * Read the role from session for inserting into the database.
     *
     * @param request Request input for Role.
     */
    public void getUserRoleFromSession(HttpServletRequest request) {
        // While user landing on Policy page, fetch the userId and Role from
        // session.
        // And, Query the Roles table and if user not exists or else modified
        // update the Roles table.
        List<String> roles;
        List<String> newRoles = new ArrayList<>();
        String userId = UserUtils.getUserSession(request).getOrgUserId();
        String name = UserUtils.getUserSession(request).getFullName();
        @SuppressWarnings("unchecked")
        Set<UserApp> userApps = UserUtils.getUserSession(request).getUserApps();
        for (UserApp userApp : userApps) {
            newRoles.add(userApp.getRole().getName());
        }
        List<Object> userRoles = getRoles(userId);
        List<String> filteredRoles = filterRole(newRoles);
        if (!filteredRoles.isEmpty()) {
            cleanUpRoles(filteredRoles, userId);
        }
        for (String filteredRole : filteredRoles) {
            if (userRoles == null || userRoles.isEmpty()) {
                savePolicyRoles(name, filteredRole, userId);
            } else {
                userRoles = getRoles(userId);
                Pair<Set<String>, List<String>> pair =
                        org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
                roles = pair.u;
                if (!roles.contains(filteredRole)) {
                    savePolicyRoles(name, filteredRole, userId);
                }
            }
        }
    }

    /**
     * Build a delete query for cleaning up roles and execute it.
     *
     * @param filteredRoles Filtered roles list.
     * @param userId UserID.
     */
    private void cleanUpRoles(List<String> filteredRoles, String userId) {
        StringBuilder query = new StringBuilder();
        query.append("delete from Roles where loginid = '" + userId + "'");
        if (filteredRoles.contains(SUPERADMIN)) {
            query.append("and not role = '" + SUPERADMIN + "'");
        } else {
            for (String filteredRole : filteredRoles) {
                query.append("and not role = '" + filteredRole + "'");
            }
        }
        query.append("and id > 0");
        commonClassDao.updateQuery(query.toString());
    }

    /**
     * Save the Role to DB.
     *
     * @param name User Name.
     * @param filteredRole Role Name.
     * @param userId User LoginID.
     */
    private void savePolicyRoles(String name, String filteredRole, String userId) {
        UserInfo userInfo = new UserInfo();
        userInfo.setUserLoginId(userId);
        userInfo.setUserName(name);
        commonClassDao.save(userInfo);
        Roles role = new Roles();
        role.setName(name);
        role.setRole(filteredRole);
        role.setLoginId(userId);
        commonClassDao.save(role);
    }

    /**
     * Filter the list of roles hierarchy wise.
     *
     * @param newRoles list of roles from request.
     * @return
     */
    private List<String> filterRole(List<String> newRoles) {
        List<String> roles = new ArrayList<>();
        boolean superCheck = false;
        for (String role : newRoles) {
            if ("Policy Super Guest".equalsIgnoreCase(role.trim())) {
                superCheck = true;
                roles.add("super-guest");
            } else if ("Policy Super Editor".equalsIgnoreCase(role.trim())) {
                superCheck = true;
                roles.clear();
                roles.add("super-editor");
            } else if ("Policy Super Admin".equalsIgnoreCase(role.trim())
                    || "System Administrator".equalsIgnoreCase(role.trim())
                    || "Standard User".equalsIgnoreCase(role.trim())) {
                superCheck = true;
                roles.clear();
                roles.add(SUPERADMIN);
            }
            if (!roles.contains(SUPERADMIN)
                    || (POLICYGUEST.equalsIgnoreCase(role) && !superCheck)) {
                if ("Policy Admin".equalsIgnoreCase(role.trim())) {
                    roles.add("admin");
                } else if ("Policy Editor".equalsIgnoreCase(role.trim())) {
                    roles.add("editor");
                } else if (POLICYGUEST.equalsIgnoreCase(role.trim())) {
                    roles.add("guest");
                }
            }
        }
        return roles;
    }

    public PAPPolicyEngine getPapEngine() {
        return papEngine;
    }

    public static void setPapEngine(PAPPolicyEngine papEngine) {
        PolicyController.papEngine = papEngine;
    }

    /**
     * Get UserName based on LoginID.
     *
     * @param createdBy loginID.
     * @return name.
     */
    public String getUserName(String createdBy) {
        String loginId = createdBy;
        List<Object> data = commonClassDao.getDataById(UserInfo.class, LOGINID, loginId);
        return data.get(0).toString();
    }

    /**
     * Check if the Policy is Active or not.
     *
     * @param query sql query.
     * @return boolean.
     */
    public static boolean getActivePolicy(String query) {
        return !commonClassDao.getDataByQuery(query, new SimpleBindings()).isEmpty();
    }

    public void executeQuery(String query) {
        commonClassDao.updateQuery(query);
    }

    public void saveData(Object cloneEntity) {
        commonClassDao.save(cloneEntity);
    }

    public void updateData(Object entity) {
        commonClassDao.update(entity);
    }

    public void deleteData(Object entity) {
        commonClassDao.delete(entity);
    }

    public List<Object> getData(@SuppressWarnings("rawtypes") Class className) {
        return commonClassDao.getData(className);
    }

    public PolicyVersion getPolicyEntityFromPolicyVersion(String query) {
        return (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName",
                query);
    }

    public List<Object> getDataByQuery(String query, SimpleBindings params) {
        return commonClassDao.getDataByQuery(query, params);
    }

    @SuppressWarnings("rawtypes")
    public Object getEntityItem(Class className, String columname, String key) {
        return commonClassDao.getEntityItem(className, columname, key);
    }

    /**
     * Watch Policy Function.
     *
     * @param entity PolicyVersion entity.
     * @param policyName updated policy name.
     * @param mode type of action rename/delete/import.
     */
    public void watchPolicyFunction(PolicyVersion entity, String policyName, String mode) {
        PolicyNotificationMail email = new PolicyNotificationMail();
        email.sendMail(entity, policyName, mode, commonClassDao);
    }

    /**
     * Switch Version Policy Content.
     *
     * @param pName which is used to find associated versions.
     * @return list of available versions based on policy name.
     */
    public JSONObject switchVersionPolicyContent(String pName) {
        String policyName = pName;
        String dbCheckName = policyName.replace("/", ".");
        if (dbCheckName.contains("Config_")) {
            dbCheckName = dbCheckName.replace(".Config_", ":Config_");
        } else if (dbCheckName.contains("Action_")) {
            dbCheckName = dbCheckName.replace(".Action_", ":Action_");
        } else if (dbCheckName.contains("Decision_MS_")) {
            dbCheckName = dbCheckName.replace(".Decision_MS_", ":Decision_MS_");
        } else if (dbCheckName.contains("Decision_")) {
            dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
        }
        String[] splitDbCheckName = dbCheckName.split(":");
        String query =
                "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0";
        SimpleBindings params = new SimpleBindings();
        params.put("splitDBCheckName1", splitDbCheckName[1] + "%");
        params.put("splitDBCheckName0", splitDbCheckName[0]);
        List<Object> policyEntity = commonClassDao.getDataByQuery(query, params);
        List<String> av = new ArrayList<>();
        for (Object entity : policyEntity) {
            PolicyEntity pEntity = (PolicyEntity) entity;
            String removeExtension = pEntity.getPolicyName().replace(".xml", "");
            String version = removeExtension.substring(removeExtension.lastIndexOf('.') + 1);
            String userName = getUserId(pEntity, "@ModifiedBy:");
            av.add(version + " | " + pEntity.getModifiedDate() + " | " + userName);
        }
        if (policyName.contains("/")) {
            policyName = policyName.replace("/", File.separator);
        }
        PolicyVersion entity = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class,
                "policyName", policyName);
        JSONObject el = new JSONObject();
        el.put("activeVersion", entity.getActiveVersion());
        el.put("availableVersions", av);
        el.put("highestVersion", entity.getHigherVersion());
        return el;
    }

    public String getUserId(PolicyEntity data, String value) {
        String userId = "";
        String uValue = value;
        String description = getDescription(data);
        if (description.contains(uValue)) {
            userId = description.substring(description.indexOf(uValue) + uValue.length(),
                    description.lastIndexOf(uValue));
        }
        UserInfo userInfo = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", userId);
        if (userInfo == null) {
            return SUPERADMIN;
        }
        return userInfo.getUserName();
    }

    public String getDescription(PolicyEntity data) {
        InputStream stream =
                new ByteArrayInputStream(data.getPolicyData().getBytes(StandardCharsets.UTF_8));
        Object policy = XACMLPolicyScanner.readPolicy(stream);
        if (policy instanceof PolicySetType) {
            return ((PolicySetType) policy).getDescription();
        } else if (policy instanceof PolicyType) {
            return ((PolicyType) policy).getDescription();
        } else {
            PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE
                    + "Expecting a PolicySet/Policy/Rule object. Got: "
                    + policy.getClass().getCanonicalName());
            return null;
        }
    }

    public String[] getUserInfo(PolicyEntity data, List<PolicyVersion> activePolicies) {
        String policyName = data.getScope().replace(".", File.separator) + File.separator
                + data.getPolicyName().substring(0, data.getPolicyName().indexOf('.'));
        PolicyVersion polVersion = activePolicies.stream()
                .filter(a -> policyName.equals(a.getPolicyName())).findAny().orElse(null);
        String[] result = new String[2];
        UserInfo userCreate = null;
        UserInfo userModify = null;
        if (polVersion != null) {
            userCreate = (UserInfo) getEntityItem(UserInfo.class, "userLoginId",
                    polVersion.getCreatedBy());
            userModify = (UserInfo) getEntityItem(UserInfo.class, "userLoginId",
                    polVersion.getModifiedBy());
        }

        result[0] = userCreate != null ? userCreate.getUserName() : SUPERADMIN;
        result[1] = userModify != null ? userModify.getUserName() : SUPERADMIN;

        return result;
    }

    public static String getLogTableLimit() {
        return logTableLimit;
    }

    public static void setLogTableLimit(String logTableLimit) {
        PolicyController.logTableLimit = logTableLimit;
    }

    public static String getSystemAlertTableLimit() {
        return systemAlertTableLimit;
    }

    public static void setSystemAlertTableLimit(String systemAlertTableLimit) {
        PolicyController.systemAlertTableLimit = systemAlertTableLimit;
    }

    public static CommonClassDao getCommonClassDao() {
        return commonClassDao;
    }

    public static void setCommonClassDao(CommonClassDao commonClassDao) {
        PolicyController.commonClassDao = commonClassDao;
    }

    public static Map<Datatype, List<FunctionDefinition>> getMapDatatype2Function() {
        return mapDatatype2Function;
    }

    public static void setMapDatatype2Function(
            Map<Datatype, List<FunctionDefinition>> mapDatatype2Function) {
        PolicyController.mapDatatype2Function = mapDatatype2Function;
    }

    public static Map<String, FunctionDefinition> getMapID2Function() {
        return mapID2Function;
    }

    public static void setMapID2Function(Map<String, FunctionDefinition> mapID2Function) {
        PolicyController.mapID2Function = mapID2Function;
    }

    public static String getSmtpHost() {
        return smtpHost;
    }

    public static void setSmtpHost(String smtpHost) {
        PolicyController.smtpHost = smtpHost;
    }

    public static String getSmtpPort() {
        return smtpPort;
    }

    public static void setSmtpPort(String smtpPort) {
        PolicyController.smtpPort = smtpPort;
    }

    public static String getSmtpUsername() {
        return smtpUsername;
    }

    public static void setSmtpUsername(String smtpUsername) {
        PolicyController.smtpUsername = smtpUsername;
    }

    public static String getSmtpPassword() {
        return smtpPassword;
    }

    public static void setSmtpPassword(String smtpPassword) {
        PolicyController.smtpPassword = smtpPassword;
    }

    public static String getSmtpApplicationName() {
        return smtpApplicationName;
    }

    public static void setSmtpApplicationName(String smtpApplicationName) {
        PolicyController.smtpApplicationName = smtpApplicationName;
    }

    public static String getSmtpEmailExtension() {
        return smtpEmailExtension;
    }

    public static void setSmtpEmailExtension(String smtpEmailExtension) {
        PolicyController.smtpEmailExtension = smtpEmailExtension;
    }

    public static String getLogdbDriver() {
        return logdbDriver;
    }

    public static void setLogdbDriver(String logdbDriver) {
        PolicyController.logdbDriver = logdbDriver;
    }

    public static String getLogdbUrl() {
        return logdbUrl;
    }

    public static void setLogdbUrl(String logdbUrl) {
        PolicyController.logdbUrl = logdbUrl;
    }

    public static String getLogdbUserName() {
        return logdbUserName;
    }

    public static void setLogdbUserName(String logdbUserName) {
        PolicyController.logdbUserName = logdbUserName;
    }

    public static String getLogdbPassword() {
        return logdbPassword;
    }

    public static void setLogdbPassword(String logdbPassword) {
        PolicyController.logdbPassword = logdbPassword;
    }

    public static String getLogdbDialect() {
        return logdbDialect;
    }

    public static void setLogdbDialect(String logdbDialect) {
        PolicyController.logdbDialect = logdbDialect;
    }

    public static String getXacmldbUrl() {
        return xacmldbUrl;
    }

    public static void setXacmldbUrl(String xacmldbUrl) {
        PolicyController.xacmldbUrl = xacmldbUrl;
    }

    public static String getXacmldbUserName() {
        return xacmldbUserName;
    }

    public static void setXacmldbUserName(String xacmldbUserName) {
        PolicyController.xacmldbUserName = xacmldbUserName;
    }

    public static String getXacmldbPassword() {
        return xacmldbPassword;
    }

    public static void setXacmldbPassword(String xacmldbPassword) {
        PolicyController.xacmldbPassword = xacmldbPassword;
    }

    public static String getAutoPushAvailable() {
        return autoPushAvailable;
    }

    public static void setAutoPushAvailable(String autoPushAvailable) {
        PolicyController.autoPushAvailable = autoPushAvailable;
    }

    public static String getAutoPushDSClosedLoop() {
        return autoPushDSClosedLoop;
    }

    public static void setAutoPushDSClosedLoop(String autoPushDSClosedLoop) {
        PolicyController.autoPushDSClosedLoop = autoPushDSClosedLoop;
    }

    public static String getAutoPushDSFirewall() {
        return autoPushDSFirewall;
    }

    public static void setAutoPushDSFirewall(String autoPushDSFirewall) {
        PolicyController.autoPushDSFirewall = autoPushDSFirewall;
    }

    public static String getAutoPushDSMicroservice() {
        return autoPushDSMicroservice;
    }

    public static void setAutoPushDSMicroservice(String autoPushDSMicroservice) {
        PolicyController.autoPushDSMicroservice = autoPushDSMicroservice;
    }

    public static String getAutoPushPDPGroup() {
        return autoPushPDPGroup;
    }

    public static void setAutoPushPDPGroup(String autoPushPDPGroup) {
        PolicyController.autoPushPDPGroup = autoPushPDPGroup;
    }

    public static String getPapUrl() {
        return papUrl;
    }

    public static void setPapUrl(String papUrl) {
        PolicyController.papUrl = papUrl;
    }

    public static String getMsOnapName() {
        return msOnapName;
    }

    public static void setMsOnapName(String msOnapName) {
        PolicyController.msOnapName = msOnapName;
    }

    public static String getMsPolicyName() {
        return msPolicyName;
    }

    public static void setMsPolicyName(String msPolicyName) {
        PolicyController.msPolicyName = msPolicyName;
    }

    public static String getConfigHome() {
        return configHome;
    }

    public static void setConfigHome(String configHome) {
        PolicyController.configHome = configHome;
    }

    public static String getActionHome() {
        return actionHome;
    }

    public static void setActionHome(String actionHome) {
        PolicyController.actionHome = actionHome;
    }

    public static Object getMapaccess() {
        return mapAccess;
    }

    public static String getPolicydata() {
        return policyData;
    }

    public static String getCharacterencoding() {
        return characterEncoding;
    }

    public static String getContenttype() {
        return contentType;
    }

    public static String getFile() {
        return file;
    }

    /**
     * Set File Size limit.
     *
     * @param uploadSize value.
     */
    public static void setFileSizeLimit(String uploadSize) {
        // Default size limit is 30MB
        if (uploadSize == null || uploadSize.isEmpty()) {
            fileSizeLimit = 30000000;
        } else {
            fileSizeLimit = Long.parseLong(uploadSize);
        }
    }

    public static long getFileSizeLimit() {
        return fileSizeLimit;
    }

    /**
     * Function to convert date.
     *
     * @param dateTTL input date value.
     * @return
     */
    public String convertDate(String dateTTL) {
        String formateDate = null;
        if (dateTTL.contains("-")) {
            formateDate = dateTTL.replace("-", "/");
        }
        return formateDate;
    }
}