From 073cc188efe9abb4c010cf674e34e2cf46ef1c52 Mon Sep 17 00:00:00 2001 From: Guo Ruijing Date: Mon, 31 Jul 2017 08:47:35 +0000 Subject: [POLICY-73] replace openecomp for policy-engine Change-Id: I54072f6bcd388c0e05562614ee89b4ae7ad67004 Signed-off-by: Guo Ruijing Signed-off-by: Pamela Dragosh --- .../main/java/org/onap/policy/admin/CheckPDP.java | 181 +++ .../java/org/onap/policy/admin/PolicyAdapter.java | 116 ++ .../onap/policy/admin/PolicyManagerServlet.java | 1477 ++++++++++++++++++ .../onap/policy/admin/PolicyNotificationMail.java | 163 ++ .../onap/policy/admin/PolicyRestController.java | 443 ++++++ .../policy/admin/PolicyUserInfoController.java | 62 + .../org/onap/policy/admin/RESTfulPAPEngine.java | 517 +++++++ .../policy/components/HumanPolicyComponent.java | 991 ++++++++++++ .../org/onap/policy/conf/HibernateSession.java | 63 + .../policy/controller/ActionPolicyController.java | 268 ++++ .../onap/policy/controller/AdminTabController.java | 119 ++ .../onap/policy/controller/AutoPushController.java | 377 +++++ .../controller/CreateBRMSParamController.java | 551 +++++++ .../policy/controller/CreateBRMSRawController.java | 172 +++ .../CreateClosedLoopFaultController.java | 709 +++++++++ .../controller/CreateClosedLoopPMController.java | 208 +++ .../CreateDcaeMicroServiceController.java | 1622 ++++++++++++++++++++ .../controller/CreateFirewallController.java | 929 +++++++++++ .../policy/controller/CreatePolicyController.java | 163 ++ .../policy/controller/DashboardController.java | 430 ++++++ .../controller/DecisionPolicyController.java | 361 +++++ .../org/onap/policy/controller/PDPController.java | 394 +++++ .../onap/policy/controller/PolicyController.java | 696 +++++++++ .../PolicyExportAndImportController.java | 384 +++++ .../controller/PolicyNotificationController.java | 122 ++ .../policy/controller/PolicyRolesController.java | 167 ++ .../controller/PolicyValidationController.java | 776 ++++++++++ .../java/org/onap/policy/dao/SystemLogDbDao.java | 33 + .../org/onap/policy/daoImp/CommonClassDaoImpl.java | 382 +++++ .../org/onap/policy/daoImp/SystemLogDbDaoImpl.java | 93 ++ .../org/onap/policy/model/PDPGroupContainer.java | 522 +++++++ .../org/onap/policy/model/PDPPolicyContainer.java | 348 +++++ .../src/main/java/org/onap/policy/model/Roles.java | 99 ++ .../onap/policy/utils/ConfigurableRESTUtils.java | 163 ++ .../org/onap/policy/utils/PolicyContainer.java | 121 ++ .../policy/utils/PolicyItemSetChangeNotifier.java | 95 ++ .../utils/XACMLPolicyWriterWithPapNotify.java | 483 ++++++ .../java/org/openecomp/policy/admin/CheckPDP.java | 181 --- .../org/openecomp/policy/admin/PolicyAdapter.java | 116 -- .../policy/admin/PolicyManagerServlet.java | 1477 ------------------ .../policy/admin/PolicyNotificationMail.java | 163 -- .../policy/admin/PolicyRestController.java | 443 ------ .../policy/admin/PolicyUserInfoController.java | 62 - .../openecomp/policy/admin/RESTfulPAPEngine.java | 517 ------- .../policy/components/HumanPolicyComponent.java | 991 ------------ .../openecomp/policy/conf/HibernateSession.java | 63 - .../policy/controller/ActionPolicyController.java | 268 ---- .../policy/controller/AdminTabController.java | 119 -- .../policy/controller/AutoPushController.java | 377 ----- .../controller/CreateBRMSParamController.java | 551 ------- .../policy/controller/CreateBRMSRawController.java | 172 --- .../CreateClosedLoopFaultController.java | 709 --------- .../controller/CreateClosedLoopPMController.java | 208 --- .../CreateDcaeMicroServiceController.java | 1622 -------------------- .../controller/CreateFirewallController.java | 929 ----------- .../policy/controller/CreatePolicyController.java | 163 -- .../policy/controller/DashboardController.java | 430 ------ .../controller/DecisionPolicyController.java | 361 ----- .../openecomp/policy/controller/PDPController.java | 394 ----- .../policy/controller/PolicyController.java | 696 --------- .../PolicyExportAndImportController.java | 384 ----- .../controller/PolicyNotificationController.java | 122 -- .../policy/controller/PolicyRolesController.java | 167 -- .../controller/PolicyValidationController.java | 776 ---------- .../org/openecomp/policy/dao/SystemLogDbDao.java | 33 - .../policy/daoImp/CommonClassDaoImpl.java | 382 ----- .../policy/daoImp/SystemLogDbDaoImpl.java | 93 -- .../openecomp/policy/model/PDPGroupContainer.java | 522 ------- .../openecomp/policy/model/PDPPolicyContainer.java | 348 ----- .../java/org/openecomp/policy/model/Roles.java | 99 -- .../policy/utils/ConfigurableRESTUtils.java | 163 -- .../openecomp/policy/utils/PolicyContainer.java | 121 -- .../policy/utils/PolicyItemSetChangeNotifier.java | 95 -- .../utils/XACMLPolicyWriterWithPapNotify.java | 483 ------ .../src/main/webapp/WEB-INF/conf/system.properties | 10 +- .../fusion/orm/RNoteBookIntegration.hbm.xml | 2 +- POLICY-SDK-APP/src/main/webapp/WEB-INF/index.jsp | 2 +- .../src/main/webapp/WEB-INF/jsp/login.jsp | 6 +- POLICY-SDK-APP/src/main/webapp/WEB-INF/web.xml | 2 +- .../webapp/app/policyApp/CSS/UIGrid/ui-grid.js | 10 +- .../main/webapp/app/policyApp/CSS/b2b-angular.css | 26 +- .../docs/_includes/getting-started/download.html | 4 +- .../docs/_includes/getting-started/grunt.html | 2 +- .../_includes/getting-started/whats-included.html | 8 +- .../docs/_includes/nav/getting-started.html | 2 +- .../CSS/bootstrap/docs/assets/js/customize.min.js | 2 +- .../bootstrap/docs/assets/js/vendor/jszip.min.js | 2 +- .../app/policyApp/CSS/bootstrap/docs/index.html | 2 +- .../src/main/webapp/app/policyApp/CSS/select.js | 2 +- .../Windows/Dictionary/ActionPolicyDictionary.html | 6 +- .../Windows/Dictionary/AttributeDictionary.html | 2 +- .../Dictionary/BRMSControllerDictionary.html | 2 +- .../Dictionary/BRMSDependencyDictionary.html | 2 +- .../Windows/Dictionary/BRMSParamDictionary.html | 2 +- .../Windows/Dictionary/CLPepOptionsDictionary.html | 2 +- .../Dictionary/CLServiceTypeDictionary.html | 2 +- .../Windows/Dictionary/CLSiteDictionary.html | 2 +- .../Windows/Dictionary/CLVarbindDictionary.html | 2 +- .../Windows/Dictionary/CLVnfTypeDictionary.html | 2 +- .../Windows/Dictionary/CLVsclActionDictionary.html | 2 +- .../Dictionary/DecisionRainyDayDictionary.html | 2 +- .../Dictionary/DecisionSettingsDictionary.html | 2 +- .../Dictionary/DescriptiveScopeDictionary.html | 2 +- .../Windows/Dictionary/EcompNameDictionary.html | 51 - .../Windows/Dictionary/EnforcerTypeDictionary.html | 2 +- .../Windows/Dictionary/FWActionListDictionary.html | 2 +- .../Dictionary/FWAddressGroupDictionary.html | 2 +- .../Windows/Dictionary/FWParentListDictionary.html | 2 +- .../Windows/Dictionary/FWPortListDictionary.html | 2 +- .../Windows/Dictionary/FWPrefixListDictionary.html | 2 +- .../Dictionary/FWProtocolListDictionary.html | 2 +- .../Dictionary/FWSecurityZoneDictionary.html | 2 +- .../Dictionary/FWServiceListDictionary.html | 2 +- .../app/policyApp/Windows/Dictionary/FWTag.html | 2 +- .../policyApp/Windows/Dictionary/FWTagPicker.html | 2 +- .../Windows/Dictionary/FWTermListDictionary.html | 2 +- .../Windows/Dictionary/FWZoneDictionary.html | 2 +- .../Windows/Dictionary/MSConfigNameDictionary.html | 2 +- .../Windows/Dictionary/MSDCAEUUIDDictionary.html | 4 +- .../Windows/Dictionary/MSLocationDictionary.html | 2 +- .../Windows/Dictionary/MSModelsDictionary.html | 2 +- .../Dictionary/ModelAttributeDictionary.html | 2 +- .../Windows/Dictionary/OnapNameDictionary.html | 51 + .../Windows/Dictionary/PSClosedLoopDictionary.html | 2 +- .../Dictionary/PSGroupPolicyScopeDictionary.html | 2 +- .../Windows/Dictionary/PSResourceDictionary.html | 2 +- .../Windows/Dictionary/PSServiceDictionary.html | 2 +- .../Windows/Dictionary/PSTypeDictionary.html | 2 +- .../Windows/Dictionary/RiskTypeDictionary.html | 2 +- .../Dictionary/SafePolicyWarningDictionary.html | 2 +- .../app/policyApp/Windows/Edit_Roles_Window.html | 2 +- .../Windows/PDPTabWindows/AddorEditPDPtoGroup.html | 2 +- .../Windows/PDPTabWindows/PdpStatusWindow.html | 2 +- .../PushtabWindow/removeGroupPoliciesWindow.html | 2 +- .../app/policyApp/Windows/new_PDPGroup_Window.html | 2 +- .../webapp/app/policyApp/Windows/popup_modal.html | 2 +- .../app/policyApp/controller/AutoPushController.js | 2 +- .../RemovePDPGroupPoliciesController.js | 2 +- .../policyApp/controller/DictionaryController.js | 4 +- .../controller/ImportDictionaryController.js | 2 +- .../PDPTabController/AddorEditPdpInGroup.js | 2 +- .../PDPTabController/PDPGroupStatusController.js | 2 +- .../controller/PolicyAddScopeRoleController.js | 2 +- .../policyApp/controller/PolicyRolesController.js | 2 +- .../policyApp/controller/dashboardController.js | 2 +- .../controller/dashboard_Logging_Controller.js | 2 +- .../BRMSControllerDictController.js | 2 +- .../BRMSDependencyDictController.js | 2 +- .../BRMSParamDictController.js | 2 +- .../CLPepOptionsDictController.js | 2 +- .../CLServiceDictController.js | 2 +- .../dictionaryController/CLSiteDictController.js | 2 +- .../CLVarbindDictController.js | 2 +- .../CLVnfTypeDictController.js | 2 +- .../CLVsclActionDictController.js | 2 +- .../DecisionRainyDayDictController.js | 2 +- .../DecisionSettingsDictController.js | 2 +- .../DescriptiveSearchDictController.js | 2 +- .../dictionaryController/EnforcerDictController.js | 2 +- .../FWActionListDictController.js | 2 +- .../FWAddressGroupDictController.js | 2 +- .../FWParentListDictController.js | 2 +- .../FWPortListDictController.js | 2 +- .../FWPrefixListDictController.js | 2 +- .../FWProtocolListDictController.js | 2 +- .../FWSecurityZoneDictController.js | 2 +- .../FWServiceGroupDictController.js | 2 +- .../FWServiceListDictController.js | 2 +- .../FWTagListDictController.js | 2 +- .../FWTagPickerListDictController.js | 2 +- .../FWTermListDictController.js | 2 +- .../dictionaryController/FWZoneDictController.js | 2 +- .../MSConfigNameDictController.js | 2 +- .../MSDcaeUUIDDictController.js | 2 +- .../MSLocationDictController.js | 2 +- .../dictionaryController/MSModelsDictController.js | 2 +- .../ModelAttributeDictController.js | 2 +- .../PSClosedLoopDictController.js | 2 +- .../PSGroupPolicyScopeDictController.js | 2 +- .../PSResourceDictController.js | 2 +- .../PSServiceDictController.js | 2 +- .../dictionaryController/PSTypeDictController.js | 2 +- .../dictionaryController/RiskTypeDictController.js | 2 +- .../SafePolicyWarningDictController.js | 2 +- .../actionPolicyDictController.js | 2 +- .../attributeDictController.js | 2 +- .../ecompNameEditorController.js | 70 - .../onapNameEditorController.js | 70 + .../BRMSControllerDictGridController.js | 2 +- .../BRMSDependencyDictGridController.js | 2 +- .../BRMSParamDictGridController.js | 2 +- .../CLPepOptionsDictGridController.js | 4 +- .../CLServiceDictGridController.js | 2 +- .../CLSiteDictGridController.js | 2 +- .../CLVarbindDictGridController.js | 2 +- .../CLVnfTypeDictGridController.js | 2 +- .../CLVsclActionDictGridController.js | 2 +- .../DecisionRainyDayDictGridController.js | 2 +- .../DecisionSettingsDictGridController.js | 2 +- .../DescriptiveScopeDictGridController.js | 2 +- .../EnforcerTypeDictGridController.js | 2 +- .../FWActionListDictGridController.js | 2 +- .../FWAddressGroupDictGridController.js | 2 +- .../FWParentListDictGridController.js | 2 +- .../FWPortListDictGridController.js | 2 +- .../FWPrefixListDictGridController.js | 2 +- .../FWProtocolListDictGridController.js | 2 +- .../FWSecurityZoneDictGridController.js | 2 +- .../FWServiceGroupDictGridController.js | 2 +- .../FWServiceListDictGridController.js | 2 +- .../FWTagListDictGridController.js | 2 +- .../FWTagPickerListDictGridController.js | 2 +- .../FWTermListDictGridController.js | 2 +- .../FWZoneDictGridController.js | 2 +- .../MSConfigNameDictGridController.js | 2 +- .../MSDcaeUUIDDictGridController.js | 2 +- .../MSLocationDictGridController.js | 2 +- .../MSModelDictGridController.js | 2 +- .../ModelAttributeDictGridController.js | 2 +- .../PSClosedLoopDictGridController.js | 2 +- .../PSGroupPolicyScopeDictGridController.js | 2 +- .../PSResourceDictGridController.js | 2 +- .../PSServiceDictGridController.js | 2 +- .../PSTypeDictGridController.js | 2 +- .../RiskTypeDictGridController.js | 4 +- .../SafePolicyWarningDictGridController.js | 2 +- .../actionPolicyDictGridController.js | 2 +- .../attributeDictGridController.js | 2 +- .../ecompNameDictGridController.js | 197 --- .../onapNameDictGridController.js | 197 +++ .../app/policyApp/controller/pdpController.js | 2 +- .../controller/pdpGroupPopUpController.js | 2 +- .../controller/policyAdminTabController.js | 2 +- .../app/policyApp/controller/policyController.js | 2 +- .../libs/bower_components/angular/angular.js | 2 +- .../libs/bower_components/jquery/dist/jquery.js | 2 +- .../jquery/src/sizzle/dist/sizzle.js | 2 +- .../app/policyApp/main/modalPopupController.js | 2 +- .../webapp/app/policyApp/main/policyEditor.html | 10 +- .../Dictionary/ActionPolicyDictionary.html | 2 +- .../Dictionary/AttributeDictionary.html | 2 +- .../Dictionary/BRMSControllerDictionary.html | 2 +- .../Dictionary/BRMSDependencyDictionary.html | 2 +- .../Dictionary/BRMSParamDictionary.html | 2 +- .../Dictionary/CLPepOptionsDictionary.html | 2 +- .../Dictionary/CLServiceDictionary.html | 2 +- .../policy-models/Dictionary/CLSiteDictionary.html | 2 +- .../Dictionary/CLVNFTypeDictionary.html | 2 +- .../Dictionary/CLVSCLActionDictionary.html | 2 +- .../Dictionary/CLVarbindDictionary.html | 2 +- .../Dictionary/DecisionRainyDayDictionary.html | 2 +- .../Dictionary/DecisionSettingsDictionary.html | 2 +- .../Dictionary/DescriptiveScopeDictionary.html | 2 +- .../Dictionary/EcompNameDictionary.html | 22 - .../Dictionary/EnforcerTypeDictionary.html | 2 +- .../Dictionary/FWActionLisdtDictionary.html | 2 +- .../Dictionary/FWActionListDictionary.html | 2 +- .../Dictionary/FWAddressGroupDictionary.html | 2 +- .../Dictionary/FWParentListDictionary.html | 2 +- .../Dictionary/FWPortListDictionary.html | 2 +- .../Dictionary/FWPrefixListDictionary.html | 2 +- .../Dictionary/FWProtocolListDictionary.html | 2 +- .../Dictionary/FWSecurityZoneDictionary.html | 2 +- .../Dictionary/FWServiceGroupDictionary.html | 2 +- .../Dictionary/FWServiceListDictionary.html | 2 +- .../Dictionary/FWTagListDictionary.html | 2 +- .../Dictionary/FWTagPickerListDictionary.html | 2 +- .../Dictionary/FWTermListDictionary.html | 2 +- .../policy-models/Dictionary/FWZoneDictionary.html | 2 +- .../Dictionary/MSConfigNameDictionary.html | 2 +- .../Dictionary/MSDcaeUUIDDictionary.html | 2 +- .../Dictionary/MSLocationDictionary.html | 2 +- .../Dictionary/MSModelDictionary.html | 2 +- .../Dictionary/ModelAttributeDictionary.html | 2 +- .../Dictionary/OnapNameDictionary.html | 22 + .../Dictionary/PSClosedLoopDictionary.html | 2 +- .../Dictionary/PSGroupPolicyScopeDictionary.html | 2 +- .../Dictionary/PSResourceDictionary.html | 2 +- .../Dictionary/PSServiceDictionary.html | 2 +- .../policy-models/Dictionary/PSTypeDictionary.html | 2 +- .../Dictionary/RiskTypeDictionary.html | 2 +- .../Dictionary/SafePolicyWarningDictionary.html | 2 +- .../ActionPolicyController.js | 2 +- .../BRMSParamPolicyController.js | 2 +- .../BRMSRawPolicyController.js | 2 +- .../BaseConfigPolicyController.js | 8 +- .../ClosedLoopFaultController.js | 8 +- .../ClosedLoopPMController.js | 8 +- .../DCAEMicroServicePolicyController.js | 8 +- .../DecisionPolicyController.js | 8 +- .../ExportPolicyController.js | 2 +- .../FirewallPolicyController.js | 2 +- .../Editor/PolicyTemplates/BasePolicyTemplate.html | 8 +- .../ClosedLoopFaultPolicyTemplate.html | 8 +- .../ClosedLoopPMPolicyTemplate.html | 8 +- .../DCAEMicroServicePolicyTemplate.html | 8 +- .../PolicyTemplates/DecisionPolicyTemplate.html | 8 +- .../Editor/PolicyTemplates/PolicyTypeTemplate.html | 2 +- .../policy-models/Editor/css/animations.css | 2 +- .../policyApp/policy-models/Editor/css/dialogs.css | 2 +- .../policyApp/policy-models/Editor/css/main.css | 2 +- .../policy-models/Editor/css/normalize-legacy.css | 2 +- .../policy-models/Editor/css/normalize.css | 2 +- .../policyApp/policy-models/Editor/css/styles.css | 2 +- .../app/policyApp/policy-models/Editor/js/app.js | 2 +- .../Editor/js/controllers/policyManager.js | 6 +- .../Editor/js/controllers/policySearchManager.js | 6 +- .../Editor/js/controllers/selector-controller.js | 2 +- .../Editor/js/directives/directives.js | 2 +- .../policy-models/Editor/js/entities/item.js | 2 +- .../policy-models/Editor/js/filters/filters.js | 2 +- .../policy-models/Editor/js/providers/config.js | 2 +- .../Editor/js/services/RolesService.js | 2 +- .../Editor/js/services/policynavigator.js | 2 +- .../Editor/js/services/policyuploader.js | 2 +- .../Editor/templates/searchNavbar.html | 6 +- .../policyApp/policy-models/policy_AdminTab.html | 2 +- .../policyApp/policy-models/policy_AutoPush.html | 4 +- .../policy-models/policy_DashboardHealth.html | 2 +- .../policy-models/policy_DashboardLogging.html | 6 +- .../policyApp/policy-models/policy_Dictionary.html | 4 +- .../policy-models/policy_PDPManagement.html | 2 +- .../app/policyApp/policy-models/policy_Roles.html | 2 +- .../policy-models/policy_SearchFilter.html | 2 +- .../app/policyApp/service/PolicyAppService.js | 2 +- .../webapp/app/policyApp/service/modalService.js | 2 +- .../app/policyApp/service/userInfoServiceDS2.js | 2 +- .../policy/admin/PolicyManagerServletTest.java | 581 +++++++ .../policy/controller/AdminTabControllerTest.java | 95 ++ .../CreateDcaeMicroServiceControllerTest.java | 646 ++++++++ .../onap/policy/controller/PDPControllerTest.java | 98 ++ .../policy/controller/PolicyControllerTest.java | 66 + .../policy/admin/PolicyManagerServletTest.java | 581 ------- .../policy/controller/AdminTabControllerTest.java | 95 -- .../CreateDcaeMicroServiceControllerTest.java | 646 -------- .../policy/controller/PDPControllerTest.java | 98 -- .../policy/controller/PolicyControllerTest.java | 66 - .../test/resources/Action_TestActionPolicy.1.xml | 2 +- .../Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml | 18 +- .../Config_BRMS_Raw_TestBRMSRawPolicy.1.xml | 20 +- .../resources/Config_FW_TestFireWallPolicy.1.xml | 14 +- .../Config_Fault_TestClosedLoopPolicy.1.xml | 16 +- .../src/test/resources/Config_MS_vFirewall.1.xml | 24 +- .../Config_PM_TestClosedLoopPMPolicy.1.xml | 18 +- .../src/test/resources/Config_SampleTest1206.1.xml | 18 +- ...sion_TestDecisionPolicyWithRuleAlgorithms.1.xml | 8 +- ....Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.txt | 100 +- .../com.Config_Fault_TestClosedLoopPolicy.1.json | 2 +- POLICY-SDK-APP/src/test/resources/logback.xml | 4 +- .../src/test/resources/schedulerPolicies1707.xmi | 44 +- 350 files changed, 17091 insertions(+), 17091 deletions(-) create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyUserInfoController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/admin/RESTfulPAPEngine.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/components/HumanPolicyComponent.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/conf/HibernateSession.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/dao/SystemLogDbDao.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/SystemLogDbDaoImpl.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPGroupContainer.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPPolicyContainer.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/model/Roles.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/utils/ConfigurableRESTUtils.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/utils/PolicyContainer.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/utils/PolicyItemSetChangeNotifier.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/utils/XACMLPolicyWriterWithPapNotify.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/CheckPDP.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyAdapter.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyManagerServlet.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyNotificationMail.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyRestController.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyUserInfoController.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/RESTfulPAPEngine.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/components/HumanPolicyComponent.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/conf/HibernateSession.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/ActionPolicyController.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AdminTabController.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AutoPushController.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSParamController.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSRawController.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateClosedLoopFaultController.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateClosedLoopPMController.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateFirewallController.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreatePolicyController.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DashboardController.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PDPController.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyController.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyExportAndImportController.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyNotificationController.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyRolesController.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/dao/SystemLogDbDao.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/daoImp/CommonClassDaoImpl.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/daoImp/SystemLogDbDaoImpl.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/PDPGroupContainer.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/PDPPolicyContainer.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/Roles.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/ConfigurableRESTUtils.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/PolicyContainer.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/PolicyItemSetChangeNotifier.java delete mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/XACMLPolicyWriterWithPapNotify.java delete mode 100644 POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/EcompNameDictionary.html create mode 100644 POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/OnapNameDictionary.html delete mode 100644 POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/ecompNameEditorController.js create mode 100644 POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/onapNameEditorController.js delete mode 100644 POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/ecompNameDictGridController.js create mode 100644 POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/onapNameDictGridController.js delete mode 100644 POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Dictionary/EcompNameDictionary.html create mode 100644 POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Dictionary/OnapNameDictionary.html create mode 100644 POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyManagerServletTest.java create mode 100644 POLICY-SDK-APP/src/test/java/org/onap/policy/controller/AdminTabControllerTest.java create mode 100644 POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateDcaeMicroServiceControllerTest.java create mode 100644 POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PDPControllerTest.java create mode 100644 POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyControllerTest.java delete mode 100644 POLICY-SDK-APP/src/test/java/org/openecomp/policy/admin/PolicyManagerServletTest.java delete mode 100644 POLICY-SDK-APP/src/test/java/org/openecomp/policy/controller/AdminTabControllerTest.java delete mode 100644 POLICY-SDK-APP/src/test/java/org/openecomp/policy/controller/CreateDcaeMicroServiceControllerTest.java delete mode 100644 POLICY-SDK-APP/src/test/java/org/openecomp/policy/controller/PDPControllerTest.java delete mode 100644 POLICY-SDK-APP/src/test/java/org/openecomp/policy/controller/PolicyControllerTest.java (limited to 'POLICY-SDK-APP/src') diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java new file mode 100644 index 000000000..f983c6650 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java @@ -0,0 +1,181 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.admin; + + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Properties; + +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.xacml.api.XACMLErrorConstants; + +import com.att.research.xacml.util.XACMLProperties; + +public class CheckPDP { + private static Path pdpPath = null; + private static Long oldModified = null; + private static HashMap pdpMap = null; + private static final Logger LOGGER = FlexLogger.getLogger(CheckPDP.class); + + private CheckPDP(){ + //default constructor + } + public static boolean validateID(String id) { + // ReadFile + try { + readFile(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + return false; + } + // Check ID + return (pdpMap.containsKey(id))? true: false; + } + + private static void readFile(){ + String pdpFile = null; + Long newModified = null; + try{ + pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE); + }catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot read the PDP ID File" + e); + return; + } + if (pdpFile == null) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PDP File name not Valid : " + pdpFile); + } + if (pdpPath == null) { + pdpPath = Paths.get(pdpFile); + if (!pdpPath.toFile().exists()) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "File doesn't exist in the specified Path : " + pdpPath.toString()); + + } + if (pdpPath.toString().endsWith(".properties")) { + readProps(); + } else { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file " + pdpFile); + } + } + // Check if File is updated recently + else { + newModified = pdpPath.toFile().lastModified(); + if (!newModified.equals(oldModified)) { + // File has been updated. + readProps(); + } + } + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static void readProps() { + Properties pdpProp = null; + pdpProp = new Properties(); + try { + InputStream in = new FileInputStream(pdpPath.toFile()); + oldModified = pdpPath.toFile().lastModified(); + pdpProp.load(in); + // Read the Properties and Load the PDPs and encoding. + pdpMap = new HashMap<>(); + // Check the Keys for PDP_URLs + Collection unsorted = pdpProp.keySet(); + List sorted = new ArrayList(unsorted); + Collections.sort(sorted); + for (String propKey : sorted) { + loadPDPProperties(propKey, pdpProp); + } + if (pdpMap == null || pdpMap.isEmpty()) { + LOGGER.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Proceed without PDP_URLs"); + } + in.close(); + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + } + } + + private static void loadPDPProperties(String propKey, Properties pdpProp){ + if (propKey.startsWith("PDP_URL")) { + String check_val = pdpProp.getProperty(propKey); + if (check_val == null) { + LOGGER.error("Properties file doesn't have the PDP_URL parameter"); + } + if (check_val != null && check_val.contains(";")) { + List pdp_default = new ArrayList<>(Arrays.asList(check_val.split("\\s*;\\s*"))); + int pdpCount = 0; + while (pdpCount < pdp_default.size()) { + String pdpVal = pdp_default.get(pdpCount); + readPDPParam(pdpVal); + pdpCount++; + } + } + } + } + + private static void readPDPParam(String pdpVal){ + if(pdpVal.contains(",")){ + List pdpValues = new ArrayList<>(Arrays.asList(pdpVal.split("\\s*,\\s*"))); + if(pdpValues.size()==3){ + // 1:2 will be UserID:Password + String userID = pdpValues.get(1); + String pass = pdpValues.get(2); + Base64.Encoder encoder = Base64.getEncoder(); + // 0 - PDPURL + pdpMap.put(pdpValues.get(0), encoder.encodeToString((userID+":"+pass).getBytes(StandardCharsets.UTF_8))); + }else{ + LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpValues); + } + }else{ + LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpVal); + } + } + + public static String getEncoding(String pdpID){ + try { + readFile(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + } + String encoding = null; + if(pdpMap!=null && (!pdpMap.isEmpty())){ + try{ + encoding = pdpMap.get(pdpID); + } catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + } + return encoding; + }else{ + return null; + } + } +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java new file mode 100644 index 000000000..ee4cbcc03 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java @@ -0,0 +1,116 @@ +package org.onap.policy.admin; + +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.controller.ActionPolicyController; +import org.onap.policy.controller.CreateBRMSParamController; +import org.onap.policy.controller.CreateBRMSRawController; +import org.onap.policy.controller.CreateClosedLoopFaultController; +import org.onap.policy.controller.CreateClosedLoopPMController; +import org.onap.policy.controller.CreateDcaeMicroServiceController; +import org.onap.policy.controller.CreateFirewallController; +import org.onap.policy.controller.CreatePolicyController; +import org.onap.policy.controller.DecisionPolicyController; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.jpa.PolicyEntity; + +import com.att.research.xacml.util.XACMLProperties; + +public class PolicyAdapter { + + private static final Logger LOGGER = FlexLogger.getLogger(PolicyAdapter.class); + + public void configure(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + String policyNameValue = null ; + String configPolicyName = null ; + if(extendedOptions(policyAdapter, entity)){ + return; + } + if(policyAdapter.getPolicyName().startsWith("Config_PM")){ + policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_")); + configPolicyName = "ClosedLoop_PM"; + }else if(policyAdapter.getPolicyName().startsWith("Config_Fault")){ + policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_")); + configPolicyName = "ClosedLoop_Fault"; + }else if(policyAdapter.getPolicyName().startsWith("Config_FW")){ + policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_")); + configPolicyName = "Firewall Config"; + }else if(policyAdapter.getPolicyName().startsWith("Config_BRMS_Raw")){ + policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_")); + configPolicyName = "BRMS_Raw"; + }else if(policyAdapter.getPolicyName().startsWith("Config_BRMS_Param")){ + policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_")); + configPolicyName = "BRMS_Param"; + }else if(policyAdapter.getPolicyName().startsWith("Config_MS")){ + policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_")); + configPolicyName = "Micro Service"; + }else if(policyAdapter.getPolicyName().startsWith("Action") || policyAdapter.getPolicyName().startsWith("Decision") ){ + policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_")); + }else{ + policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_")); + configPolicyName = "Base"; + } + if (policyNameValue != null) { + policyAdapter.setPolicyType(policyNameValue); + } + if (configPolicyName != null) { + policyAdapter.setConfigPolicyType(configPolicyName); + } + + if("Action".equalsIgnoreCase(policyAdapter.getPolicyType())){ + ActionPolicyController actionController = new ActionPolicyController(); + actionController.prePopulateActionPolicyData(policyAdapter, entity); + } + if("Decision".equalsIgnoreCase(policyAdapter.getPolicyType())){ + DecisionPolicyController decisionController = new DecisionPolicyController(); + decisionController.prePopulateDecisionPolicyData(policyAdapter, entity); + } + if("Config".equalsIgnoreCase(policyAdapter.getPolicyType())){ + if("Base".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + CreatePolicyController baseController = new CreatePolicyController(); + baseController.prePopulateBaseConfigPolicyData(policyAdapter, entity); + } + else if("BRMS_Raw".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + CreateBRMSRawController brmsController = new CreateBRMSRawController(); + brmsController.prePopulateBRMSRawPolicyData(policyAdapter, entity); + } + else if("BRMS_Param".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + CreateBRMSParamController paramController = new CreateBRMSParamController(); + paramController.prePopulateBRMSParamPolicyData(policyAdapter, entity); + } + else if("ClosedLoop_Fault".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + CreateClosedLoopFaultController newFaultTemplate = new CreateClosedLoopFaultController(); + newFaultTemplate.prePopulateClosedLoopFaultPolicyData(policyAdapter, entity); + } + else if("ClosedLoop_PM".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + CreateClosedLoopPMController pmController = new CreateClosedLoopPMController(); + pmController.prePopulateClosedLoopPMPolicyData(policyAdapter, entity); + } + else if("Micro Service".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + CreateDcaeMicroServiceController msController = new CreateDcaeMicroServiceController(); + msController.prePopulateDCAEMSPolicyData(policyAdapter, entity); + } + else if("Firewall Config".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + CreateFirewallController firewallController = new CreateFirewallController(); + firewallController.prePopulateFWPolicyData(policyAdapter, entity); + } + } + } + + public boolean extendedOptions(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + return false; + } + + public static PolicyAdapter getInstance() { + try { + Class policyAdapter = Class.forName(XACMLProperties.getProperty("policyAdapter.impl.className", PolicyAdapter.class.getName())); + return (PolicyAdapter) policyAdapter.newInstance(); + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException e) { + LOGGER.error("Exception Occured"+e); + } + return null; + } + + + +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java new file mode 100644 index 000000000..036d13aa6 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java @@ -0,0 +1,1477 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.admin; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.json.Json; +import javax.json.JsonArray; +import javax.json.JsonReader; +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebInitParam; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.compress.utils.IOUtils; +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.apache.commons.fileupload.servlet.ServletFileUpload; +import org.apache.http.HttpStatus; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.components.HumanPolicyComponent; +import org.onap.policy.controller.PolicyController; +import org.onap.policy.controller.PolicyExportAndImportController; +import org.onap.policy.model.Roles; +import org.onap.policy.rest.XACMLRest; +import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.jpa.ActionBodyEntity; +import org.onap.policy.rest.jpa.ConfigurationDataEntity; +import org.onap.policy.rest.jpa.PolicyEditorScopes; +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.PolicyUtils; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.util.XACMLPolicyScanner; +import org.openecomp.portalsdk.core.web.support.UserUtils; + +import com.att.research.xacml.util.XACMLProperties; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + + +@WebServlet(value ="/fm/*", loadOnStartup = 1, initParams = { @WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.admin.properties", description = "The location of the properties file holding configuration information.") }) +public class PolicyManagerServlet extends HttpServlet { + private static final Logger LOGGER = FlexLogger.getLogger(PolicyManagerServlet.class); + private static final long serialVersionUID = -8453502699403909016L; + + private enum Mode { + LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION, EXPORT, SEARCHLIST + } + + private static PolicyController policyController; + public synchronized PolicyController getPolicyController() { + return policyController; + } + + public synchronized static void setPolicyController(PolicyController policyController) { + PolicyManagerServlet.policyController = policyController; + } + + private static String CONTENTTYPE = "application/json"; + private static String SUPERADMIN = "super-admin"; + private static String SUPEREDITOR = "super-editor"; + private static String SUPERGUEST = "super-guest"; + private static String ADMIN = "admin"; + private static String EDITOR = "editor"; + private static String GUEST = "guest"; + private static String RESULT = "result"; + + private static Path closedLoopJsonLocation; + private static JsonArray policyNames; + private static String testUserId = null; + + public static JsonArray getPolicyNames() { + return policyNames; + } + + public static void setPolicyNames(JsonArray policyNames) { + PolicyManagerServlet.policyNames = policyNames; + } + + private static List serviceTypeNamesList = new ArrayList<>(); + + public static List getServiceTypeNamesList() { + return serviceTypeNamesList; + } + + @Override + public void init(ServletConfig servletConfig) throws ServletException { + super.init(servletConfig); + // + // Common initialization + // + XACMLRest.xacmlInit(servletConfig); + // + //Initialize ClosedLoop JSON + // + PolicyManagerServlet.initializeJSONLoad(); + } + + protected static void initializeJSONLoad() { + closedLoopJsonLocation = Paths.get(XACMLProperties + .getProperty(XACMLRestProperties.PROP_ADMIN_CLOSEDLOOP)); + FileInputStream inputStream = null; + JsonReader jsonReader = null; + String location = closedLoopJsonLocation.toString(); + try { + inputStream = new FileInputStream(location); + if (location.endsWith("json")) { + jsonReader = Json.createReader(inputStream); + policyNames = jsonReader.readArray(); + serviceTypeNamesList = new ArrayList<>(); + for (int i = 0; i < policyNames.size(); i++) { + javax.json.JsonObject policyName = policyNames.getJsonObject(i); + String name = policyName.getJsonString("serviceTypePolicyName").getString(); + serviceTypeNamesList.add(name); + } + } + } catch (FileNotFoundException e) { + LOGGER.error("Exception Occured while initializing the JSONConfig file"+e); + }finally{ + try { + if(inputStream != null){ + inputStream.close(); + } + if(jsonReader != null){ + jsonReader.close(); + } + } catch (IOException e) { + LOGGER.error("Exception Occured while closing the File InputStream"+e); + } + } + } + + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + LOGGER.debug("doPost"); + try { + // if request contains multipart-form-data + if (ServletFileUpload.isMultipartContent(request)) { + uploadFile(request, response); + } + // all other post request has json params in body + else { + fileOperation(request, response); + } + } catch (Exception e) { + try { + setError(e, response); + }catch(Exception e1){ + LOGGER.error("Exception Occured"+e1); + } + } + } + + //Set Error Message for Exception + private void setError(Exception t, HttpServletResponse response) throws IOException { + try { + JSONObject responseJsonObject = error(t.getMessage()); + response.setContentType(CONTENTTYPE); + PrintWriter out = response.getWriter(); + out.print(responseJsonObject); + out.flush(); + } catch (Exception x) { + LOGGER.error("Exception Occured"+x); + response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, x.getMessage()); + } + } + + //Policy Import Functionality + private void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException { + try { + String newFile; + Map files = new HashMap<>(); + + List items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); + for (FileItem item : items) { + if (!item.isFormField()) { + // Process form file field (input type="file"). + files.put(item.getName(), item.getInputStream()); + if(item.getName().endsWith(".xls")){ + OutputStream outputStream = null; + try{ + File file = new File(item.getName()); + outputStream = new FileOutputStream(file); + IOUtils.copy(item.getInputStream(), outputStream); + outputStream.close(); + newFile = file.toString(); + PolicyExportAndImportController importController = new PolicyExportAndImportController(); + importController.importRepositoryFile(newFile, request); + }catch(Exception e){ + LOGGER.error("Upload error : " + e); + }finally{ + if(outputStream != null){ + outputStream.close(); + } + } + } + } + } + + JSONObject responseJsonObject = null; + responseJsonObject = this.success(); + response.setContentType(CONTENTTYPE); + PrintWriter out = response.getWriter(); + out.print(responseJsonObject); + out.flush(); + } catch (Exception e) { + LOGGER.debug("Cannot write file"); + throw new ServletException("Cannot write file", e); + } + } + + //File Operation Functionality + private void fileOperation(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + JSONObject responseJsonObject = null; + try { + StringBuilder sb = new StringBuilder(); + BufferedReader br = request.getReader(); + String str; + while ((str = br.readLine()) != null) { + sb.append(str); + } + br.close(); + JSONObject jObj = new JSONObject(sb.toString()); + JSONObject params = jObj.getJSONObject("params"); + Mode mode = Mode.valueOf(params.getString("mode")); + switch (mode) { + case ADDFOLDER: + case ADDSUBSCOPE: + responseJsonObject = addFolder(params, request); + break; + case COPY: + responseJsonObject = copy(params, request); + break; + case DELETE: + responseJsonObject = delete(params, request); + break; + case EDITFILE: + case VIEWPOLICY: + responseJsonObject = editFile(params); + break; + case LIST: + responseJsonObject = list(params, request); + break; + case RENAME: + responseJsonObject = rename(params, request); + break; + case DESCRIBEPOLICYFILE: + responseJsonObject = describePolicy(params); + break; + case SWITCHVERSION: + responseJsonObject = switchVersion(params, request); + break; + case SEARCHLIST: + responseJsonObject = searchPolicyList(params, request); + break; + default: + throw new ServletException("not implemented"); + } + if (responseJsonObject == null) { + responseJsonObject = error("generic error : responseJsonObject is null"); + } + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While doing File Operation" + e); + responseJsonObject = error(e.getMessage()); + } + response.setContentType(CONTENTTYPE); + PrintWriter out = response.getWriter(); + out.print(responseJsonObject); + out.flush(); + } + + private JSONObject searchPolicyList(JSONObject params, HttpServletRequest request) { + Set scopes = null; + List roles = null; + List policyData = new ArrayList<>(); + JSONArray policyList = null; + if(params.has("policyList")){ + policyList = (JSONArray) params.get("policyList"); + } + PolicyController controller = getPolicyControllerInstance(); + List resultList = new ArrayList<>(); + try { + //Get the Login Id of the User from Request + String userId = UserUtils.getUserSession(request).getOrgUserId(); + //Check if the Role and Scope Size are Null get the values from db. + List userRoles = controller.getRoles(userId); + roles = new ArrayList<>(); + scopes = new HashSet<>(); + for(Object role: userRoles){ + Roles userRole = (Roles) role; + roles.add(userRole.getRole()); + if(userRole.getScope() != null){ + if(userRole.getScope().contains(",")){ + String[] multipleScopes = userRole.getScope().split(","); + for(int i =0; i < multipleScopes.length; i++){ + scopes.add(multipleScopes[i]); + } + }else{ + scopes.add(userRole.getScope()); + } + } + } + if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) { + if(scopes.isEmpty()){ + return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin"); + } + Set tempScopes = scopes; + for(String scope : tempScopes){ + List scopesList = queryPolicyEditorScopes(scope); + if(!scopesList.isEmpty()){ + for(int i = 0; i < scopesList.size(); i++){ + PolicyEditorScopes tempScope = (PolicyEditorScopes) scopesList.get(i); + scopes.add(tempScope.getScopeName()); + } + } + } + } + if(policyList!= null){ + for(int i = 0; i < policyList.length(); i++){ + String policyName = policyList.get(i).toString().replace(".xml", ""); + String version = policyName.substring(policyName.lastIndexOf(".")+1); + policyName = policyName.substring(0, policyName.lastIndexOf(".")).replace(".", File.separator); + if(policyName.contains("\\")){ + policyName = policyName.replace("\\", "\\\\"); + } + String policyVersionQuery = "From PolicyVersion where policy_name ='"+policyName+"' and active_version = '"+version+"'and id >0"; + List activeData = controller.getDataByQuery(policyVersionQuery); + if(!activeData.isEmpty()){ + PolicyVersion policy = (PolicyVersion) activeData.get(0); + JSONObject el = new JSONObject(); + el.put("name", policy.getPolicyName().replace(File.separator, "/")); + el.put("date", policy.getModifiedDate()); + el.put("version", policy.getActiveVersion()); + el.put("size", ""); + el.put("type", "file"); + el.put("createdBy", getUserName(policy.getCreatedBy())); + el.put("modifiedBy", getUserName(policy.getModifiedBy())); + resultList.add(el); + } + } + }else{ + if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST) ){ + policyData = controller.getData(PolicyVersion.class); + }else{ + List filterdatas = controller.getData(PolicyVersion.class); + for(Object filter : filterdatas){ + PolicyVersion filterdata = (PolicyVersion) filter; + try{ + String scopeName = filterdata.getPolicyName().substring(0, filterdata.getPolicyName().lastIndexOf(File.separator)); + if(scopes.contains(scopeName)){ + policyData.add(filterdata); + } + }catch(Exception e){ + LOGGER.error("Exception occured while filtering policyversion data"+e); + } + } + } + + if(!policyData.isEmpty()){ + for(int i =0; i < policyData.size(); i++){ + PolicyVersion policy = (PolicyVersion) policyData.get(i); + JSONObject el = new JSONObject(); + el.put("name", policy.getPolicyName().replace(File.separator, "/")); + el.put("date", policy.getModifiedDate()); + el.put("version", policy.getActiveVersion()); + el.put("size", ""); + el.put("type", "file"); + el.put("createdBy", getUserName(policy.getCreatedBy())); + el.put("modifiedBy", getUserName(policy.getModifiedBy())); + resultList.add(el); + } + } + } + }catch(Exception e){ + LOGGER.error("Exception occured while reading policy Data from Policy Version table for Policy Search Data"+e); + } + + return new JSONObject().put(RESULT, resultList); + } + + //Switch Version Functionality + private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException{ + String path = params.getString("path"); + String userId = null; + try { + userId = UserUtils.getUserSession(request).getOrgUserId(); + } catch (Exception e) { + LOGGER.error("Exception Occured while reading userid from cookie" +e); + } + String policyName; + String removeExtension = path.replace(".xml", ""); + if(path.startsWith("/")){ + policyName = removeExtension.substring(1, removeExtension.lastIndexOf(".")); + }else{ + policyName = removeExtension.substring(0, removeExtension.lastIndexOf(".")); + } + + String activePolicy = null; + PolicyController controller = getPolicyControllerInstance(); + if(params.toString().contains("activeVersion")){ + String activeVersion = params.getString("activeVersion"); + String highestVersion = params.get("highestVersion").toString(); + if(Integer.parseInt(activeVersion) > Integer.parseInt(highestVersion)){ + return error("The Version shouldn't be greater than Highest Value"); + }else{ + activePolicy = policyName + "." + activeVersion + ".xml"; + String dbCheckName = activePolicy.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_")){ + dbCheckName = dbCheckName.replace(".Decision_", ":Decision_"); + } + String[] splitDBCheckName = dbCheckName.split(":"); + String peQuery = "FROM PolicyEntity where policyName = '"+splitDBCheckName[1]+"' and scope ='"+splitDBCheckName[0]+"'"; + List policyEntity = controller.getDataByQuery(peQuery); + PolicyEntity pentity = (PolicyEntity) policyEntity.get(0); + if(pentity.isDeleted()){ + return error("The Policy is Not Existing in Workspace"); + }else{ + if(policyName.contains("/")){ + policyName = policyName.replace("/", File.separator); + } + policyName = policyName.substring(policyName.indexOf(File.separator)+1); + if(policyName.contains("\\")){ + policyName = policyName.replace(File.separator, "\\"); + } + policyName = splitDBCheckName[0].replace(".", File.separator)+File.separator+policyName; + String watchPolicyName = policyName; + if(policyName.contains("/")){ + policyName = policyName.replace("/", File.separator); + } + if(policyName.contains("\\")){ + policyName = policyName.replace("\\", "\\\\"); + } + String query = "update PolicyVersion set active_version='"+activeVersion+"' where policy_name ='"+policyName+"' and id >0"; + //query the database + controller.executeQuery(query); + //Policy Notification + PolicyVersion entity = new PolicyVersion(); + entity.setPolicyName(watchPolicyName); + entity.setActiveVersion(Integer.parseInt(activeVersion)); + entity.setModifiedBy(userId); + controller.watchPolicyFunction(entity, activePolicy, "SwitchVersion"); + return success(); + } + } + } + return controller.switchVersionPolicyContent(policyName); + } + + //Describe Policy + private JSONObject describePolicy(JSONObject params) throws ServletException{ + JSONObject object = null; + String path = params.getString("path"); + String policyName = null; + if(path.startsWith("/")){ + path = path.substring(1); + policyName = path.substring(path.lastIndexOf("/") +1); + path = path.replace("/", "."); + }else{ + path = path.replace("/", "."); + policyName = path; + } + if(path.contains("Config_")){ + path = path.replace(".Config_", ":Config_"); + }else if(path.contains("Action_")){ + path = path.replace(".Action_", ":Action_"); + }else if(path.contains("Decision_")){ + path = path.replace(".Decision_", ":Decision_"); + } + PolicyController controller = getPolicyControllerInstance(); + String[] split = path.split(":"); + String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'"; + List queryData = controller.getDataByQuery(query); + if(!queryData.isEmpty()){ + PolicyEntity entity = (PolicyEntity) queryData.get(0); + File temp = null; + BufferedWriter bw = null; + try { + temp = File.createTempFile(policyName, ".tmp"); + bw = new BufferedWriter(new FileWriter(temp)); + bw.write(entity.getPolicyData()); + bw.close(); + object = HumanPolicyComponent.DescribePolicy(temp); + } catch (IOException e) { + LOGGER.error("Exception Occured while Describing the Policy"+e); + }finally{ + if(temp != null){ + temp.delete(); + } + if(bw != null){ + try { + bw.close(); + } catch (IOException e) { + LOGGER.error("Exception Occured while Closing the File Writer"+e); + } + } + } + }else{ + return error("Error Occured while Describing the Policy"); + } + + return object; + } + + //Get the List of Policies and Scopes for Showing in Editor tab + private JSONObject list(JSONObject params, HttpServletRequest request) throws ServletException { + Set scopes = null; + List roles = null; + try { + PolicyController controller = getPolicyControllerInstance(); + //Get the Login Id of the User from Request + String testUserID = getTestUserId(); + String userId = testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId(); + //Check if the Role and Scope Size are Null get the values from db. + List userRoles = controller.getRoles(userId); + roles = new ArrayList<>(); + scopes = new HashSet<>(); + for(Object role: userRoles){ + Roles userRole = (Roles) role; + roles.add(userRole.getRole()); + if(userRole.getScope() != null){ + if(userRole.getScope().contains(",")){ + String[] multipleScopes = userRole.getScope().split(","); + for(int i =0; i < multipleScopes.length; i++){ + scopes.add(multipleScopes[i]); + } + }else{ + scopes.add(userRole.getScope()); + } + } + } + + List resultList = new ArrayList<>(); + boolean onlyFolders = params.getBoolean("onlyFolders"); + String path = params.getString("path"); + if(path.contains("..xml")){ + path = path.replaceAll("..xml", "").trim(); + } + + if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) { + if(scopes.isEmpty()){ + return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin"); + }else{ + if(!"/".equals(path)){ + String tempScope = path.substring(1, path.length()); + tempScope = tempScope.replace("/", File.separator); + scopes.add(tempScope); + } + } + } + + if("/".equals(path)){ + if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){ + List scopesList = queryPolicyEditorScopes(null); + for(Object list : scopesList){ + PolicyEditorScopes scope = (PolicyEditorScopes) list; + if(!(scope.getScopeName().contains(File.separator))){ + JSONObject el = new JSONObject(); + el.put("name", scope.getScopeName()); + el.put("date", scope.getCreatedDate()); + el.put("size", ""); + el.put("type", "dir"); + el.put("createdBy", scope.getUserCreatedBy().getUserName()); + el.put("modifiedBy", scope.getUserModifiedBy().getUserName()); + resultList.add(el); + } + } + }else if(roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)){ + for(Object scope : scopes){ + JSONObject el = new JSONObject(); + List scopesList = queryPolicyEditorScopes(scope.toString()); + if(!scopesList.isEmpty()){ + PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0); + el.put("name", scopeById.getScopeName()); + el.put("date", scopeById.getCreatedDate()); + el.put("size", ""); + el.put("type", "dir"); + el.put("createdBy", scopeById.getUserCreatedBy().getUserName()); + el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName()); + resultList.add(el); + } + } + } + }else{ + try{ + String scopeName = path.substring(path.indexOf("/") +1); + activePolicyList(scopeName, resultList, roles, scopes, onlyFolders); + } catch (Exception ex) { + LOGGER.error("Error Occured While reading Policy Files List"+ex ); + } + } + + return new JSONObject().put(RESULT, resultList); + } catch (Exception e) { + LOGGER.error("list", e); + return error(e.getMessage()); + } + } + + private List queryPolicyEditorScopes(String scopeName){ + String scopeNamequery = ""; + if(scopeName == null){ + scopeNamequery = "from PolicyEditorScopes"; + }else{ + scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"%'"; + } + PolicyController controller = getPolicyControllerInstance(); + List scopesList = controller.getDataByQuery(scopeNamequery); + return scopesList; + } + + //Get Active Policy List based on Scope Selection form Policy Version table + private void activePolicyList(String scopeName, List resultList, List roles, Set scopes, boolean onlyFolders){ + PolicyController controller = getPolicyControllerInstance(); + if(scopeName.contains("/")){ + scopeName = scopeName.replace("/", File.separator); + } + if(scopeName.contains("\\")){ + scopeName = scopeName.replace("\\", "\\\\\\\\"); + } + String query = "from PolicyVersion where POLICY_NAME like '" +scopeName+"%'"; + String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like '" +scopeName+"%'"; + List activePolicies = controller.getDataByQuery(query); + List scopesList = controller.getDataByQuery(scopeNamequery); + for(Object list : scopesList){ + PolicyEditorScopes scopeById = (PolicyEditorScopes) list; + String scope = scopeById.getScopeName(); + if(scope.contains(File.separator)){ + String checkScope = scope.substring(0, scope.lastIndexOf(File.separator)); + if(scopeName.contains("\\\\")){ + scopeName = scopeName.replace("\\\\", File.separator); + } + if(scope.contains(File.separator)){ + scope = scope.substring(checkScope.length()+1); + if(scope.contains(File.separator)){ + scope = scope.substring(0, scope.indexOf(File.separator)); + } + } + if(scopeName.equalsIgnoreCase(checkScope)){ + JSONObject el = new JSONObject(); + el.put("name", scope); + el.put("date", scopeById.getModifiedDate()); + el.put("size", ""); + el.put("type", "dir"); + el.put("createdBy", scopeById.getUserCreatedBy().getUserName()); + el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName()); + resultList.add(el); + } + } + } + String scopeNameCheck = null; + for (Object list : activePolicies) { + PolicyVersion policy = (PolicyVersion) list; + String scopeNameValue = policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator)); + if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){ + if((scopeName.contains("\\\\"))){ + scopeNameCheck = scopeName.replace("\\\\", File.separator); + }else{ + scopeNameCheck = scopeName; + } + if(scopeNameValue.equals(scopeNameCheck)){ + JSONObject el = new JSONObject(); + el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1)); + el.put("date", policy.getModifiedDate()); + el.put("version", policy.getActiveVersion()); + el.put("size", ""); + el.put("type", "file"); + el.put("createdBy", getUserName(policy.getCreatedBy())); + el.put("modifiedBy", getUserName(policy.getModifiedBy())); + resultList.add(el); + } + }else if(!scopes.isEmpty()){ + if(scopes.contains(scopeNameValue)){ + JSONObject el = new JSONObject(); + el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1)); + el.put("date", policy.getModifiedDate()); + el.put("version", policy.getActiveVersion()); + el.put("size", ""); + el.put("type", "file"); + el.put("createdBy", getUserName(policy.getCreatedBy())); + el.put("modifiedBy", getUserName(policy.getModifiedBy())); + resultList.add(el); + } + } + } + } + + private String getUserName(String loginId){ + PolicyController controller = getPolicyControllerInstance(); + UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId); + if(userInfo == null){ + return SUPERADMIN; + } + return userInfo.getUserName(); + } + + //Rename Policy + private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException { + try { + boolean isActive = false; + List policyActiveInPDP = new ArrayList<>(); + Set scopeOfPolicyActiveInPDP = new HashSet<>(); + String userId = UserUtils.getUserSession(request).getOrgUserId(); + String oldPath = params.getString("path"); + String newPath = params.getString("newPath"); + oldPath = oldPath.substring(oldPath.indexOf("/")+1); + newPath = newPath.substring(newPath.indexOf("/")+1); + if(oldPath.endsWith(".xml")){ + JSONObject result = policyRename(oldPath, newPath, userId); + if(!(Boolean)(result.getJSONObject("result").get("success"))){ + return result; + } + }else{ + String scopeName = oldPath; + String newScopeName = newPath; + if(scopeName.contains("/")){ + scopeName = scopeName.replace("/", File.separator); + newScopeName = newScopeName.replace("/", File.separator); + } + if(scopeName.contains("\\")){ + scopeName = scopeName.replace("\\", "\\\\\\\\"); + newScopeName = newScopeName.replace("\\", "\\\\\\\\"); + } + PolicyController controller = getPolicyControllerInstance(); + String query = "from PolicyVersion where POLICY_NAME like'" +scopeName+"%'"; + String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"%'"; + List activePolicies = controller.getDataByQuery(query); + List scopesList = controller.getDataByQuery(scopeNamequery); + for(Object object : activePolicies){ + PolicyVersion activeVersion = (PolicyVersion) object; + String policyOldPath = activeVersion.getPolicyName().replace(File.separator, "/") + "." + activeVersion.getActiveVersion() + ".xml"; + String policyNewPath = policyOldPath.replace(oldPath, newPath); + JSONObject result = policyRename(policyOldPath, policyNewPath, userId); + if(!(Boolean)(result.getJSONObject("result").get("success"))){ + isActive = true; + policyActiveInPDP.add(policyOldPath); + String scope = policyOldPath.substring(0, policyOldPath.lastIndexOf("/")); + scopeOfPolicyActiveInPDP.add(scope.replace("/", File.separator)); + } + } + boolean rename = false; + if(activePolicies.size() != policyActiveInPDP.size()){ + rename = true; + } + + UserInfo userInfo = new UserInfo(); + userInfo.setUserLoginId(userId); + if(policyActiveInPDP.size() == 0){ + renameScope(scopesList, scopeName, newScopeName, controller); + }else if(rename){ + renameScope(scopesList, scopeName, newScopeName, controller); + for(String scope : scopeOfPolicyActiveInPDP){ + PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes(); + editorScopeEntity.setScopeName(scope.replace("\\", "\\\\\\\\")); + editorScopeEntity.setUserCreatedBy(userInfo); + editorScopeEntity.setUserModifiedBy(userInfo); + controller.saveData(editorScopeEntity); + } + } + if(isActive){ + return error("The Following policies rename failed. Since they are active in PDP Groups" +policyActiveInPDP); + } + } + return success(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e); + return error(e.getMessage()); + } + } + + private void renameScope(List scopesList, String scopeName, String newScopeName, PolicyController controller){ + for(Object object : scopesList){ + PolicyEditorScopes editorScopeEntity = (PolicyEditorScopes) object; + if(scopeName.contains("\\\\\\\\")){ + scopeName = scopeName.replace("\\\\\\\\", File.separator); + newScopeName = newScopeName.replace("\\\\\\\\", File.separator); + } + String scope = editorScopeEntity.getScopeName().replace(scopeName, newScopeName); + editorScopeEntity.setScopeName(scope); + controller.updateData(editorScopeEntity); + } + } + + private JSONObject policyRename(String oldPath, String newPath, String userId) throws ServletException { + try { + PolicyEntity entity = null; + PolicyController controller = getPolicyControllerInstance(); + + String policyVersionName = newPath.replace(".xml", ""); + String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf(".")).replace("/", File.separator); + + String oldpolicyVersionName = oldPath.replace(".xml", ""); + String oldpolicyName = oldpolicyVersionName.substring(0, oldpolicyVersionName.lastIndexOf(".")).replace("/", File.separator); + + String newpolicyName = newPath.replace("/", "."); + String newPolicyCheck = newpolicyName; + if(newPolicyCheck.contains("Config_")){ + newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_"); + }else if(newPolicyCheck.contains("Action_")){ + newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_"); + }else if(newPolicyCheck.contains("Decision_")){ + newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_"); + } + String[] newPolicySplit = newPolicyCheck.split(":"); + + String orignalPolicyName = oldPath.replace("/", "."); + String oldPolicyCheck = orignalPolicyName; + if(oldPolicyCheck.contains("Config_")){ + oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_"); + }else if(oldPolicyCheck.contains("Action_")){ + oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_"); + }else if(oldPolicyCheck.contains("Decision_")){ + oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_"); + } + String[] oldPolicySplit = oldPolicyCheck.split(":"); + + //Check PolicyEntity table with newPolicy Name + String policyEntityquery = "FROM PolicyEntity where policyName = '"+newPolicySplit[1]+"' and scope ='"+newPolicySplit[0]+"'"; + List queryData = controller.getDataByQuery(policyEntityquery); + if(!queryData.isEmpty()){ + entity = (PolicyEntity) queryData.get(0); + return error("Policy rename failed. Since, the policy with same name already exists."); + } + + //Query the Policy Entity with oldPolicy Name + String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf(".")); + String oldpolicyEntityquery = "FROM PolicyEntity where policyName like '"+policyEntityCheck+"%' and scope ='"+oldPolicySplit[0]+"'"; + List oldEntityData = controller.getDataByQuery(oldpolicyEntityquery); + if(!oldEntityData.isEmpty()){ + String groupQuery = "FROM PolicyGroupEntity where ("; + for(int i=0; i groupEntityData = controller.getDataByQuery(groupQuery); + if(groupEntityData.size() > 0){ + return error("Policy rename failed. Since the policy or its version is active in PDP Groups."); + } + for(int i=0; i queryData = controller.getDataByQuery(policyEntityquery); + if(!queryData.isEmpty()){ + return error("Policy already exists with same name"); + } + + //Query the Policy Entity with oldPolicy Name + policyEntityquery = "FROM PolicyEntity where policyName = '"+oldPolicySplit[1]+"' and scope ='"+oldPolicySplit[0]+"'"; + queryData = controller.getDataByQuery(policyEntityquery); + if(!queryData.isEmpty()){ + entity = (PolicyEntity) queryData.get(0); + } + if(entity != null){ + cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId); + success = true; + } + + if(success){ + PolicyVersion entityItem = new PolicyVersion(); + entityItem.setActiveVersion(Integer.parseInt(version)); + entityItem.setHigherVersion(Integer.parseInt(version)); + entityItem.setPolicyName(policyName); + entityItem.setCreatedBy(userId); + entityItem.setModifiedBy(userId); + controller.saveData(entityItem); + } + + LOGGER.debug("copy from: {} to: {}" + oldPath +newPath); + + return success(); + } catch (Exception e) { + LOGGER.error("copy", e); + return error(e.getMessage()); + } + } + + //Delete Policy or Scope Functionality + private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException { + PolicyController controller = getPolicyControllerInstance(); + PolicyRestController restController = new PolicyRestController(); + PolicyEntity policyEntity = null; + String policyNamewithoutExtension; + try { + String userId = UserUtils.getUserSession(request).getOrgUserId(); + String deleteVersion = ""; + String path = params.getString("path"); + LOGGER.debug("delete {}" +path); + if(params.has("deleteVersion")){ + deleteVersion = params.getString("deleteVersion"); + } + path = path.substring(path.indexOf("/")+1); + String policyNamewithExtension = path.replace("/", File.separator); + String policyVersionName = policyNamewithExtension.replace(".xml", ""); + String query = ""; + if(path.endsWith(".xml")){ + policyNamewithoutExtension = policyVersionName.substring(0, policyVersionName.lastIndexOf(".")); + policyNamewithoutExtension = policyNamewithoutExtension.replace(File.separator, "."); + String splitPolicyName = null; + if(policyNamewithoutExtension.contains("Config_")){ + splitPolicyName = policyNamewithoutExtension.replace(".Config_", ":Config_"); + }else if(policyNamewithoutExtension.contains("Action_")){ + splitPolicyName = policyNamewithoutExtension.replace(".Action_", ":Action_"); + }else if(policyNamewithoutExtension.contains("Decision_")){ + splitPolicyName = policyNamewithoutExtension.replace(".Decision_", ":Decision_"); + } + String[] split = splitPolicyName.split(":"); + query = "FROM PolicyEntity where policyName like '"+split[1]+"%' and scope ='"+split[0]+"'"; + }else{ + policyNamewithoutExtension = path.replace(File.separator, "."); + query = "FROM PolicyEntity where scope like '"+policyNamewithoutExtension+"%'"; + } + + List policyEntityobjects = controller.getDataByQuery(query); + String activePolicyName = null; + boolean pdpCheck = false; + if(path.endsWith(".xml")){ + policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator); + int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf(".")+1)); + if("ALL".equals(deleteVersion)){ + if(!policyEntityobjects.isEmpty()){ + for(Object object : policyEntityobjects){ + policyEntity = (PolicyEntity) object; + String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'"; + List groupobject = controller.getDataByQuery(groupEntityquery); + if(!groupobject.isEmpty()){ + pdpCheck = true; + activePolicyName = policyEntity.getScope() +"."+ policyEntity.getPolicyName(); + }else{ + //Delete the entity from Elastic Search Database + String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); + restController.deleteElasticData(searchFileName); + //Delete the entity from Policy Entity table + controller.deleteData(policyEntity); + if(policyNamewithoutExtension.contains("Config_")){ + controller.deleteData(policyEntity.getConfigurationData()); + }else if(policyNamewithoutExtension.contains("Action_")){ + controller.deleteData(policyEntity.getActionBodyEntity()); + } + } + } + } + //Policy Notification + PolicyVersion versionEntity = new PolicyVersion(); + versionEntity.setPolicyName(policyNamewithoutExtension); + versionEntity.setModifiedBy(userId); + controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll"); + if(pdpCheck){ + //Delete from policyVersion table + String getActivePDPPolicyVersion = activePolicyName.replace(".xml", ""); + getActivePDPPolicyVersion = getActivePDPPolicyVersion.substring(getActivePDPPolicyVersion.lastIndexOf(".")+1); + String policyVersionQuery = "update PolicyVersion set active_version='"+getActivePDPPolicyVersion+"' , highest_version='"+getActivePDPPolicyVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0"; + if(policyVersionQuery != null){ + controller.executeQuery(policyVersionQuery); + } + return error("Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: "+activePolicyName); + }else{ + //No Active Policy in PDP. So, deleting all entries from policyVersion table + String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0"; + if(policyVersionQuery != null){ + controller.executeQuery(policyVersionQuery); + } + } + }else if("CURRENT".equals(deleteVersion)){ + String currentVersionPolicyName = policyNamewithExtension.substring(policyNamewithExtension.lastIndexOf(File.separator)+1); + String currentVersionScope = policyNamewithExtension.substring(0, policyNamewithExtension.lastIndexOf(File.separator)).replace(File.separator, "."); + query = "FROM PolicyEntity where policyName = '"+currentVersionPolicyName+"' and scope ='"+currentVersionScope+"'"; + List policyEntitys = controller.getDataByQuery(query); + if(!policyEntitys.isEmpty()){ + policyEntity = (PolicyEntity) policyEntitys.get(0); + } + if(policyEntity != null){ + String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"' and policyid > 0"; + List groupobject = controller.getDataByQuery(groupEntityquery); + if(groupobject.isEmpty()){ + //Delete the entity from Elastic Search Database + String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); + restController.deleteElasticData(searchFileName); + //Delete the entity from Policy Entity table + controller.deleteData(policyEntity); + if(policyNamewithoutExtension.contains("Config_")){ + controller.deleteData(policyEntity.getConfigurationData()); + }else if(policyNamewithoutExtension.contains("Action_")){ + controller.deleteData(policyEntity.getActionBodyEntity()); + } + + if(version > 1){ + int highestVersion = 0; + if(!policyEntityobjects.isEmpty()){ + for(Object object : policyEntityobjects){ + policyEntity = (PolicyEntity) object; + String policyEntityName = policyEntity.getPolicyName().replace(".xml", ""); + int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf(".")+1)); + if(policyEntityVersion > highestVersion && policyEntityVersion != version){ + highestVersion = policyEntityVersion; + } + } + } + + //Policy Notification + PolicyVersion entity = new PolicyVersion(); + entity.setPolicyName(policyNamewithoutExtension); + entity.setActiveVersion(highestVersion); + entity.setModifiedBy(userId); + controller.watchPolicyFunction(entity, policyNamewithExtension, "DeleteOne"); + + String updatequery = "update PolicyVersion set active_version='"+highestVersion+"' , highest_version='"+highestVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"'"; + controller.executeQuery(updatequery); + }else{ + String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0"; + if(policyVersionQuery != null){ + controller.executeQuery(policyVersionQuery); + } + } + }else{ + return error("Policy can't be deleted, it is active in PDP Groups. PolicyName: '"+policyEntity.getScope() + "." +policyEntity.getPolicyName()+"'"); + } + } + } + }else{ + List activePoliciesInPDP = new ArrayList(); + if(!policyEntityobjects.isEmpty()){ + for(Object object : policyEntityobjects){ + policyEntity = (PolicyEntity) object; + String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'"; + List groupobject = controller.getDataByQuery(groupEntityquery); + if(!groupobject.isEmpty()){ + pdpCheck = true; + activePoliciesInPDP.add(policyEntity.getScope()+"."+policyEntity.getPolicyName()); + }else{ + //Delete the entity from Elastic Search Database + String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); + restController.deleteElasticData(searchFileName); + //Delete the entity from Policy Entity table + controller.deleteData(policyEntity); + policyNamewithoutExtension = policyEntity.getPolicyName(); + if(policyNamewithoutExtension.contains("Config_")){ + controller.deleteData(policyEntity.getConfigurationData()); + }else if(policyNamewithoutExtension.contains("Action_")){ + controller.deleteData(policyEntity.getActionBodyEntity()); + } + } + } + //Delete from policyVersion and policyEditor Scope table + String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"+path.replace("\\", "\\\\")+"%' and id >0"; + controller.executeQuery(policyVersionQuery); + + //Policy Notification + PolicyVersion entity = new PolicyVersion(); + entity.setPolicyName(path); + entity.setModifiedBy(userId); + controller.watchPolicyFunction(entity, path, "DeleteScope"); + if(pdpCheck){ + //Add Active Policies List to PolicyVersionTable + for(int i =0; i < activePoliciesInPDP.size(); i++){ + String activePDPPolicyName = activePoliciesInPDP.get(i).replace(".xml", ""); + int activePDPPolicyVersion = Integer.parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf(".")+1)); + activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf(".")).replace(".", File.separator); + PolicyVersion insertactivePDPVersion = new PolicyVersion(); + insertactivePDPVersion.setPolicyName(activePDPPolicyName); + insertactivePDPVersion.setHigherVersion(activePDPPolicyVersion); + insertactivePDPVersion.setActiveVersion(activePDPPolicyVersion); + insertactivePDPVersion.setCreatedBy(userId); + insertactivePDPVersion.setModifiedBy(userId); + controller.saveData(insertactivePDPVersion); + } + + return error("All the Policies has been deleted in Scope. Except the following list of Policies:"+activePoliciesInPDP); + }else{ + String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0"; + controller.executeQuery(policyScopeQuery); + } + }else{ + String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0"; + controller.executeQuery(policyScopeQuery); + } + } + return success(); + } catch (Exception e) { + LOGGER.error("delete", e); + return error(e.getMessage()); + } + } + + //Edit the Policy + private JSONObject editFile(JSONObject params) throws ServletException { + // get content + try { + PolicyController controller = getPolicyControllerInstance(); + String mode = params.getString("mode"); + String path = params.getString("path"); + LOGGER.debug("editFile path: {}"+ path); + + String domain = path.substring(1, path.lastIndexOf("/")); + domain = domain.replace("/", "."); + + path = path.substring(1); + path = path.replace("/", "."); + String dbCheckName = path; + if(dbCheckName.contains("Config_")){ + dbCheckName = dbCheckName.replace(".Config_", ":Config_"); + }else if(dbCheckName.contains("Action_")){ + dbCheckName = dbCheckName.replace(".Action_", ":Action_"); + }else if(dbCheckName.contains("Decision_")){ + dbCheckName = dbCheckName.replace(".Decision_", ":Decision_"); + } + + String[] split = dbCheckName.split(":"); + String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'"; + List queryData = controller.getDataByQuery(query); + PolicyEntity entity = (PolicyEntity) queryData.get(0); + InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8)); + + + Object policy = XACMLPolicyScanner.readPolicy(stream); + PolicyRestAdapter policyAdapter = new PolicyRestAdapter(); + policyAdapter.setData(policy); + + if("viewPolicy".equalsIgnoreCase(mode)){ + policyAdapter.setReadOnly(true); + policyAdapter.setEditPolicy(false); + }else{ + policyAdapter.setReadOnly(false); + policyAdapter.setEditPolicy(true); + } + policyAdapter.setDomain(domain); + policyAdapter.setDomainDir(domain); + policyAdapter.setPolicyData(policy); + String policyName = path.replace(".xml", ""); + policyName = policyName.substring(0, policyName.lastIndexOf(".")); + policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf(".")+1)); + + PolicyAdapter setpolicyAdapter = PolicyAdapter.getInstance(); + setpolicyAdapter.configure(policyAdapter,entity); + + policyAdapter.setParentPath(null); + ObjectMapper mapper = new ObjectMapper(); + String json = mapper.writeValueAsString(policyAdapter); + JsonNode jsonNode = mapper.readTree(json); + + return new JSONObject().put(RESULT, jsonNode); + } catch (Exception e) { + LOGGER.error("editFile", e); + return error(e.getMessage()); + } + } + + //Add Scopes + private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException { + PolicyController controller = getPolicyControllerInstance(); + String name = ""; + try { + String userId = UserUtils.getUserSession(request).getOrgUserId(); + String path = params.getString("path"); + try{ + if(params.has("subScopename")){ + if(!params.getString("subScopename").equals("")){ + name = params.getString("path").replace("/", File.separator) + File.separator +params.getString("subScopename"); + } + }else{ + name = params.getString("name"); + } + }catch(Exception e){ + name = params.getString("name"); + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope"+e); + } + String validateName; + if(name.contains(File.separator)){ + validateName = name.substring(name.lastIndexOf(File.separator)+1); + }else{ + validateName = name; + } + if(!name.isEmpty()){ + String validate = PolicyUtils.emptyPolicyValidator(validateName); + if(!validate.contains("success")){ + return error(validate); + } + } + LOGGER.debug("addFolder path: {} name: {}" + path +name); + if(!name.equals("")){ + if(name.startsWith(File.separator)){ + name = name.substring(1); + } + PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, "scopeName", name); + if(entity == null){ + UserInfo userInfo = new UserInfo(); + userInfo.setUserLoginId(userId); + PolicyEditorScopes newScope = new PolicyEditorScopes(); + newScope.setScopeName(name); + newScope.setUserCreatedBy(userInfo); + newScope.setUserModifiedBy(userInfo); + controller.saveData(newScope); + }else{ + return error("Scope Already Exists"); + } + } + return success(); + } catch (Exception e) { + LOGGER.error("addFolder", e); + return error(e.getMessage()); + } + } + + //Return Error Object + private JSONObject error(String msg) throws ServletException { + try { + JSONObject result = new JSONObject(); + result.put("success", false); + result.put("error", msg); + return new JSONObject().put(RESULT, result); + } catch (JSONException e) { + throw new ServletException(e); + } + } + + //Return Success Object + private JSONObject success() throws ServletException { + try { + JSONObject result = new JSONObject(); + result.put("success", true); + result.put("error", (Object) null); + return new JSONObject().put(RESULT, result); + } catch (JSONException e) { + throw new ServletException(e); + } + } + + private PolicyController getPolicyControllerInstance(){ + return policyController != null ? getPolicyController() : new PolicyController(); + } + + public String getTestUserId() { + return testUserId; + } + + public static void setTestUserId(String testUserId) { + PolicyManagerServlet.testUserId = testUserId; + } +} \ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java new file mode 100644 index 000000000..bf89c01ff --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java @@ -0,0 +1,163 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.admin; + +import java.io.File; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; +import java.util.Properties; + +import javax.mail.MessagingException; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeMessage; + +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.controller.PolicyController; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.PolicyVersion; +import org.onap.policy.rest.jpa.WatchPolicyNotificationTable; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.springframework.beans.factory.annotation.Configurable; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.mail.javamail.JavaMailSenderImpl; +import org.springframework.mail.javamail.MimeMessageHelper; + +@Configurable +public class PolicyNotificationMail{ + private static Logger policyLogger = FlexLogger.getLogger(PolicyNotificationMail.class); + + @Bean + public JavaMailSenderImpl javaMailSenderImpl(){ + JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); + mailSender.setHost(PolicyController.getSmtpHost()); + mailSender.setPort(Integer.parseInt(PolicyController.getSmtpPort())); + mailSender.setUsername(PolicyController.getSmtpUsername()); + mailSender.setPassword(PolicyController.getSmtpPassword()); + Properties prop = mailSender.getJavaMailProperties(); + prop.put("mail.transport.protocol", "smtp"); + prop.put("mail.smtp.auth", "true"); + prop.put("mail.smtp.starttls.enable", "true"); + prop.put("mail.debug", "true"); + return mailSender; + } + + public void sendMail(PolicyVersion entityItem, String policyName, String mode, CommonClassDao policyNotificationDao) throws MessagingException { + String from = PolicyController.getSmtpUsername(); + String to = ""; + String subject = ""; + String message = ""; + DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + Date date = new Date(); + if("EditPolicy".equalsIgnoreCase(mode)){ + subject = "Policy has been Updated : "+entityItem.getPolicyName(); + message = "The Policy Which you are watching in " + PolicyController.getSmtpApplicationName() + " has been Updated" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' + "Active Version : " +entityItem.getActiveVersion() + + '\n' + '\n' + "Modified By : " +entityItem.getModifiedBy() + '\n' + "Modified Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; + } + if("Rename".equalsIgnoreCase(mode)){ + subject = "Policy has been Renamed : "+entityItem.getPolicyName(); + message = "The Policy Which you are watching in " + PolicyController.getSmtpApplicationName() + " has been Renamed" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' + "Active Version : " +entityItem.getActiveVersion() + + '\n' + '\n' + "Renamed By : " +entityItem.getModifiedBy() + '\n' + "Renamed Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; + } + if("DeleteAll".equalsIgnoreCase(mode)){ + subject = "Policy has been Deleted : "+entityItem.getPolicyName(); + message = "The Policy Which you are watching in " + PolicyController.getSmtpApplicationName() + " has been Deleted with All Versions" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' + + '\n' + '\n' + "Deleted By : " +entityItem.getModifiedBy() + '\n' + "Deleted Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; + } + if("DeleteOne".equalsIgnoreCase(mode)){ + subject = "Policy has been Deleted : "+entityItem.getPolicyName(); + message = "The Policy Which you are watching in " + PolicyController.getSmtpApplicationName() + " has been Deleted" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' +"Policy Version : " +entityItem.getActiveVersion() + + '\n' + '\n' + "Deleted By : " +entityItem.getModifiedBy() + '\n' + "Deleted Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; + } + if("DeleteScope".equalsIgnoreCase(mode)){ + subject = "Scope has been Deleted : "+entityItem.getPolicyName(); + message = "The Scope Which you are watching in " + PolicyController.getSmtpApplicationName() + " has been Deleted" + '\n' + '\n' + '\n'+ "Scope + Scope Name : " + policyName + '\n' + + '\n' + '\n' + "Deleted By : " +entityItem.getModifiedBy() + '\n' + "Deleted Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; + } + if("SwitchVersion".equalsIgnoreCase(mode)){ + subject = "Policy has been SwitchedVersion : "+entityItem.getPolicyName(); + message = "The Policy Which you are watching in " + PolicyController.getSmtpApplicationName() + " has been SwitchedVersion" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' + "Active Version : " +entityItem.getActiveVersion() + + '\n' + '\n' + "Switched By : " +entityItem.getModifiedBy() + '\n' + "Switched Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; + } + if("Move".equalsIgnoreCase(mode)){ + subject = "Policy has been Moved to Other Scope : "+entityItem.getPolicyName(); + message = "The Policy Which you are watching in " + PolicyController.getSmtpApplicationName() + " has been Moved to Other Scope" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' + "Active Version : " +entityItem.getActiveVersion() + + '\n' + '\n' + "Moved By : " +entityItem.getModifiedBy() + '\n' + "Moved Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; + } + String policyFileName = entityItem.getPolicyName(); + String checkPolicyName = policyName; + if(policyFileName.contains("/")){ + policyFileName = policyFileName.substring(0, policyFileName.indexOf("/")); + policyFileName = policyFileName.replace("/", File.separator); + } + if(policyFileName.contains("\\")){ + policyFileName = policyFileName.substring(0, policyFileName.indexOf("\\")); + policyFileName = policyFileName.replace("\\", "\\\\"); + } + + String query = "from WatchPolicyNotificationTable where policyName like'" +policyFileName+"%'"; + boolean sendFlag = false; + List watchList = policyNotificationDao.getDataByQuery(query); + if(watchList != null && !watchList.isEmpty()){ + for(Object watch : watchList){ + WatchPolicyNotificationTable list = (WatchPolicyNotificationTable) watch; + String watchPolicyName = list.getPolicyName(); + if(watchPolicyName.contains("Config_") || watchPolicyName.contains("Action_") || watchPolicyName.contains("Decision_")){ + if(watchPolicyName.equals(checkPolicyName)){ + sendFlag = true; + }else{ + sendFlag = false; + } + } + if(sendFlag){ + AnnotationConfigApplicationContext ctx = null; + try { + to = list.getLoginIds()+"@"+PolicyController.getSmtpEmailExtension(); + to = to.trim(); + ctx = new AnnotationConfigApplicationContext(); + ctx.register(PolicyNotificationMail.class); + ctx.refresh(); + JavaMailSenderImpl mailSender = ctx.getBean(JavaMailSenderImpl.class); + MimeMessage mimeMessage = mailSender.createMimeMessage(); + MimeMessageHelper mailMsg = new MimeMessageHelper(mimeMessage); + mailMsg.setFrom(new InternetAddress(from, "Policy Notification System")); + mailMsg.setTo(to); + mailMsg.setSubject(subject); + mailMsg.setText(message); + mailSender.send(mimeMessage); + if(mode.equalsIgnoreCase("Rename") || mode.contains("Delete") || mode.contains("Move")){ + policyNotificationDao.delete(watch); + } + } catch (Exception e) { + policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Exception Occured in Policy Notification" +e); + }finally{ + if(ctx != null){ + ctx.close(); + } + } + } + } + } + } +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java new file mode 100644 index 000000000..e99f35bde --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java @@ -0,0 +1,443 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.admin; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintWriter; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.apache.commons.fileupload.servlet.ServletFileUpload; +import org.apache.commons.io.IOUtils; +import org.json.JSONObject; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.controller.CreateClosedLoopFaultController; +import org.onap.policy.controller.CreateDcaeMicroServiceController; +import org.onap.policy.controller.CreateFirewallController; +import org.onap.policy.controller.PolicyController; +import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.PolicyVersion; +import org.onap.policy.utils.PolicyUtils; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.servlet.ModelAndView; + +import com.att.research.xacml.util.XACMLProperties; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; + +@RestController +@RequestMapping("/") +public class PolicyRestController extends RestrictedBaseController{ + + private static final Logger policyLogger = FlexLogger.getLogger(PolicyRestController.class); + + private static final String modal = "model"; + private static final String importDictionary = "import_dictionary"; + + @Autowired + CommonClassDao commonClassDao; + + @RequestMapping(value={"/policycreation/save_policy"}, method={RequestMethod.POST}) + public void policyCreationController(HttpServletRequest request, HttpServletResponse response) { + String userId = UserUtils.getUserSession(request).getOrgUserId(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + try{ + JsonNode root = mapper.readTree(request.getReader()); + + PolicyRestAdapter policyData = mapper.readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class); + + if("file".equals(root.get(PolicyController.getPolicydata()).get(modal).get("type").toString().replace("\"", ""))){ + policyData.setEditPolicy(true); + } + if(root.get(PolicyController.getPolicydata()).get(modal).get("path").size() != 0){ + String dirName = ""; + for(int i = 0; i < root.get(PolicyController.getPolicydata()).get(modal).get("path").size(); i++){ + dirName = dirName.replace("\"", "") + root.get(PolicyController.getPolicydata()).get(modal).get("path").get(i).toString().replace("\"", "") + File.separator; + } + if(policyData.isEditPolicy()){ + policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator))); + }else{ + policyData.setDomainDir(dirName + root.get(PolicyController.getPolicydata()).get(modal).get("name").toString().replace("\"", "")); + } + }else{ + String domain = root.get(PolicyController.getPolicydata()).get("model").get("name").toString(); + if(domain.contains("/")){ + domain = domain.substring(0, domain.lastIndexOf('/')).replace("/", File.separator); + } + domain = domain.replace("\"", ""); + policyData.setDomainDir(domain); + } + + if(policyData.getConfigPolicyType() != null){ + if("ClosedLoop_Fault".equalsIgnoreCase(policyData.getConfigPolicyType())){ + CreateClosedLoopFaultController faultController = new CreateClosedLoopFaultController(); + policyData = faultController.setDataToPolicyRestAdapter(policyData, root); + }else if("Firewall Config".equalsIgnoreCase(policyData.getConfigPolicyType())){ + CreateFirewallController fwController = new CreateFirewallController(); + policyData = fwController.setDataToPolicyRestAdapter(policyData); + }else if("Micro Service".equalsIgnoreCase(policyData.getConfigPolicyType())){ + CreateDcaeMicroServiceController msController = new CreateDcaeMicroServiceController(); + policyData = msController.setDataToPolicyRestAdapter(policyData, root); + } + } + + policyData.setUserId(userId); + + String result; + String body = PolicyUtils.objectToJsonString(policyData); + String uri = request.getRequestURI(); + ResponseEntity responseEntity = sendToPAP(body, uri, HttpMethod.POST); + if(responseEntity != null && responseEntity.getBody().equals(HttpServletResponse.SC_CONFLICT)){ + result = "PolicyExists"; + }else if(responseEntity != null){ + result = responseEntity.getBody().toString(); + String policyName = responseEntity.getHeaders().get("policyName").get(0); + if(policyData.isEditPolicy() && "success".equalsIgnoreCase(result)){ + PolicyNotificationMail email = new PolicyNotificationMail(); + String mode = "EditPolicy"; + String watchPolicyName = policyName.replace(".xml", ""); + String version = watchPolicyName.substring(watchPolicyName.lastIndexOf('.')+1); + watchPolicyName = watchPolicyName.substring(0, watchPolicyName.lastIndexOf('.')).replace(".", File.separator); + String policyVersionName = watchPolicyName.replace(".", File.separator); + watchPolicyName = watchPolicyName + "." + version + ".xml"; + PolicyVersion entityItem = new PolicyVersion(); + entityItem.setPolicyName(policyVersionName); + entityItem.setActiveVersion(Integer.parseInt(version)); + entityItem.setModifiedBy(userId); + email.sendMail(entityItem, watchPolicyName, mode, commonClassDao); + } + }else{ + result = "Response is null from PAP"; + } + + response.setCharacterEncoding(PolicyController.getCharacterencoding()); + response.setContentType(PolicyController.getContenttype()); + request.setCharacterEncoding(PolicyController.getCharacterencoding()); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(result); + JSONObject j = new JSONObject("{policyData: " + responseString + "}"); + out.write(j.toString()); + }catch(Exception e){ + policyLogger.error("Exception Occured while saving policy" , e); + } + } + + + private ResponseEntity sendToPAP(String body, String requestURI, HttpMethod method){ + String papUrl = PolicyController.getPapUrl(); + String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); + String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS); + + Base64.Encoder encoder = Base64.getEncoder(); + String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8)); + HttpHeaders headers = new HttpHeaders(); + headers.set("Authorization", "Basic " + encoding); + headers.set("Content-Type", PolicyController.getContenttype()); + + RestTemplate restTemplate = new RestTemplate(); + HttpEntity requestEntity = new HttpEntity<>(body, headers); + ResponseEntity result = null; + HttpClientErrorException exception = null; + + try{ + result = restTemplate.exchange(papUrl + requestURI, method, requestEntity, String.class); + }catch(Exception e){ + policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl, e); + exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage()); + if("409 Conflict".equals(e.getMessage())){ + return ResponseEntity.ok(HttpServletResponse.SC_CONFLICT); + } + } + if(exception != null && exception.getStatusCode()!=null){ + if(exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)){ + String message = XACMLErrorConstants.ERROR_PERMISSIONS +":"+exception.getStatusCode()+":" + "ERROR_AUTH_GET_PERM" ; + policyLogger.error(message); + } + if(exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)){ + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString(); + policyLogger.error(message); + } + if(exception.getStatusCode().equals(HttpStatus.NOT_FOUND)){ + String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl + exception; + policyLogger.error(message); + } + String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString(); + policyLogger.error(message); + } + return result; + } + + private String callPAP(HttpServletRequest request , String method, String uriValue){ + String uri = uriValue; + String boundary = null; + String papUrl = PolicyController.getPapUrl(); + String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); + String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS); + + Base64.Encoder encoder = Base64.getEncoder(); + String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8)); + HttpHeaders headers = new HttpHeaders(); + headers.set("Authorization", "Basic " + encoding); + headers.set("Content-Type", PolicyController.getContenttype()); + + + HttpURLConnection connection = null; + List items; + FileItem item = null; + File file = null; + if(uri.contains(importDictionary)){ + try { + items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); + item = items.get(0); + file = new File(item.getName()); + String newFile = file.toString(); + uri = uri +"&dictionaryName="+newFile; + } catch (Exception e2) { + policyLogger.error("Exception Occured while calling PAP with import dictionary request"+e2); + } + } + + try { + URL url = new URL(papUrl + uri); + connection = (HttpURLConnection)url.openConnection(); + connection.setRequestMethod(method); + connection.setUseCaches(false); + connection.setInstanceFollowRedirects(false); + connection.setRequestProperty("Authorization", "Basic " + encoding); + connection.setDoOutput(true); + connection.setDoInput(true); + + if(!uri.contains("searchPolicy?action=delete&")){ + + if(!(uri.endsWith("set_BRMSParamData") || uri.contains(importDictionary))){ + connection.setRequestProperty("Content-Type",PolicyController.getContenttype()); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = null; + try { + root = mapper.readTree(request.getReader()); + }catch (Exception e1) { + policyLogger.error("Exception Occured while calling PAP"+e1); + } + + ObjectMapper mapper1 = new ObjectMapper(); + mapper1.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true); + + Object obj = mapper1.treeToValue(root, Object.class); + String json = mapper1.writeValueAsString(obj); + + Object content = new ByteArrayInputStream(json.getBytes()); + + if (content instanceof InputStream) { + // send current configuration + try (OutputStream os = connection.getOutputStream()) { + int count = IOUtils.copy((InputStream) content, os); + if (policyLogger.isDebugEnabled()) { + policyLogger.debug("copied to output, bytes=" + count); + } + } + } + }else{ + if(uri.endsWith("set_BRMSParamData")){ + connection.setRequestProperty("Content-Type",PolicyController.getContenttype()); + try (OutputStream os = connection.getOutputStream()) { + IOUtils.copy((InputStream) request.getInputStream(), os); + } + }else{ + boundary = "===" + System.currentTimeMillis() + "==="; + connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary); + try (OutputStream os = connection.getOutputStream()) { + if(item != null){ + IOUtils.copy((InputStream) item.getInputStream(), os); + } + } + } + } + } + + connection.connect(); + + int responseCode = connection.getResponseCode(); + if(responseCode == 200){ + // get the response content into a String + String responseJson = null; + // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file) + java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream()); + scanner.useDelimiter("\\A"); + responseJson = scanner.hasNext() ? scanner.next() : ""; + scanner.close(); + policyLogger.info("JSON response from PAP: " + responseJson); + return responseJson; + } + + } catch (Exception e) { + policyLogger.error("Exception Occured"+e); + }finally{ + if(file != null && file.exists() && file.delete()){ + policyLogger.info("File Deleted Successfully"); + } + if (connection != null) { + try { + // For some reason trying to get the inputStream from the connection + // throws an exception rather than returning null when the InputStream does not exist. + InputStream is = connection.getInputStream(); + if (is != null) { + is.close(); + } + } catch (IOException ex) { + policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex); + } + connection.disconnect(); + } + } + return null; + } + + @RequestMapping(value={"/getDictionary/*"}, method={RequestMethod.GET}) + public void getDictionaryController(HttpServletRequest request, HttpServletResponse response){ + String uri = request.getRequestURI().replace("/getDictionary", ""); + String body = null; + ResponseEntity responseEntity = sendToPAP(null, uri, HttpMethod.GET); + if(responseEntity != null){ + body = responseEntity.getBody().toString(); + }else{ + body = ""; + } + try { + response.getWriter().write(body); + } catch (IOException e) { + policyLogger.error("Exception occured while getting Dictionary entries", e); + } + } + + @RequestMapping(value={"/saveDictionary/*/*"}, method={RequestMethod.POST}) + public ModelAndView saveDictionaryController(HttpServletRequest request, HttpServletResponse response) throws Exception{ + String uri = request.getRequestURI().replace("/saveDictionary", ""); + if(uri.contains(importDictionary)){ + String userId = UserUtils.getUserSession(request).getOrgUserId(); + uri = uri+ "?userId=" +userId; + } + String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim()); + response.getWriter().write(body); + return null; + } + + @RequestMapping(value={"/deleteDictionary/*/*"}, method={RequestMethod.POST}) + public ModelAndView deletetDictionaryController(HttpServletRequest request, HttpServletResponse response) throws Exception{ + String uri = request.getRequestURI().replace("/deleteDictionary", ""); + String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim()); + response.getWriter().write(body); + return null; + } + + @RequestMapping(value={"/searchDictionary"}, method={RequestMethod.POST}) + public ModelAndView searchDictionaryController(HttpServletRequest request, HttpServletResponse response) throws Exception{ + Object resultList = null; + String uri = request.getRequestURI(); + try{ + String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim()); + if(body.contains("CouldNotConnectException")){ + List data = new ArrayList<>(); + data.add("Elastic Search Server is down"); + resultList = data; + }else{ + JSONObject json = new JSONObject(body); + resultList = json.get("policyresult"); + } + }catch(Exception e){ + policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception Occured while querying Elastic Search: " + e); + List data = new ArrayList<>(); + data.add("Elastic Search Server is down"); + resultList = data; + } + + response.setCharacterEncoding(PolicyController.getCharacterencoding()); + response.setContentType(PolicyController.getContenttype()); + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{result: " + resultList + "}"); + out.write(j.toString()); + return null; + } + + @RequestMapping(value={"/searchPolicy"}, method={RequestMethod.POST}) + public ModelAndView searchPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + Object resultList = null; + String uri = request.getRequestURI()+"?action=search"; + String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim()); + + JSONObject json = new JSONObject(body); + try{ + resultList = json.get("policyresult"); + }catch(Exception e){ + List data = new ArrayList<>(); + data.add("Elastic Search Server is down"); + resultList = data; + policyLogger.error("Exception Occured while searching for Policy in Elastic Database" +e); + } + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{result: " + resultList + "}"); + out.write(j.toString()); + return null; + } + + public void deleteElasticData(String fileName){ + String uri = "searchPolicy?action=delete&policyName='"+fileName+"'"; + callPAP(null, "POST", uri.trim()); + } + +} \ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyUserInfoController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyUserInfoController.java new file mode 100644 index 000000000..65312a957 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyUserInfoController.java @@ -0,0 +1,62 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.admin; + +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import com.fasterxml.jackson.databind.ObjectMapper; + +@Controller +@RequestMapping("/") +public class PolicyUserInfoController extends RestrictedBaseController{ + + private static final Logger LOGGER = FlexLogger.getLogger(PolicyUserInfoController.class); + + @RequestMapping(value="/get_PolicyUserInfo", method = RequestMethod.GET) + private void getPolicyUserInfo(HttpServletRequest request, HttpServletResponse response){ + JsonMessage msg = null; + try { + String userId = UserUtils.getUserSession(request).getOrgUserId(); + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("userid", userId); + msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } catch (Exception e) { + LOGGER.error("Exception Occured"+e); + } + } + +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/RESTfulPAPEngine.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/RESTfulPAPEngine.java new file mode 100644 index 000000000..d75af075d --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/RESTfulPAPEngine.java @@ -0,0 +1,517 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.admin; + + + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.UnsupportedEncodingException; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.io.IOUtils; +import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.api.pap.OnapPDP; +import org.onap.policy.xacml.api.pap.OnapPDPGroup; +import org.onap.policy.xacml.api.pap.PAPPolicyEngine; +import org.onap.policy.xacml.std.pap.StdPAPPolicy; +import org.onap.policy.xacml.std.pap.StdPDP; +import org.onap.policy.xacml.std.pap.StdPDPGroup; +import org.onap.policy.xacml.std.pap.StdPDPItemSetChangeNotifier; +import org.onap.policy.xacml.std.pap.StdPDPPolicy; +import org.onap.policy.xacml.std.pap.StdPDPStatus; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.api.pap.PDPPolicy; +import com.att.research.xacml.api.pap.PDPStatus; +import com.att.research.xacml.util.XACMLProperties; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.type.CollectionType; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + +/** + * Implementation of the PAPEngine interface that communicates with a PAP engine in a remote servlet + * through a RESTful interface + * + * + */ +public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyEngine { + private static final Logger LOGGER = FlexLogger.getLogger(RESTfulPAPEngine.class); + + private static final String groupID = "groupId="; + + // + // URL of the PAP Servlet that this Admin Console talks to + // + private String papServletURLString; + + /** + * Set up link with PAP Servlet and get our initial set of Groups + * @throws Exception + */ + public RESTfulPAPEngine (String myURLString) throws PAPException, IOException { + // + // Get our URL to the PAP servlet + // + this.papServletURLString = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); + if (this.papServletURLString == null || this.papServletURLString.length() == 0) { + String message = "The property 'POLICYENGINE_ADMIN_ACTIVE' was not set during installation. Admin Console cannot call PAP."; + LOGGER.error(message); + throw new PAPException(message); + } + + // + // register this Admin Console with the PAP Servlet to get updates + // + Object newURL = sendToPAP("PUT", null, null, null, "adminConsoleURL=" + myURLString); + if (newURL != null) { + // assume this was a re-direct and try again + LOGGER.warn("Redirecting to '" + newURL + "'"); + this.papServletURLString = (String)newURL; + newURL = sendToPAP("PUT", null, null, null, "adminConsoleURL=" + myURLString); + if (newURL != null) { + LOGGER.error("Failed to redirect to " + this.papServletURLString); + throw new PAPException("Failed to register with PAP"); + } + } + } + + + // + // High-level commands used by the Admin Console code through the PAPEngine Interface + // + + @Override + public OnapPDPGroup getDefaultGroup() throws PAPException { + return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID, "default="); + } + + @Override + public void SetDefaultGroup(OnapPDPGroup group) throws PAPException { + sendToPAP("POST", null, null, null, groupID + group.getId(), "default=true"); + } + + @SuppressWarnings("unchecked") + @Override + public Set getOnapPDPGroups() throws PAPException { + Set newGroupSet; + newGroupSet = (Set) this.sendToPAP("GET", null, Set.class, StdPDPGroup.class, groupID); + return Collections.unmodifiableSet(newGroupSet); + } + + + @Override + public OnapPDPGroup getGroup(String id) throws PAPException { + return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID + id); + } + + @Override + public void newGroup(String name, String description) + throws PAPException, NullPointerException { + String escapedName = null; + String escapedDescription = null; + try { + escapedName = URLEncoder.encode(name, "UTF-8"); + escapedDescription = URLEncoder.encode(description, "UTF-8"); + } catch (UnsupportedEncodingException e) { + throw new PAPException("Unable to send name or description to PAP: " + e.getMessage() +e); + } + + this.sendToPAP("POST", null, null, null, groupID, "groupName="+escapedName, "groupDescription=" + escapedDescription); + } + + + /** + * Update the configuration on the PAP for a single Group. + * + * @param group + * @return + * @throws PAPException + */ + public void updateGroup(OnapPDPGroup group) throws PAPException { + + try { + + // + // ASSUME that all of the policies mentioned in this group are already located in the correct directory on the PAP! + // + // Whenever a Policy is added to the group, that file must be automatically copied to the PAP from the Workspace. + // + + + // Copy all policies from the local machine's workspace to the PAP's PDPGroup directory. + // This is not efficient since most of the policies will already exist there. + // However, the policy files are (probably!) not too huge, and this is a good way to ensure that any corrupted files on the PAP get refreshed. + + + // now update the group object on the PAP + + sendToPAP("PUT", group, null, null, groupID + group.getId()); + } catch (Exception e) { + String message = "Unable to PUT policy '" + group.getId() + "', e:" + e; + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); + throw new PAPException(message); + } + } + + + @Override + public void removeGroup(OnapPDPGroup group, OnapPDPGroup newGroup) + throws PAPException, NullPointerException { + String moveToGroupString = null; + if (newGroup != null) { + moveToGroupString = "movePDPsToGroupId=" + newGroup.getId(); + } + sendToPAP("DELETE", null, null, null, groupID + group.getId(), moveToGroupString); + } + + @Override + public OnapPDPGroup getPDPGroup(OnapPDP pdp) throws PAPException { + return getPDPGroup(pdp.getId()); + } + + + public OnapPDPGroup getPDPGroup(String pdpId) throws PAPException { + return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID, "pdpId=" + pdpId, "getPDPGroup="); + } + + @Override + public OnapPDP getPDP(String pdpId) throws PAPException { + return (OnapPDP)sendToPAP("GET", null, null, StdPDP.class, groupID, "pdpId=" + pdpId); + } + + @Override + public void newPDP(String id, OnapPDPGroup group, String name, String description, int jmxport) throws PAPException, + NullPointerException { + StdPDP newPDP = new StdPDP(id, name, description, jmxport); + sendToPAP("PUT", newPDP, null, null, groupID + group.getId(), "pdpId=" + id); + return; + } + + @Override + public void movePDP(OnapPDP pdp, OnapPDPGroup newGroup) throws PAPException { + sendToPAP("POST", null, null, null, groupID + newGroup.getId(), "pdpId=" + pdp.getId()); + return; + } + + @Override + public void updatePDP(OnapPDP pdp) throws PAPException { + OnapPDPGroup group = getPDPGroup(pdp); + sendToPAP("PUT", pdp, null, null, groupID + group.getId(), "pdpId=" + pdp.getId()); + return; + } + + @Override + public void removePDP(OnapPDP pdp) throws PAPException { + OnapPDPGroup group = getPDPGroup(pdp); + sendToPAP("DELETE", null, null, null, groupID + group.getId(), "pdpId=" + pdp.getId()); + return; + } + + //Validate the Policy Data + public boolean validatePolicyRequest(PolicyRestAdapter policyAdapter, String policyType) throws PAPException { + Boolean isValidData = false; + StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getConfigBodyData(), policyAdapter.getConfigType(), "Base"); + + //send JSON object to PAP + isValidData = (Boolean) sendToPAP("PUT", newPAPPolicy, null, null, "operation=validate", "apiflag=admin", "policyType=" + policyType); + return isValidData; + } + + + + @Override + public void publishPolicy(String id, String name, boolean isRoot, + InputStream policy, OnapPDPGroup group) throws PAPException { + + + // copy the (one) file into the target directory on the PAP servlet + copyFile(id, group, policy); + + // adjust the local copy of the group to include the new policy + PDPPolicy pdpPolicy = new StdPDPPolicy(id, isRoot, name); + group.getPolicies().add(pdpPolicy); + + // tell the PAP servlet to include the policy in the configuration + updateGroup(group); + + return; + } + + /** + * Copy a single Policy file from the input stream to the PAP Servlet. + * Either this works (silently) or it throws an exception. + * + * @param policyId + * @param group + * @param policy + * @return + * @throws PAPException + */ + public void copyFile(String policyId, OnapPDPGroup group, InputStream policy) throws PAPException { + // send the policy file to the PAP Servlet + try { + sendToPAP("POST", policy, null, null, groupID + group.getId(), "policyId="+policyId); + } catch (Exception e) { + String message = "Unable to PUT policy '" + policyId + "', e:" + e; + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); + throw new PAPException(message); + } + } + + + @Override + public void copyPolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException { + if (policy == null || group == null) { + throw new PAPException("Null input policy="+policy+" group="+group); + } + try (InputStream is = new FileInputStream(new File(policy.getLocation())) ) { + copyFile(policy.getId(), group, is ); + } catch (Exception e) { + String message = "Unable to PUT policy '" + policy.getId() + "', e:" + e; + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); + throw new PAPException(message); + } + } + + @Override + public void removePolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException { + throw new PAPException("NOT IMPLEMENTED"); + + } + + + /** + * Special operation - Similar to the normal PAP operations but this one contacts the PDP directly + * to get detailed status info. + * + * @param pdp + * @return + * @throws PAPException + */ + + public PDPStatus getStatus(OnapPDP pdp) throws PAPException { + return (StdPDPStatus)sendToPAP("GET", pdp, null, StdPDPStatus.class); + } + + + // + // Internal Operations called by the PAPEngine Interface methods + // + + /** + * Send a request to the PAP Servlet and get the response. + * + * The content is either an InputStream to be copied to the Request OutputStream + * OR it is an object that is to be encoded into JSON and pushed into the Request OutputStream. + * + * The Request parameters may be encoded in multiple "name=value" sets, or parameters may be combined by the caller. + * + * @param method + * @param content - EITHER an InputStream OR an Object to be encoded in JSON + * @param collectionTypeClass + * @param responseContentClass + * @param parameters + * @return + * @throws Exception + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + private Object sendToPAP(String method, Object content, Class collectionTypeClass, Class responseContentClass, String... parameters ) throws PAPException { + HttpURLConnection connection = null; + String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); + LOGGER.info("User Id is " + papID); + String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS); + Base64.Encoder encoder = Base64.getEncoder(); + String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8)); + LOGGER.info("Encoding for the PAP is: " + encoding); + try { + String fullURL = papServletURLString; + if (parameters != null && parameters.length > 0) { + String queryString = ""; + for (String p : parameters) { + queryString += "&" + p; + } + fullURL += "?" + queryString.substring(1); + } + + // special case - Status (actually the detailed status) comes from the PDP directly, not the PAP + if (method.equals("GET") && (content instanceof OnapPDP) && responseContentClass == StdPDPStatus.class) { + // Adjust the url and properties appropriately + String pdpID =((OnapPDP)content).getId(); + fullURL = pdpID + "?type=Status"; + content = null; + if(CheckPDP.validateID(pdpID)){ + encoding = CheckPDP.getEncoding(pdpID); + } + } + + + URL url = new URL(fullURL); + + // + // Open up the connection + // + connection = (HttpURLConnection)url.openConnection(); + // + // Setup our method and headers + // + connection.setRequestMethod(method); + connection.setUseCaches(false); + // + // Adding this in. It seems the HttpUrlConnection class does NOT + // properly forward our headers for POST re-direction. It does so + // for a GET re-direction. + // + // So we need to handle this ourselves. + // + connection.setInstanceFollowRedirects(false); + connection.setRequestProperty("Authorization", "Basic " + encoding); + connection.setDoOutput(true); + connection.setDoInput(true); + + if (content != null) { + if (content instanceof InputStream) { + try { + // + // Send our current policy configuration + // + try (OutputStream os = connection.getOutputStream()) { + int count = IOUtils.copy((InputStream)content, os); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("copied to output, bytes="+count); + } + } + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to write content in '" + method + "'", e); + } + } else { + // The content is an object to be encoded in JSON + ObjectMapper mapper = new ObjectMapper(); + mapper.writeValue(connection.getOutputStream(), content); + } + } + // + // Do the connect + // + connection.connect(); + if (connection.getResponseCode() == 204) { + LOGGER.info("Success - no content."); + return null; + } else if (connection.getResponseCode() == 200) { + LOGGER.info("Success. We have a return object."); + String isValidData = connection.getHeaderField("isValidData"); + String isSuccess = connection.getHeaderField("successMapKey"); + Map successMap = new HashMap<>(); + if (isValidData != null && isValidData.equalsIgnoreCase("true")){ + LOGGER.info("Policy Data is valid."); + return true; + } else if (isValidData != null && isValidData.equalsIgnoreCase("false")) { + LOGGER.info("Policy Data is invalid."); + return false; + } else if (isSuccess != null && isSuccess.equalsIgnoreCase("success")) { + LOGGER.info("Policy Created Successfully!" ); + String finalPolicyPath = connection.getHeaderField("finalPolicyPath"); + successMap.put("success", finalPolicyPath); + return successMap; + } else if (isSuccess != null && isSuccess.equalsIgnoreCase("error")) { + LOGGER.info("There was an error while creating the policy!"); + successMap.put("error", "error"); + return successMap; + } else { + // get the response content into a String + String json = null; + // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file) + java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream()); + scanner.useDelimiter("\\A"); + json = scanner.hasNext() ? scanner.next() : ""; + scanner.close(); + LOGGER.info("JSON response from PAP: " + json); + + // convert Object sent as JSON into local object + ObjectMapper mapper = new ObjectMapper(); + mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + if (collectionTypeClass != null) { + // collection of objects expected + final CollectionType javaType = + mapper.getTypeFactory().constructCollectionType(collectionTypeClass, responseContentClass); + + Object objectFromJSON = mapper.readValue(json, javaType); + return objectFromJSON; + } else { + // single value object expected + Object objectFromJSON = mapper.readValue(json, responseContentClass); + return objectFromJSON; + } + } + + } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) { + // redirection + String newURL = connection.getHeaderField("Location"); + if (newURL == null) { + LOGGER.error("No Location header to redirect to when response code="+connection.getResponseCode()); + throw new IOException("No redirect Location header when response code="+connection.getResponseCode()); + } + int qIndex = newURL.indexOf("?"); + if (qIndex > 0) { + newURL = newURL.substring(0, qIndex); + } + LOGGER.info("Redirect seen. Redirecting " + fullURL + " to " + newURL); + return newURL; + } else { + LOGGER.warn("Unexpected response code: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); + throw new IOException("Server Response: " + connection.getResponseCode() + ": " + connection.getResponseMessage()); + } + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "HTTP Request/Response to PAP: " + e,e); + throw new PAPException("Request/Response threw :" + e); + } finally { + // cleanup the connection + if (connection != null) { + try { + // For some reason trying to get the inputStream from the connection + // throws an exception rather than returning null when the InputStream does not exist. + InputStream is = connection.getInputStream(); + if (is != null) { + is.close(); + } + } catch (IOException ex) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex); + } + connection.disconnect(); + } + } + } +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/components/HumanPolicyComponent.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/components/HumanPolicyComponent.java new file mode 100644 index 000000000..a0f1ba86d --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/components/HumanPolicyComponent.java @@ -0,0 +1,991 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.components; + + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.xml.bind.JAXBElement; + +import org.apache.commons.io.FilenameUtils; +import org.json.JSONObject; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.controller.PolicyController; +import org.onap.policy.rest.jpa.FunctionDefinition; +import org.onap.policy.utils.XACMLPolicyWriterWithPapNotify; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.util.XACMLPolicyScanner; + +import com.att.research.xacml.api.AttributeValue; +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacml.std.StdAttribute; +import com.att.research.xacml.std.StdAttributeValue; +import com.att.research.xacml.util.XACMLPolicyScanner.CallbackResult; +import com.att.research.xacml.util.XACMLPolicyScanner.SimpleCallback; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeSelectorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType; +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 oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType; + + + +public class HumanPolicyComponent{ + + private static final Logger LOGGER = FlexLogger.getLogger(HumanPolicyComponent.class); + + // Constants Used in XML Creation + public static final String CATEGORY_RECIPIENT_SUBJECT = "urn:oasis:names:tc:xacml:1.0:subject-category:recipient-subject"; + public static final String CATEGORY_RESOURCE = "urn:oasis:names:tc:xacml:3.0:attribute-category:resource"; + public static final String CATEGORY_ACTION = "urn:oasis:names:tc:xacml:3.0:attribute-category:action"; + public static final String CATEGORY_ACCESS_SUBJECT = "urn:oasis:names:tc:xacml:1.0:subject-category:access-subject"; + public static final String ACTION_ID = "urn:oasis:names:tc:xacml:1.0:action:action-id"; + public static final String SUBJECT_ID = "urn:oasis:names:tc:xacml:1.0:subject:subject-id"; + public static final String RESOURCE_ID = "urn:oasis:names:tc:xacml:1.0:resource:resource-id"; + public static final String FUNTION_INTEGER_ONE_AND_ONLY = "urn:oasis:names:tc:xacml:1.0:function:integer-one-and-only"; + public static final String FUNCTION_STRING_ONE_AND_ONLY = "urn:oasis:names:tc:xacml:1.0:function:string-one-and-only"; + public static final String FUNCTION_STRING_EQUAL = "urn:oasis:names:tc:xacml:1.0:function:string-equal"; + public static final String FUNCTION_STRING_REGEX_MATCH = "org.onap.function.regex-match"; + public static final String FUNCTION_STRING_EQUAL_IGNORE = "urn:oasis:names:tc:xacml:3.0:function:string-equal-ignore-case"; + public static final String INTEGER_DATATYPE = "http://www.w3.org/2001/XMLSchema#integer"; + public static final String BOOLEAN_DATATYPE = "http://www.w3.org/2001/XMLSchema#boolean"; + public static final String STRING_DATATYPE = "http://www.w3.org/2001/XMLSchema#string"; + public static final String URI_DATATYPE = "http://www.w3.org/2001/XMLSchema#anyURI"; + public static final String RULE_VARIABLE = "var:"; + public static final String EMPTY_STRING = ""; + + private static HtmlProcessor htmlProcessor; + + private static File policyFile; + + private HumanPolicyComponent(){ + //Default Constructor + } + + public static JSONObject DescribePolicy(final File policyFile) { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("ENTER"); + + HumanPolicyComponent.policyFile = policyFile; + return humanPolicyLayout(); + + } + + private static JSONObject humanPolicyLayout() { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("ENTER"); + + try { + String html = processPolicy(); + JSONObject result = new JSONObject(); + result.put("html", html); + return result; + + } catch (IllegalArgumentException e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "cannot build html area por policy", e); + } + return null; + } + + private static String processPolicy() throws IllegalArgumentException { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("ENTER"); + + FileInputStream pIS = null; + try { + pIS = new FileInputStream(policyFile); + Object policy = XACMLPolicyScanner.readPolicy(pIS); + if (policy == null) + throw new IllegalArgumentException("Policy File " + policyFile.getName() + + " cannot be unmarshalled"); + + HumanPolicyComponent.htmlProcessor = + new HtmlProcessor(HumanPolicyComponent.policyFile, policy); + + Path policyPath = Paths.get(policyFile.getAbsolutePath()); + XACMLPolicyScanner xacmlScanner = new XACMLPolicyScanner(policyPath, htmlProcessor); + xacmlScanner.scan(); + String html = htmlProcessor.html(); + if (LOGGER.isDebugEnabled()) + LOGGER.debug(policyPath + System.lineSeparator() + html); + + return html; + + } catch (Exception e) { + String msg = "Exception reading policy: " + policyFile.getAbsolutePath() + + ": " + e.getMessage(); + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + msg, e); + throw new IllegalArgumentException(msg); + } finally { + if (pIS != null) { + try { + pIS.close(); + } catch (IOException e) { + LOGGER.warn(e.getMessage(), e); + } + } + } + } + +} + +class HtmlProcessor extends SimpleCallback { + + private static final Logger LOGGER = FlexLogger.getLogger(HtmlProcessor.class); + + private static Map function2human; + static { + function2human = new HashMap<>(); + function2human.put(HumanPolicyComponent.FUNCTION_STRING_EQUAL, "equal"); + function2human.put(HumanPolicyComponent.FUNCTION_STRING_EQUAL_IGNORE, "equal"); + function2human.put(HumanPolicyComponent.FUNCTION_STRING_ONE_AND_ONLY, "one-and-only"); + function2human.put(HumanPolicyComponent.FUNCTION_STRING_REGEX_MATCH, "matching regular expression"); + function2human.put(HumanPolicyComponent.FUNTION_INTEGER_ONE_AND_ONLY, "one-and-only"); + } + + private static Map combiningAlgo2human; + static { + combiningAlgo2human = new HashMap<>(); + combiningAlgo2human.put("deny-overrides", "to deny if any $placeholder$ below evaluates to deny"); + combiningAlgo2human.put("permit-overrides", "to permit if any $placeholder$ below evaluates to permit"); + + combiningAlgo2human.put("ordered-deny-overrides", "to deny if any $placeholder$ below evaluates to deny"); + combiningAlgo2human.put("ordered-permit-overrides", "to permit if any $placeholder$ below evaluates to permit"); + combiningAlgo2human.put("deny-unless-permit", "to permit if any $placeholder$ below evaluates to deny and not indeterminate"); + + combiningAlgo2human.put("permit-unless-deny", "to deny if any $placeholder$ below evaluates to is permit and not indeterminate"); + combiningAlgo2human.put("first-applicable", "to honour the result of the first successfully evaluated $placeholder$ in order"); + combiningAlgo2human.put("only-one-applicable", "to honour the result of the first successfully evaluated $placeholder$ in order"); + } + + private Map attributeIdentifiersMap = new HashMap(); + + private final StringWriter stringWriter = new StringWriter(); + private final PrintWriter htmlOut = new PrintWriter(stringWriter); + private final String policyName; + private final Object rootPolicyObject; + + public HtmlProcessor(File policyFile, Object policyObject) + throws IllegalArgumentException { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("ENTER"); + + if (policyFile == null) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Null Policy File"); + throw new IllegalArgumentException("Null Policy File"); + } + + if (!policyFile.exists() || !policyFile.canRead()) { + String msg = "Can't access " + policyFile.getAbsolutePath(); + LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + msg); + throw new IllegalArgumentException(msg); + } + + if (policyObject == null || + (!(policyObject instanceof PolicySetType) && !(policyObject instanceof PolicyType))) { + String msg = "Invalid unmarshalled object: " + policyObject; + LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + msg); + throw new IllegalArgumentException(msg); + } + + this.policyName = FilenameUtils.removeExtension(policyFile.getName()); + this.rootPolicyObject = policyObject; + + String version = "-"; + if (policyObject instanceof PolicyType) { + PolicyType policy = (PolicyType) policyObject; + version = policy.getVersion(); + htmlOut.println("

Policy: " + policyName + + " (version " + version + ")

"); + + } else { + PolicySetType policySet = (PolicySetType) policyObject; + version = policySet.getVersion(); + htmlOut.println("

Policy Set: " + policyName + + " (v" + version + ")

"); + } + + htmlOut.println("

Location: " + policyFile.getPath() + "

"); + htmlOut.println("
"); + + if (rootPolicyObject instanceof PolicySetType) { + if (policyName.startsWith("Config_")) { + htmlOut.println("

This is a config policy set.

"); + } else if (policyName.startsWith("Action_")) { + htmlOut.println("

This is an action policy set.

"); + } + htmlOut.println("
"); + } else { + if (policyName.startsWith("Config_")) { + htmlOut.println("

This is a config policy.

"); + } else if (policyName.startsWith("Action_")) { + htmlOut.println("

This is an action policy.

"); + } + htmlOut.println("
    "); + } + } + + /** + * @return the attributeIdentifiersMap + */ + public Map getAttributeIdentifiersMap() { + return attributeIdentifiersMap; + } + + @Override + public void onFinishScan(Object root) { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("ENTER"); + + if (rootPolicyObject instanceof PolicySetType) { + htmlOut.println("
"); + } else { + htmlOut.println(""); + } + + htmlOut.println("
"); + + htmlOut.println("

Attribute Table:

"); + + htmlOut.println(""); + htmlOut.println(""); + htmlOut.print(""); + htmlOut.print(""); + htmlOut.print(""); + htmlOut.println(""); + for(Map.Entry entry : this.attributeIdentifiersMap.entrySet()){ + AttributeIdentifiers value = entry.getValue(); + htmlOut.println(""); + htmlOut.print(""); + htmlOut.print(""); + htmlOut.print(""); + htmlOut.println(""); + } + htmlOut.println("
CategoryTypeIdentifier
" + value.category + "" + value.getType() + "" + value.id + "
"); + + htmlOut.println("

"); + + // Not necessary for the user, uncomment if desired at some point + // writeRawXACML() + + super.onFinishScan(root); + } + + @SuppressWarnings("unused") + private void writeRawXACML() { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("ENTER"); + + htmlOut.println("
"); + htmlOut.println("

Raw XACML:

"); + + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + if (rootPolicyObject instanceof PolicySetType) { + XACMLPolicyWriterWithPapNotify.writePolicyFile(bos, (PolicySetType) rootPolicyObject); + } else if (rootPolicyObject instanceof PolicyType) { + XACMLPolicyWriterWithPapNotify.writePolicyFile(bos, (PolicyType) rootPolicyObject); + } + + String xacml = bos.toString(); + xacml = xacml.replaceAll("<", "<"); + xacml = xacml.replaceAll(">", ">"); + htmlOut.println("
");
+		htmlOut.println(xacml);
+		htmlOut.println("
"); + } + + @Override + public CallbackResult onPreVisitPolicySet(PolicySetType parent, PolicySetType policySet) { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + " Version: " + policySet.getVersion()); + + if (parent != null && LOGGER.isTraceEnabled()) + LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + + "Parent PolicySet: " + parent.getPolicySetId() + " Version: " + parent.getVersion()); + + String description = policySet.getDescription(); + if (description != null && LOGGER.isTraceEnabled()) + LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + + " Description: " + policySet.getDescription()); + + if (parent == null) // root + policySet(policySet, "dl"); + else + policySet(policySet, "li"); + + if (policySet.getPolicySetOrPolicyOrPolicySetIdReference().size() > 0) + htmlOut.println("
    "); + + return super.onPreVisitPolicySet(parent, policySet); + } + + @Override + public CallbackResult onPostVisitPolicySet(PolicySetType parent, PolicySetType policySet) { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + " Version: " + policySet.getVersion()); + + if (parent != null && LOGGER.isTraceEnabled()) + LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + + "Parent PolicySet: " + parent.getPolicySetId() + " Version: " + parent.getVersion()); + + String description = policySet.getDescription(); + if (description != null && LOGGER.isTraceEnabled()) + LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + + " Description: " + policySet.getDescription()); + + if (policySet.getPolicySetOrPolicyOrPolicySetIdReference().size() > 0) + htmlOut.println("
"); + + htmlOut.println("

"); + + return super.onPostVisitPolicySet(parent, policySet); + } + + public void policySet(PolicySetType policySet, String htmlListElement) { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("PolicySet: " + policySet.getPolicySetId()); + + String combiningAlgorithm = "-"; + String id = "-"; + String version = "-"; + + + if (policySet.getPolicyCombiningAlgId() != null) + combiningAlgorithm = extractLastIdentifier(policySet.getPolicyCombiningAlgId(), ":"); + + if (policySet.getPolicySetId() != null) + id = extractLastIdentifier(policySet.getPolicySetId(), ":"); + + if (policySet.getVersion() != null) + version = policySet.getVersion(); + + + htmlOut.println("<" + htmlListElement + ">Policy Set ID: " + id + + " (v" + version + ") " + ""); + + if (policySet.getTarget() == null || + policySet.getTarget().getAnyOf() == null || + policySet.getTarget().getAnyOf().size() <= 0) { + htmlOut.println("

This policy set applies to all requests.

"); + } else { + htmlOut.print("

"); + htmlOut.print("This policy set applies to requests with attributes "); + + List anyOf_s = policySet.getTarget().getAnyOf(); + target(anyOf_s); + htmlOut.println(".

"); + } + + if (policySet.getPolicySetOrPolicyOrPolicySetIdReference() != null && + policySet.getPolicySetOrPolicyOrPolicySetIdReference().size() > 0) { + String algoDesc = combiningAlgo2human.get(combiningAlgorithm); + if (algoDesc != null) { + algoDesc = algoDesc.replace("$placeholder$", "policy") + " (" + "" + combiningAlgorithm + ")"; + } else { + algoDesc = combiningAlgorithm; + } + + htmlOut.println("

The result is " + algoDesc + ":

"); + } + } + + @Override + public CallbackResult onPreVisitPolicy(PolicySetType parent, PolicyType policy) { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("PolicySet: " + policy.getPolicyId() + " Version: " + policy.getVersion()); + + if (parent != null && LOGGER.isTraceEnabled()) + LOGGER.trace("PolicySet: " + policy.getPolicyId() + + "Parent PolicySet: " + parent.getPolicySetId() + " Version: " + parent.getVersion()); + + String description = policy.getDescription(); + if (description != null && LOGGER.isTraceEnabled()) + LOGGER.trace("PolicySet: " + policy.getPolicyId() + + " Description: " + policy.getDescription()); + + policy(policy); + + if (policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().size() > 0) + htmlOut.println("
    "); + + return super.onPreVisitPolicy(parent, policy); + } + + @Override + public CallbackResult onPostVisitPolicy(PolicySetType parent, PolicyType policy) { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("PolicySet: " + policy.getPolicyId() + " Version: " + policy.getVersion()); + + if (parent != null && LOGGER.isTraceEnabled()) + LOGGER.trace("PolicySet: " + policy.getPolicyId() + + "Parent PolicySet: " + parent.getPolicySetId() + " Version: " + parent.getVersion()); + + if (policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().size() > 0) + htmlOut.println("
"); + + htmlOut.println("

"); + return super.onPostVisitPolicy(parent, policy); + } + + public void policy(PolicyType policy) { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("Policy: " + policy.getPolicyId()); + + String combiningAlgorithm = "-"; + String id = "-"; + String version = "-"; + + + if (policy.getRuleCombiningAlgId() != null) + combiningAlgorithm = extractLastIdentifier(policy.getRuleCombiningAlgId(), ":"); + + if (policy.getPolicyId() != null) + id = extractLastIdentifier(policy.getPolicyId(), ":"); + + if (policy.getVersion() != null) + version = policy.getVersion(); + + htmlOut.println("
  • Policy ID: " + id + + " (v" + version + ") " + "
  • "); + + if (policy.getTarget() == null || + policy.getTarget().getAnyOf() == null || + policy.getTarget().getAnyOf().size() <= 0) { + htmlOut.println("

    This policy applies to all requests.

    "); + } else { + htmlOut.print("

    "); + htmlOut.print("This policy applies to requests with attributes "); + + List anyOf_s = policy.getTarget().getAnyOf(); + target(anyOf_s); + htmlOut.println(".

    "); + } + + if (policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition() != null && + policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().size() > 0) { + String algoDesc = combiningAlgo2human.get(combiningAlgorithm); + if (algoDesc != null) { + algoDesc = algoDesc.replace("$placeholder$", "rule") + " (" + combiningAlgorithm + ")"; + } else { + algoDesc = combiningAlgorithm; + } + htmlOut.println("

    The result is " + algoDesc + ":

    "); + } + } + + + @Override + public CallbackResult onPreVisitRule(PolicyType parent, RuleType rule) { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("Rule: " + rule.getRuleId()); + + if (parent != null && LOGGER.isTraceEnabled()) + LOGGER.trace("Parent Policy: " + parent.getPolicyId() + " Version: " + parent.getVersion()); + + String description = rule.getDescription(); + if (description != null && LOGGER.isTraceEnabled()) { + LOGGER.trace("Rule: " + rule.getRuleId() + + " Description: " + rule.getDescription()); + } + + rule(rule); + + return super.onPreVisitRule(parent, rule); + } + + @Override + public CallbackResult onPostVisitRule(PolicyType parent, RuleType rule) { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("Rule: " + rule.getRuleId()); + + if (parent != null && LOGGER.isTraceEnabled()) + LOGGER.trace("Parent Policy: " + parent.getPolicyId() + " Version: " + parent.getVersion()); + + return super.onPostVisitRule(parent, rule); + } + + public void rule(RuleType rule) { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("Rule: " + rule.getRuleId()); + + String id = "-"; + + if (rule.getRuleId() != null) + id = extractLastIdentifier(rule.getRuleId(), ":"); + + htmlOut.println("
  • Rule ID: " + id + "
  • "); + + htmlOut.println("
    "); + + htmlOut.print("

    "); + htmlOut.print(rule.getEffect().value()); + + if (rule.getTarget() == null || + rule.getTarget().getAnyOf() == null || + rule.getTarget().getAnyOf().size() <= 0) { + htmlOut.print(" for all requests"); + } else { + List anyOf_s = rule.getTarget().getAnyOf(); + htmlOut.print(" for requests with attributes "); + target(anyOf_s); + } + + if (rule.getCondition() != null) { + htmlOut.print(" when "); + htmlOut.println(this.stringifyCondition(rule.getCondition()) + " "); + } else { + htmlOut.print(" with no conditions "); + } + + if (rule.getAdviceExpressions() != null) { + advice(rule.getAdviceExpressions()); + if (rule.getObligationExpressions() != null) + htmlOut.println(" and "); + } + + if (rule.getObligationExpressions() != null) { + obligation(rule.getObligationExpressions()); + } + + htmlOut.println("

    "); + } + + private void advice(AdviceExpressionsType adviceExpressions) { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("ENTER"); + + List ae = adviceExpressions.getAdviceExpression(); + for (AdviceExpressionType expression : ae) { + htmlOut.println(" with advice (" + expression.getAdviceId() + ") on " + + expression.getAppliesTo().value() + ":" ); + htmlOut.println("
      "); + List assignments = expression.getAttributeAssignmentExpression(); + if (assignments != null) { + processAttributeAssignments(assignments); + } + htmlOut.println("
    "); + } + } + + private void obligation(ObligationExpressionsType obligationExpressions) { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("ENTER"); + + List oe = obligationExpressions.getObligationExpression(); + for (ObligationExpressionType expression : oe) { + htmlOut.println(" with obligations (" + expression.getObligationId() + ") to be fullfilled on " + + expression.getFulfillOn().value() + ":" ); + htmlOut.println("
      "); + List assignments = expression.getAttributeAssignmentExpression(); + if (assignments != null) { + processAttributeAssignments(assignments); + } + htmlOut.println("
    "); + } + } + + /** + * @param assignments + */ + private void processAttributeAssignments(List assignments) { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("ENTER"); + + for (AttributeAssignmentExpressionType assignment : assignments) { + String succintIdentifier = extractLastIdentifier(assignment.getCategory(), ":") + + ":" + extractLastIdentifier(assignment.getAttributeId(), ":"); + AttributeIdentifiers attributeIdentifiers = null; + if (!this.attributeIdentifiersMap.containsKey(succintIdentifier)) { + // Note Attribute Assignments do not have an Attribute Type, assume string + // but note this case is unlikely since attributeMap should have been populated + // during parsing of target and conditions, and not in this case for Advice and + // Obligations. + attributeIdentifiers = new AttributeIdentifiers(assignment.getCategory(), + "NA", + assignment.getAttributeId()); + this.attributeIdentifiersMap.put(succintIdentifier, attributeIdentifiers); + } + + htmlOut.print("
  • " + succintIdentifier + " is "); + // AttributeValueType + JAXBElement jaxbExp = assignment.getExpression(); + Object assignmentObject = jaxbExp.getValue(); + if (assignmentObject instanceof AttributeValueType) { + AttributeValueType avt = (AttributeValueType) assignmentObject; + if (attributeIdentifiers != null) { + attributeIdentifiers.setType(avt.getDataType()); + } + int numContent = avt.getContent().size(); + int countContent = 0; + for (Object c: avt.getContent()) { + countContent++; + htmlOut.print("" + c + ""); + if (countContent < numContent) + htmlOut.print(" or "); + } + htmlOut.println("
  • "); + } else if (assignmentObject instanceof AttributeDesignatorType) { + htmlOut.println("NA"); + } else if (assignmentObject instanceof AttributeSelectorType) { + htmlOut.println("NA"); + } else if (assignmentObject instanceof ApplyType) { + htmlOut.println("NA"); + } else { + htmlOut.println("Unexpected"); + } + } + } + + /** + * + * @param anyOfList + */ + public void target(List anyOfList) { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("ENTER"); + + if (anyOfList != null) { + Iterator iterAnyOf = anyOfList.iterator(); + String targetInHuman = ""; + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + List allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator iterAllOf = allOfList.iterator(); + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + List matchList = allOf.getMatch(); + if (matchList != null) { + Iterator iterMatch = matchList.iterator(); + if (matchList.size() > 1) + targetInHuman += "("; + while (iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Finally down to the actual attribute + // + StdAttribute attribute = null; + AttributeValueType value = match.getAttributeValue(); + String attributeDataType = null; + if (match.getAttributeDesignator() != null && value != null) { + AttributeDesignatorType designator = match.getAttributeDesignator(); + attribute = new StdAttribute(new IdentifierImpl(designator.getCategory()), + new IdentifierImpl(designator.getAttributeId()), + new StdAttributeValue>(new IdentifierImpl(value.getDataType()), value.getContent()), + designator.getIssuer(), + false); + attributeDataType = designator.getDataType(); + } else if (match.getAttributeSelector() != null && value != null) { + AttributeSelectorType selector = match.getAttributeSelector(); + attribute = new StdAttribute(new IdentifierImpl(selector.getCategory()), + new IdentifierImpl(selector.getContextSelectorId()), + new StdAttributeValue>(new IdentifierImpl(value.getDataType()), value.getContent()), + null, + false); + attributeDataType = selector.getDataType(); + } else { + LOGGER.warn("NULL designator/selector or value for match."); + attributeDataType = "NA"; + } + + String functionName = getHumanFunction(match.getMatchId()); + if(attribute != null){ + String succintIdentifier = extractLastIdentifier(attribute.getCategory().stringValue(), ":") + + ":" + extractLastIdentifier(attribute.getAttributeId().stringValue(), ":"); + AttributeIdentifiers ai = new AttributeIdentifiers(attribute.getCategory().stringValue(), + attributeDataType, + attribute.getAttributeId().stringValue()); + this.attributeIdentifiersMap.put(succintIdentifier,ai); + + targetInHuman += "" + succintIdentifier + " " + functionName + " "; + + int numAttributes = attribute.getValues().size(); + int count = 0; + for (AttributeValue v: attribute.getValues()) { + count++; + if (v.getValue() instanceof Collection) { + Collection value_s = (Collection) v.getValue(); + int numValues = value_s.size(); + int countValues = 0; + for (Object o : value_s) { + countValues++; + targetInHuman += " " + o + ""; + if (countValues < numValues) { + targetInHuman += ", or"; + } + } + } else { + targetInHuman += " " + v.getValue() + ""; + if (count < numAttributes) { + targetInHuman += ", or "; + } + } + } + } + + if (iterMatch.hasNext()) { + targetInHuman += " and "; + } + } // end iterMatch + if (matchList.size() > 1) { + targetInHuman += ")"; + } + } + if (iterAllOf.hasNext()) { + targetInHuman += " or "; + } + } // end iterAllOf + } + if (iterAnyOf.hasNext()) { + targetInHuman = "(" + targetInHuman + ")" + " or "; + } else { + if (anyOfList.size() > 1) { + targetInHuman += ")"; + } + } + } // end iterAnyOf + htmlOut.println(targetInHuman); + } + } + + private String getHumanFunction(String matchId) { + if (HtmlProcessor.function2human.containsKey(matchId)) { + return HtmlProcessor.function2human.get(matchId); + } + + FunctionDefinition function = PolicyController.getFunctionIDMap().get(matchId); + String functionName = function.getShortname(); + + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(functionName + + ": #args[" + function.getArgLb() + "," + function.getArgUb() +"]"); + } + + return extractLastIdentifier(removePrimitives(functionName), ":"); + } + + public String html() { + this.htmlOut.flush(); + return this.stringWriter.toString(); + } + + private String extractLastIdentifier(String in, String separator) { + int lastIndex = in.lastIndexOf(separator); + if (lastIndex < 0) + return in; + else + return in.substring(lastIndex+1); + } + + private String removePrimitives(String in) { + in = in.replace("string-", ""); + in = in.replace("integer-", ""); + in = in.replace("double-", ""); + in = in.replace("boolean-", ""); + return in; + } + + private String stringifyCondition(ConditionType condition) { + if (condition.getExpression() == null) { + return ""; + } + + return stringifyExpression(condition.getExpression().getValue()); + } + + private String stringifyExpression(Object expression) { + if (expression instanceof ApplyType) { + ApplyType apply = (ApplyType) expression; + FunctionDefinition function = PolicyController.getFunctionIDMap().get(apply.getFunctionId()); + String functionName = function.getShortname(); + + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(functionName + + ": #args[" + function.getArgLb() + "," + function.getArgUb() +"]"); + } + + if (functionName.contains("one-and-only")) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("one-and-only found: " + functionName); + } + + List> exps = apply.getExpression(); + if (exps == null || exps.size() == 0) + return ""; + else { + String forResult = ""; + for (JAXBElement e : exps) { + Object v = e.getValue(); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("one-and-only children: " + v); + } + if (v != null) { + // C: return stringifyExpression(v, result); + forResult += stringifyExpression(v); + } + } + return forResult; + } + } + + final int numExpr = (apply.getExpression() == null) ? -1 : apply.getExpression().size(); + if (numExpr <= 0) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(functionName + " 0 expressions: " + numExpr); + } + return ""; + } else if (numExpr == 1) { + // eg: not + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(functionName + " 1 expression: " + numExpr); + } + String applySubresult = ""; + for (JAXBElement e : apply.getExpression()) { + Object v = e.getValue(); + if (v != null) { + applySubresult += this.stringifyExpression(e.getValue()); + } + } + return " " + removePrimitives(functionName) + " (" + applySubresult + ")"; + } else { + // > 1 arguments + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(functionName + " > 1 expressions: " + numExpr); + } + String applySubresult = ""; + int exprCount = 0; + for (JAXBElement e : apply.getExpression()) { + exprCount++; + Object ev = e.getValue(); + if (ev != null) { + if (ev instanceof ApplyType) { + if (((ApplyType) ev).getFunctionId().contains("one-and-only")) { + applySubresult += this.stringifyExpression(e.getValue()); + } else { + applySubresult += "(" + this.stringifyExpression(e.getValue()) + ")"; + } + } else { + applySubresult += this.stringifyExpression(e.getValue()); + } + + if (exprCount < numExpr) { + applySubresult += " " + removePrimitives(functionName) + " "; + } + } + } + return applySubresult; + } + } + if (expression instanceof AttributeDesignatorType) { + AttributeDesignatorType adt = (AttributeDesignatorType) expression; + + String succintIdentifier = extractLastIdentifier(adt.getCategory(), ":") + + ":" + extractLastIdentifier(adt.getAttributeId(), ":"); + AttributeIdentifiers ai = new AttributeIdentifiers(adt.getCategory(), + adt.getDataType(), + adt.getAttributeId()); + this.attributeIdentifiersMap.put(succintIdentifier,ai); + + return "" + succintIdentifier + ""; + } + if (expression instanceof AttributeSelectorType) { + AttributeSelectorType ast = (AttributeSelectorType) expression; + + String attrName = ast.getPath(); + if (attrName == null || (attrName.length() == 0)) { + return ""; + } + + String textSelector = "/text()"; + if (attrName.endsWith(textSelector)) { + attrName = attrName.substring(0, attrName.length() - textSelector.length()); + } + + attrName = extractLastIdentifier(attrName, "/"); + attrName = extractLastIdentifier(attrName, ":"); + return " " + attrName; + } + if (expression instanceof AttributeValueType) { + AttributeValueType avt = (AttributeValueType) expression; + List content = avt.getContent(); + String value_s = ""; + for (Object o: content) { + value_s += " " + o.toString(); + } + return " " + value_s; + } + if (expression instanceof VariableReferenceType) { + // + // Really unknown - the variable may or may not have been defined + // + return " VARIABLEREF-NOT-HANDLED"; + } else { + throw new IllegalArgumentException("Unexpected input expression"); + } + } +} + + +class AttributeIdentifiers { + public final String category; + private String type; + public final String id; + + public AttributeIdentifiers(String category, String type, String id) { + this.category = category; + this.setType(type); + this.id = id; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/conf/HibernateSession.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/conf/HibernateSession.java new file mode 100644 index 000000000..d70f199f0 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/conf/HibernateSession.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.conf; + +/* + * + * + * */ +import java.util.Properties; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.controller.PolicyController; +import org.onap.policy.rest.jpa.SystemLogDB; + +@SuppressWarnings("deprecation") +public class HibernateSession{ + + private static final Logger LOGGER = FlexLogger.getLogger(HibernateSession.class); + + private static SessionFactory logSessionFactory; + + static { + try { + Properties prop= new Properties(); + prop.setProperty("hibernate.connection.url", PolicyController.getLogdbUrl()); + prop.setProperty("hibernate.connection.username", PolicyController.getLogdbUserName()); + prop.setProperty("hibernate.connection.password", PolicyController.getLogdbPassword()); + prop.setProperty("dialect", PolicyController.getLogdbDialect()); + prop.setProperty("hibernate.connection.driver_class", PolicyController.getLogdbDriver()); + prop.setProperty("show_sql", "false"); + logSessionFactory = new Configuration().addPackage("org.onap.policy.*").addProperties(prop) + .addAnnotatedClass(SystemLogDB.class).buildSessionFactory(); + } catch (Exception ex) { + LOGGER.error("Exception Occured while creating Log database Hibernate session"+ex); + } + } + public static Session getSession(){ + return logSessionFactory.openSession(); + } + +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java new file mode 100644 index 000000000..0a985045d --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java @@ -0,0 +1,268 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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 java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import javax.xml.bind.JAXBElement; + +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.jpa.PolicyEntity; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + +@Controller +@RequestMapping({"/"}) +public class ActionPolicyController extends RestrictedBaseController{ + private static final Logger LOGGER = FlexLogger.getLogger(ActionPolicyController.class); + + public ActionPolicyController(){ + //Default Constructor + } + + private ArrayList attributeList; + protected LinkedList ruleAlgoirthmTracker; + public static final String PERFORMER_ATTRIBUTEID = "performer"; + protected Map performer = new HashMap<>(); + private ArrayList ruleAlgorithmList; + + public void prePopulateActionPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + attributeList = new ArrayList<>(); + ruleAlgorithmList = new ArrayList<>(); + performer.put("PDP", "PDPAction"); + performer.put("PEP", "PEPAction"); + + if (policyAdapter.getPolicyData() instanceof PolicyType) { + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("_") + 1); + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try{ + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + }catch(Exception e){ + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + // Get the target data under policy for Action. + TargetType target = policy.getTarget(); + if (target != null) { + // under target we have AnyOFType + List anyOfList = target.getAnyOf(); + if (anyOfList != null) { + Iterator iterAnyOf = anyOfList.iterator(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + // Under AntOfType we have AllOfType + List allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator iterAllOf = allOfList.iterator(); + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + // Under AllOfType we have Mathch. + List matchList = allOf.getMatch(); + if (matchList != null) { + Iterator iterMatch = matchList.iterator(); + while (iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attributevalue and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + // Component attributes are saved under Target here we are fetching them back. + // One row is default so we are not adding dynamic component at index 0. + Map attribute = new HashMap<>(); + attribute.put("key", attributeId); + attribute.put("value", value); + attributeList.add(attribute); + } + } + policyAdapter.setAttributes(attributeList); + } + } + } + } + + List ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); + // Under rule we have Condition and obligation. + for (Object o : ruleList) { + if (o instanceof RuleType) { + ConditionType condition = ((RuleType) o).getCondition(); + ObligationExpressionsType obligations = ((RuleType) o).getObligationExpressions(); + if (condition != null) { + int index = 0; + ApplyType actionApply = (ApplyType) condition.getExpression().getValue(); + ruleAlgoirthmTracker = new LinkedList<>(); + // Populating Rule Algorithms starting from compound. + prePopulateCompoundRuleAlgorithm(index, actionApply); + } + policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList); + // get the Obligation data under the rule for Form elements. + if (obligations != null) { + // Under the obligationExpressions we have obligationExpression. + List obligationList = obligations.getObligationExpression(); + if (obligationList != null) { + Iterator iterObligation = obligationList.iterator(); + while (iterObligation.hasNext()) { + ObligationExpressionType obligation = iterObligation.next(); + policyAdapter.setActionAttributeValue(obligation.getObligationId()); + // Under the obligationExpression we have attributeAssignmentExpression. + List attributeAssignmentExpressionList = obligation.getAttributeAssignmentExpression(); + if (attributeAssignmentExpressionList != null) { + Iterator iterAttributeAssignmentExpression = attributeAssignmentExpressionList.iterator(); + while (iterAttributeAssignmentExpression.hasNext()) { + AttributeAssignmentExpressionType attributeAssignmentExpression = iterAttributeAssignmentExpression.next(); + String attributeID = attributeAssignmentExpression.getAttributeId(); + AttributeValueType attributeValue = (AttributeValueType) attributeAssignmentExpression.getExpression().getValue(); + if (attributeID.equals(PERFORMER_ATTRIBUTEID)) { + for (String key : performer.keySet()) { + String keyValue = performer.get(key); + if (keyValue.equals(attributeValue.getContent().get(0))) { + policyAdapter.setActionPerformer(key); + } + } + } + } + } + } + } + } + } + } + } + } + } + + private int prePopulateCompoundRuleAlgorithm(int index, ApplyType actionApply) { + boolean isCompoundRule = true; + List> jaxbActionTypes = actionApply.getExpression(); + for (JAXBElement jaxbElement : jaxbActionTypes) { + // If There is Attribute Value under Action Type that means we came to the final child + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Prepopulating rule algoirthm: " + index); + } + // Check to see if Attribute Value exists, if yes then it is not a compound rule + if (jaxbElement.getValue() instanceof AttributeValueType) { + prePopulateRuleAlgorithms(index, actionApply, jaxbActionTypes); + ruleAlgoirthmTracker.addLast(index); + isCompoundRule = false; + index++; + } + } + if (isCompoundRule) { + // As it's compound rule, Get the Apply types + for (JAXBElement jaxbElement : jaxbActionTypes) { + ApplyType innerActionApply = (ApplyType) jaxbElement.getValue(); + index = prePopulateCompoundRuleAlgorithm(index, innerActionApply); + } + // Populate combo box + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Prepopulating Compound rule algorithm: " + index); + } + Map rule = new HashMap(); + for (String key : PolicyController.getDropDownMap().keySet()) { + String keyValue = PolicyController.getDropDownMap().get(key); + if (keyValue.equals(actionApply.getFunctionId())) { + rule.put("dynamicRuleAlgorithmCombo", key); + } + } + rule.put("id", "A" + (index +1)); + // Populate Key and values for Compound Rule + rule.put("dynamicRuleAlgorithmField1", "A" + (ruleAlgoirthmTracker.getLast() + 1 )); + ruleAlgoirthmTracker.removeLast(); + rule.put("dynamicRuleAlgorithmField2", "A" + (ruleAlgoirthmTracker.getLast() + 1)); + ruleAlgoirthmTracker.removeLast(); + ruleAlgoirthmTracker.addLast(index); + ruleAlgorithmList.add(rule); + index++; + } + return index; + } + + private void prePopulateRuleAlgorithms(int index, ApplyType actionApply, List> jaxbActionTypes) { + Map ruleMap = new HashMap(); + ruleMap.put("id", "A" + (index +1)); + // Populate combo box + Map dropDownMap = PolicyController.getDropDownMap(); + for (String key : dropDownMap.keySet()) { + String keyValue = dropDownMap.get(key); + if (keyValue.equals(actionApply.getFunctionId())) { + ruleMap.put("dynamicRuleAlgorithmCombo", key); + } + } + // Populate the key and value fields + // Rule Attribute added as key + if ((jaxbActionTypes.get(0).getValue()) instanceof ApplyType) { + // Get from Attribute Designator + ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(0).getValue(); + List> jaxbInnerActionTypes = innerActionApply.getExpression(); + AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerActionTypes.get(0).getValue(); + ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId()); + + // Get from Attribute Value + AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbActionTypes.get(1).getValue(); + String attributeValue = (String) actionConditionAttributeValue.getContent().get(0); + ruleMap.put("dynamicRuleAlgorithmField2", attributeValue); + } + // Rule Attribute added as value + else if (((jaxbActionTypes.get(0).getValue()) instanceof AttributeValueType)) { + AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbActionTypes.get(0).getValue(); + String attributeValue = (String) actionConditionAttributeValue.getContent().get(0); + ruleMap.put("dynamicRuleAlgorithmField2", attributeValue); + + ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(1).getValue(); + List> jaxbInnerActionTypes = innerActionApply.getExpression(); + AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerActionTypes.get(0).getValue(); + ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId()); + } + ruleAlgorithmList.add(ruleMap); + } + +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java new file mode 100644 index 000000000..820a1ebd9 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java @@ -0,0 +1,119 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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 java.io.PrintWriter; +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.GlobalRoleSettings; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +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.servlet.ModelAndView; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Controller +@RequestMapping({"/"}) +public class AdminTabController extends RestrictedBaseController{ + + private static final Logger LOGGER = FlexLogger.getLogger(AdminTabController.class); + + private static CommonClassDao commonClassDao; + + public static CommonClassDao getCommonClassDao() { + return commonClassDao; + } + + public static void setCommonClassDao(CommonClassDao commonClassDao) { + AdminTabController.commonClassDao = commonClassDao; + } + + @Autowired + private AdminTabController(CommonClassDao commonClassDao){ + AdminTabController.commonClassDao = commonClassDao; + } + + public AdminTabController() { + //default constructor + } + + @RequestMapping(value={"/get_LockDownData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getAdminTabEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("lockdowndata", mapper.writeValueAsString(commonClassDao.getData(GlobalRoleSettings.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error("Exception Occured"+e); + } + } + + @RequestMapping(value={"/adminTabController/save_LockDownValue.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveAdminTabLockdownValue(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + GlobalRoleSettings globalRole = mapper.readValue(root.get("lockdowndata").toString(), GlobalRoleSettings.class); + globalRole.setRole("super-admin"); + commonClassDao.update(globalRole); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(commonClassDao.getData(GlobalRoleSettings.class)); + JSONObject j = new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString + "}"); + + out.write(j.toString()); + + return null; + } + catch (Exception e){ + LOGGER.error("Exception Occured"+e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java new file mode 100644 index 000000000..f78a79c9c --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java @@ -0,0 +1,377 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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 java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.net.URI; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +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.PDPPolicyContainer; +import org.onap.policy.model.Roles; +import org.onap.policy.rest.adapter.AutoPushTabAdapter; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.PolicyEntity; +import org.onap.policy.rest.jpa.PolicyVersion; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.api.pap.OnapPDPGroup; +import org.onap.policy.xacml.std.pap.StdPDPGroup; +import org.onap.policy.xacml.std.pap.StdPDPPolicy; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.openecomp.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.servlet.ModelAndView; + +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.api.pap.PDPPolicy; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + + +@Controller +@RequestMapping({"/"}) +public class AutoPushController extends RestrictedBaseController{ + + private static final Logger logger = FlexLogger.getLogger(AutoPushController.class); + + @Autowired + CommonClassDao commonClassDao; + + private PDPGroupContainer container; + protected List groups = Collections.synchronizedList(new ArrayList()); + + private PDPPolicyContainer policyContainer; + + private PolicyController policyController; + public PolicyController getPolicyController() { + return policyController; + } + + public void setPolicyController(PolicyController policyController) { + this.policyController = policyController; + } + + private List data; + + public synchronized void refreshGroups() { + synchronized(this.groups) { + this.groups.clear(); + try { + PolicyController controller = getPolicyControllerInstance(); + this.groups.addAll(controller.getPapEngine().getOnapPDPGroups()); + } catch (PAPException e) { + String message = "Unable to retrieve Groups from server: " + e; + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message); + } + + } + } + + private PolicyController getPolicyControllerInstance(){ + return policyController != null ? getPolicyController() : new PolicyController(); + } + + @RequestMapping(value={"/get_AutoPushPoliciesContainerData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response){ + try{ + Set scopes = null; + List roles = null; + data = new ArrayList(); + String userId = UserUtils.getUserSession(request).getOrgUserId(); + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + PolicyController controller = policyController != null ? getPolicyController() : new PolicyController(); + List userRoles = controller.getRoles(userId); + roles = new ArrayList<>(); + scopes = new HashSet<>(); + for(Object role: userRoles){ + Roles userRole = (Roles) role; + roles.add(userRole.getRole()); + if(userRole.getScope() != null){ + if(userRole.getScope().contains(",")){ + String[] multipleScopes = userRole.getScope().split(","); + for(int i =0; i < multipleScopes.length; i++){ + scopes.add(multipleScopes[i]); + } + }else{ + if(!userRole.getScope().equals("")){ + scopes.add(userRole.getScope()); + } + } + } + } + if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest")) { + data = commonClassDao.getData(PolicyVersion.class); + }else{ + if(!scopes.isEmpty()){ + for(String scope : scopes){ + String query = "From PolicyVersion where policy_name like '"+scope+"%' and id > 0"; + List filterdatas = commonClassDao.getDataByQuery(query); + if(filterdatas != null){ + for(int i =0; i < filterdatas.size(); i++){ + data.add(filterdatas.get(i)); + } + } + } + }else{ + PolicyVersion emptyPolicyName = new PolicyVersion(); + emptyPolicyName.setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you"); + data.add(emptyPolicyName); + } + } + model.put("policydatas", mapper.writeValueAsString(data)); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + logger.error("Exception Occured"+e); + } + } + + @RequestMapping(value={"/auto_Push/PushPolicyToPDP.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView PushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception { + try { + ArrayList selectedPDPS = new ArrayList<>(); + ArrayList selectedPoliciesInUI = new ArrayList<>(); + PolicyController controller = getPolicyControllerInstance(); + this.groups.addAll(controller.getPapEngine().getOnapPDPGroups()); + ObjectMapper mapper = new ObjectMapper(); + this.container = new PDPGroupContainer(controller.getPapEngine()); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + AutoPushTabAdapter adapter = mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class); + for (Object pdpGroupId : adapter.getPdpDatas()) { + LinkedHashMap selectedPDP = (LinkedHashMap)pdpGroupId; + for(OnapPDPGroup pdpGroup : this.groups){ + if(pdpGroup.getId().equals(selectedPDP.get("id"))){ + selectedPDPS.add(pdpGroup); + } + } + } + + for (Object policyId : adapter.getPolicyDatas()) { + LinkedHashMap selected = (LinkedHashMap)policyId; + String policyName = selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml"; + selectedPoliciesInUI.add(policyName); + } + + for (Object pdpDestinationGroupId : selectedPDPS) { + Set currentPoliciesInGroup = new HashSet<>(); + Set selectedPolicies = new HashSet<>(); + for (String policyId : selectedPoliciesInUI) { + logger.debug("Handlepolicies..." + pdpDestinationGroupId + policyId); + + // + // Get the current selection + String selectedItem = policyId; + // + assert (selectedItem != null); + // create the id of the target file + // Our standard for file naming is: + // ...xml + // since the file name usually has a ".xml", we need to strip + // that + // before adding the other parts + String name = selectedItem.replace(File.separator, "."); + String id = name; + if (id.endsWith(".xml")) { + id = id.replace(".xml", ""); + id = id.substring(0, id.lastIndexOf(".")); + } + + // Default policy to be Root policy; user can change to deferred + // later + + StdPDPPolicy selectedPolicy = null; + String dbCheckName = name; + if(dbCheckName.contains("Config_")){ + dbCheckName = dbCheckName.replace(".Config_", ":Config_"); + }else if(dbCheckName.contains("Action_")){ + dbCheckName = dbCheckName.replace(".Action_", ":Action_"); + }else if(dbCheckName.contains("Decision_")){ + dbCheckName = dbCheckName.replace(".Decision_", ":Decision_"); + } + String[] split = dbCheckName.split(":"); + String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'"; + List queryData = controller.getDataByQuery(query); + PolicyEntity policyEntity = (PolicyEntity) queryData.get(0); + File temp = new File(name); + BufferedWriter bw = new BufferedWriter(new FileWriter(temp)); + bw.write(policyEntity.getPolicyData()); + bw.close(); + URI selectedURI = temp.toURI(); + try { + // + // Create the policy + selectedPolicy = new StdPDPPolicy(name, true, id, selectedURI); + } catch (IOException e) { + logger.error("Unable to create policy '" + name + "': "+ e.getMessage()); + } + StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId; + if (selectedPolicy != null) { + // Add Current policies from container + for (OnapPDPGroup group : container.getGroups()) { + if (group.getId().equals(selectedGroup.getId())) { + currentPoliciesInGroup.addAll(group.getPolicies()); + } + } + // copy policy to PAP + try { + controller.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId); + } catch (PAPException e) { + logger.error("Exception Occured"+e); + return null; + } + selectedPolicies.add(selectedPolicy); + } + temp.delete(); + } + StdPDPGroup pdpGroup = (StdPDPGroup) pdpDestinationGroupId; + StdPDPGroup updatedGroupObject = new StdPDPGroup(pdpGroup.getId(), pdpGroup.isDefaultGroup(), pdpGroup.getName(), pdpGroup.getDescription(), pdpGroup.getDirectory()); + updatedGroupObject.setOnapPdps(pdpGroup.getOnapPdps()); + updatedGroupObject.setPipConfigs(pdpGroup.getPipConfigs()); + updatedGroupObject.setStatus(pdpGroup.getStatus()); + + // replace the original set of Policies with the set from the + // container (possibly modified by the user) + // do not allow multiple copies of same policy + Iterator policyIterator = currentPoliciesInGroup.iterator(); + logger.debug("policyIterator....." + selectedPolicies); + while (policyIterator.hasNext()) { + PDPPolicy existingPolicy = policyIterator.next(); + for (PDPPolicy selPolicy : selectedPolicies) { + if (selPolicy.getName().equals(existingPolicy.getName())) { + if (selPolicy.getVersion().equals(existingPolicy.getVersion())) { + if (selPolicy.getId().equals(existingPolicy.getId())) { + policyIterator.remove(); + logger.debug("Removing policy: " + selPolicy); + break; + } + } else { + policyIterator.remove(); + logger.debug("Removing Old Policy version: "+ selPolicy); + break; + } + } + } + } + + currentPoliciesInGroup.addAll(selectedPolicies); + updatedGroupObject.setPolicies(currentPoliciesInGroup); + this.container.updateGroup(updatedGroupObject); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + refreshGroups(); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); + JSONObject j = new JSONObject(msg); + out.write(j.toString()); + return null; + } + } + catch (Exception e){ + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @SuppressWarnings("unchecked") + @RequestMapping(value={"/auto_Push/remove_GroupPolicies.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception { + try { + PolicyController controller = getPolicyControllerInstance(); + this.container = new PDPGroupContainer(controller.getPapEngine()); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + StdPDPGroup group = (StdPDPGroup)mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class); + JsonNode removePolicyData = root.get("data"); + policyContainer = new PDPPolicyContainer(group); + if(removePolicyData.size() > 0){ + for(int i = 0 ; i < removePolicyData.size(); i++){ + String data = removePolicyData.get(i).toString(); + this.policyContainer.removeItem(data); + } + Set changedPolicies = new HashSet<>(); + changedPolicies.addAll((Collection) this.policyContainer.getItemIds()); + StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(), group.getDescription(),null); + updatedGroupObject.setPolicies(changedPolicies); + updatedGroupObject.setOnapPdps(group.getOnapPdps()); + updatedGroupObject.setPipConfigs(group.getPipConfigs()); + updatedGroupObject.setStatus(group.getStatus()); + this.container.updateGroup(updatedGroupObject); + } + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + refreshGroups(); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); + JSONObject j = new JSONObject(msg); + + out.write(j.toString()); + + return null; + } + catch (Exception e){ + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + +} \ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java new file mode 100644 index 000000000..3107950c9 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java @@ -0,0 +1,551 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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 java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.PrintWriter; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.bind.JAXBElement; + +import org.json.JSONObject; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.BRMSParamTemplate; +import org.onap.policy.rest.jpa.PolicyEntity; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + +@Controller +@RequestMapping("/") +public class CreateBRMSParamController extends RestrictedBaseController { + private static final Logger policyLogger = FlexLogger.getLogger(CreateBRMSParamController.class); + + private static CommonClassDao commonClassDao; + + public static CommonClassDao getCommonClassDao() { + return commonClassDao; + } + + public static void setCommonClassDao(CommonClassDao commonClassDao) { + CreateBRMSParamController.commonClassDao = commonClassDao; + } + + @Autowired + private CreateBRMSParamController(CommonClassDao commonClassDao){ + CreateBRMSParamController.commonClassDao = commonClassDao; + } + + public CreateBRMSParamController(){} + protected PolicyRestAdapter policyAdapter = null; + + private HashMap dynamicLayoutMap; + + private static String brmsTemplateVlaue = "<$%BRMSParamTemplate="; + private static String string = "String"; + + + @RequestMapping(value={"/policyController/getBRMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public void getBRMSParamPolicyRuleData(HttpServletRequest request, HttpServletResponse response){ + try{ + dynamicLayoutMap = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + String rule = findRule(root.get(PolicyController.getPolicydata()).toString().replaceAll("^\"|\"$", "")); + generateUI(rule); + response.setCharacterEncoding(PolicyController.getCharacterencoding()); + response.setContentType(PolicyController.getContenttype()); + request.setCharacterEncoding(PolicyController.getCharacterencoding()); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(dynamicLayoutMap); + JSONObject j = new JSONObject("{policyData: " + responseString + "}"); + out.write(j.toString()); + }catch(Exception e){ + policyLogger.error("Exception Occured while getting BRMS Rule data" , e); + } + } + + protected String findRule(String ruleTemplate) { + List datas = commonClassDao.getDataById(BRMSParamTemplate.class, "ruleName", ruleTemplate); + if(datas != null && !datas.isEmpty()){ + BRMSParamTemplate bRMSParamTemplate = (BRMSParamTemplate) datas.get(0); + return bRMSParamTemplate.getRule(); + } + return null; + } + + protected void generateUI(String rule) { + if(rule!=null){ + try { + StringBuilder params = new StringBuilder(""); + Boolean flag = false; + Boolean comment = false; + String lines[] = rule.split("\n"); + for(String line : lines){ + if (line.isEmpty() || line.startsWith("//")) { + continue; + } + if (line.startsWith("/*")) { + comment = true; + continue; + } + if (line.contains("//")) { + line = line.split("\\/\\/")[0]; + } + if (line.contains("/*")) { + comment = true; + if (line.contains("*/")) { + try { + comment = false; + line = line.split("\\/\\*")[0] + + line.split("\\*\\/")[1].replace("*/", ""); + } catch (Exception e) { + policyLogger.info("Just for Logging"+e); + line = line.split("\\/\\*")[0]; + } + } else { + line = line.split("\\/\\*")[0]; + } + } + if (line.contains("*/")) { + comment = false; + try { + line = line.split("\\*\\/")[1].replace("*/", ""); + } catch (Exception e) { + policyLogger.info("Just for Logging"+e); + line = ""; + } + } + if (comment) { + continue; + } + if (flag) { + params.append(line); + } + if (line.contains("declare Params")) { + params.append(line); + flag = true; + } + if (line.contains("end") && flag) { + break; + } + } + params = new StringBuilder(params.toString().replace("declare Params", "").replace("end", "").replaceAll("\\s+", "")); + String[] components = params.toString().split(":"); + String caption = ""; + for (int i = 0; i < components.length; i++) { + String type = ""; + if (i == 0) { + caption = components[i]; + } + if("".equals(caption)){ + break; + } + String nextComponent = ""; + try { + nextComponent = components[i + 1]; + } catch (Exception e) { + policyLogger.info("Just for Logging"+e); + nextComponent = components[i]; + } + if (nextComponent.startsWith(string)) { + type = "String"; + createField(caption, type); + caption = nextComponent.replace(string, ""); + } else if (nextComponent.startsWith("int")) { + type = "int"; + createField(caption, type); + caption = nextComponent.replace("int", ""); + } + } + } catch (Exception e) { + policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + } + } + } + + private void createField(String caption, String type) { + dynamicLayoutMap.put(caption, type); + } + + /* + * When the User Click Edit or View Policy the following method will get invoked for setting the data to PolicyRestAdapter. + * Which is used to bind the data in GUI + */ + public void prePopulateBRMSParamPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + dynamicLayoutMap = new HashMap<>(); + if (policyAdapter.getPolicyData() instanceof PolicyType) { + PolicyType policy = (PolicyType) policyAdapter.getPolicyData(); + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + // policy name value is the policy name without any prefix and + // Extensions. + String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Param_") + 11); + if (policyLogger.isDebugEnabled()) { + policyLogger.debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName()); + } + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try{ + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + }catch(Exception e){ + policyLogger.info("Just for Logging"+e); + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + setDataAdapterFromAdviceExpressions(policy, policyAdapter); + paramUIGenerate(policyAdapter, entity); + // Get the target data under policy. + policyAdapter.setDynamicLayoutMap(dynamicLayoutMap); + if(policyAdapter.getDynamicLayoutMap().size() > 0){ + LinkedHashMap drlRule = new LinkedHashMap<>(); + for(Object keyValue: policyAdapter.getDynamicLayoutMap().keySet()){ + drlRule.put(keyValue.toString(), policyAdapter.getDynamicLayoutMap().get(keyValue)); + } + policyAdapter.setRuleData(drlRule); + } + TargetType target = policy.getTarget(); + if (target != null) { + setDataToAdapterFromTarget(target, policyAdapter); + } + } + } + + private void setDataAdapterFromAdviceExpressions(PolicyType policy, PolicyRestAdapter policyAdapter){ + ArrayList attributeList = new ArrayList<>(); + // Set Attributes. + AdviceExpressionsType expressionTypes = ((RuleType)policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0)).getAdviceExpressions(); + for( AdviceExpressionType adviceExpression: expressionTypes.getAdviceExpression()){ + for(AttributeAssignmentExpressionType attributeAssignment: adviceExpression.getAttributeAssignmentExpression()){ + if(attributeAssignment.getAttributeId().startsWith("key:")){ + Map attribute = new HashMap<>(); + String key = attributeAssignment.getAttributeId().replace("key:", ""); + attribute.put("key", key); + @SuppressWarnings("unchecked") + JAXBElement attributevalue = (JAXBElement) attributeAssignment.getExpression(); + String value = (String) attributevalue.getValue().getContent().get(0); + attribute.put("value", value); + attributeList.add(attribute); + }else if(attributeAssignment.getAttributeId().startsWith("dependencies:")){ + ArrayList dependencies = new ArrayList<>(Arrays.asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(","))); + if(dependencies.contains("")){ + dependencies.remove(""); + } + policyAdapter.setBrmsDependency(dependencies); + }else if(attributeAssignment.getAttributeId().startsWith("controller:")){ + policyAdapter.setBrmsController(attributeAssignment.getAttributeId().replace("controller:", "")); + } + } + policyAdapter.setAttributes(attributeList); + } + } + + private void setDataToAdapterFromTarget(TargetType target, PolicyRestAdapter policyAdapter){ + // Under target we have AnyOFType + List anyOfList = target.getAnyOf(); + if (anyOfList != null) { + Iterator iterAnyOf = anyOfList.iterator(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + // Under AnyOFType we have AllOFType + List allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator iterAllOf = allOfList.iterator(); + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + // Under AllOFType we have Match + List matchList = allOf.getMatch(); + if (matchList != null) { + setDataToAdapterFromMatchList(matchList, policyAdapter); + } + } + } + } + } + } + + private void setDataToAdapterFromMatchList(List matchList, PolicyRestAdapter policyAdapter){ + Iterator iterMatch = matchList.iterator(); + while (iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attribute value and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + + if ("RiskType".equals(attributeId)){ + policyAdapter.setRiskType(value); + } + if ("RiskLevel".equals(attributeId)){ + policyAdapter.setRiskLevel(value); + } + if ("guard".equals(attributeId)){ + policyAdapter.setGuard(value); + } + if ("TTLDate".equals(attributeId) && !value.contains("NA")){ + String newDate = convertDate(value, true); + policyAdapter.setTtlDate(newDate); + } + } + } + + private String convertDate(String dateTTL, boolean portalType) { + String formateDate = null; + String[] date; + String[] parts; + + if (portalType){ + parts = dateTTL.split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z"; + } else { + date = dateTTL.split("T"); + parts = date[0].split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + } + return formateDate; + } + // This method generates the UI from rule configuration + public void paramUIGenerate(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + String data = entity.getConfigurationData().getConfigBody(); + if(data != null){ + File file = new File(PolicyController.getConfigHome() +File.separator+ entity.getConfigurationData().getConfigurationName()); + if(file.exists()){ + try (BufferedReader br = new BufferedReader(new FileReader(file))) { + StringBuilder sb = new StringBuilder(); + String line = br.readLine(); + while (line != null) { + sb.append(line); + sb.append("\n"); + line = br.readLine(); + } + }catch(Exception e){ + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+ e.getMessage() + e); + } + } + try { + StringBuilder params = new StringBuilder(""); + Boolean flag = false; + Boolean comment = false; + for (String line : Files.readAllLines(Paths.get(file.toString()))) { + if (line.isEmpty() || line.startsWith("//")) { + continue; + } + if(line.contains(brmsTemplateVlaue)){ + String value = line.substring(line.indexOf("<$%"),line.indexOf("%$>")); + value = value.replace(brmsTemplateVlaue, ""); + policyAdapter.setRuleName(value); + } + if (line.startsWith("/*")) { + comment = true; + continue; + } + if ((line.contains("//"))&&(!(line.contains("http://") || line.contains("https://")))){ + line = line.split("\\/\\/")[0]; + } + if (line.contains("/*")) { + comment = true; + if (line.contains("*/")) { + try { + comment = false; + line = line.split("\\/\\*")[0] + + line.split("\\*\\/")[1].replace( + "*/", ""); + } catch (Exception e) { + policyLogger.info("Just for Logging"+e); + line = line.split("\\/\\*")[0]; + } + } else { + line = line.split("\\/\\*")[0]; + } + } + if (line.contains("*/")) { + comment = false; + try { + line = line.split("\\*\\/")[1] + .replace("*/", ""); + } catch (Exception e) { + policyLogger.info("Just for Logging"+e); + line = ""; + } + } + if (comment) { + continue; + } + if (flag) { + params.append(line); + } + if (line.contains("rule") && line.contains(".Params\"")) { + params.append(line); + flag = true; + } + if (line.contains("end") && flag) { + break; + } + } + params = new StringBuilder(params.substring(params.indexOf(".Params\"")+ 8)); + params = new StringBuilder(params.toString().replaceAll("\\s+", "").replace("salience1000whenthenParamsparams=newParams();","") + .replace("insert(params);end", "") + .replace("params.set", "")); + String[] components = params.toString().split("\\);"); + if(components!= null && components.length > 0){ + for (int i = 0; i < components.length; i++) { + String value = null; + components[i] = components[i]+")"; + String caption = components[i].substring(0, + components[i].indexOf('(')); + caption = caption.substring(0, 1).toLowerCase() + caption.substring(1); + if (components[i].contains("(\"")) { + value = components[i] + .substring(components[i].indexOf("(\""), + components[i].indexOf("\")")) + .replace("(\"", "").replace("\")", ""); + } else { + value = components[i] + .substring(components[i].indexOf('('), + components[i].indexOf(')')) + .replace("(", "").replace(")", ""); + } + dynamicLayoutMap.put(caption, value); + + } + } + } catch (Exception e) { + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage() + e); + } + } + + } + + // set View Rule + @SuppressWarnings("unchecked") + @RequestMapping(value={"/policyController/ViewBRMSParamPolicyRule.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public void setViewRule(HttpServletRequest request, HttpServletResponse response){ + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyRestAdapter policyData = mapper.readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class); + policyData.setDomainDir(root.get(PolicyController.getPolicydata()).get("model").get("name").toString().replace("\"", "")); + if(root.get(PolicyController.getPolicydata()).get("model").get("type").toString().replace("\"", "").equals(PolicyController.getFile())){ + policyData.setEditPolicy(true); + } + + String body = ""; + + body = "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " + + brmsTemplateVlaue + policyData.getRuleName() + "%$> \n */ \n"; + body = body + findRule((String) policyData.getRuleName()) + "\n"; + StringBuilder generatedRule = new StringBuilder(); + generatedRule.append("rule \""+ policyData.getDomainDir().replace("\\", ".") +".Config_BRMS_Param_" + policyData.getPolicyName()+".Params\" \n\tsalience 1000 \n\twhen\n\tthen\n\t\tParams params = new Params();"); + + if(policyData.getRuleData().size() > 0){ + for(Object keyValue: policyData.getRuleData().keySet()){ + String key = keyValue.toString().substring(0, 1).toUpperCase() + keyValue.toString().substring(1); + if (string.equals(keyValue)) { + generatedRule.append("\n\t\tparams.set" + + key + "(\"" + + policyData.getRuleData().get(keyValue).toString() + "\");"); + } else { + generatedRule.append("\n\t\tparams.set" + + key + "(" + + policyData.getRuleData().get(keyValue).toString() + ");"); + } + } + } + generatedRule.append("\n\t\tinsert(params);\nend"); + policyLogger.info("New rule generated with :" + generatedRule.toString()); + body = body + generatedRule.toString(); + // Expand the body. + Map copyMap=new HashMap<>(); + copyMap.putAll((Map) policyData.getRuleData()); + copyMap.put("policyName", policyData.getDomainDir().replace("\\", ".") +".Config_BRMS_Param_" + policyData.getPolicyName()); + copyMap.put("policyScope", policyData.getDomainDir().replace("\\", ".")); + copyMap.put("policyVersion", "1"); + //Finding all the keys in the Map data-structure. + Set keySet= copyMap.keySet(); + Iterator iterator = keySet.iterator(); + Pattern p; + Matcher m; + while(iterator.hasNext()) { + //Converting the first character of the key into a lower case. + String input= iterator.next(); + String output = Character.toLowerCase(input.charAt(0)) + + (input.length() > 1 ? input.substring(1) : ""); + //Searching for a pattern in the String using the key. + p=Pattern.compile("\\$\\{"+output+"\\}"); + m=p.matcher(body); + //Replacing the value with the inputs provided by the user in the editor. + body=m.replaceAll(copyMap.get(input)); + } + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(body); + JSONObject j = new JSONObject("{policyData: " + responseString + "}"); + out.write(j.toString()); + } catch (Exception e) { + policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java new file mode 100644 index 000000000..9851d3165 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java @@ -0,0 +1,172 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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 java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.xml.bind.JAXBElement; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.jpa.PolicyEntity; + +public class CreateBRMSRawController{ + + private static final Logger logger = FlexLogger.getLogger(CreateBRMSRawController.class); + + protected PolicyRestAdapter policyAdapter = null; + private ArrayList attributeList; + + + @SuppressWarnings("unchecked") + public void prePopulateBRMSRawPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + attributeList = new ArrayList(); + if (policyAdapter.getPolicyData() instanceof PolicyType) { + PolicyType policy = (PolicyType) policyAdapter.getPolicyData(); + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + // policy name value is the policy name without any prefix and + // Extensions. + String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Raw_") + 9); + if (logger.isDebugEnabled()) { + logger.debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName()); + } + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try{ + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + }catch(Exception e){ + logger.info("Not able to see the createdby in description. So, add generic description", e); + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + // Set Attributes. + AdviceExpressionsType expressionTypes = ((RuleType)policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0)).getAdviceExpressions(); + for( AdviceExpressionType adviceExpression: expressionTypes.getAdviceExpression()){ + for(AttributeAssignmentExpressionType attributeAssignment: adviceExpression.getAttributeAssignmentExpression()){ + if(attributeAssignment.getAttributeId().startsWith("key:")){ + Map attribute = new HashMap<>(); + String key = attributeAssignment.getAttributeId().replace("key:", ""); + attribute.put("key", key); + JAXBElement attributevalue = (JAXBElement) attributeAssignment.getExpression(); + String value = (String) attributevalue.getValue().getContent().get(0); + attribute.put("value", value); + attributeList.add(attribute); + }else if(attributeAssignment.getAttributeId().startsWith("dependencies:")){ + ArrayList dependencies = new ArrayList(Arrays.asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(","))); + if(dependencies.contains("")){ + dependencies.remove(""); + } + policyAdapter.setBrmsDependency(dependencies); + }else if(attributeAssignment.getAttributeId().startsWith("controller:")){ + policyAdapter.setBrmsController(attributeAssignment.getAttributeId().replace("controller:", "")); + } + } + policyAdapter.setAttributes(attributeList); + } + // Get the target data under policy. + policyAdapter.setConfigBodyData(entity.getConfigurationData().getConfigBody()); + TargetType target = policy.getTarget(); + if (target != null) { + // Under target we have AnyOFType + List anyOfList = target.getAnyOf(); + if (anyOfList != null) { + Iterator iterAnyOf = anyOfList.iterator(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + // Under AnyOFType we have AllOFType + List allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator iterAllOf = allOfList.iterator(); + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + // Under AllOFType we have Match + List matchList = allOf.getMatch(); + if (matchList != null) { + Iterator iterMatch = matchList.iterator(); + while (iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attribute value and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + + if (attributeId.equals("RiskType")){ + policyAdapter.setRiskType(value); + } + if (attributeId.equals("RiskLevel")){ + policyAdapter.setRiskLevel(value); + } + if (attributeId.equals("guard")){ + policyAdapter.setGuard(value); + } + if (attributeId.equals("TTLDate") && !value.contains("NA")){ + String newDate = convertDate(value, true); + policyAdapter.setTtlDate(newDate); + } + } + } + } + } + } + } + } + } + } + + private String convertDate(String dateTTL, boolean portalType) { + String formateDate = null; + String[] date; + String[] parts; + + if (portalType){ + parts = dateTTL.split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z"; + } else { + date = dateTTL.split("T"); + parts = date[0].split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + } + return formateDate; + } +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java new file mode 100644 index 000000000..a7ce45ec4 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java @@ -0,0 +1,709 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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 java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.adapter.ClosedLoopFaultBody; +import org.onap.policy.rest.adapter.ClosedLoopFaultTriggerUISignatures; +import org.onap.policy.rest.adapter.ClosedLoopSignatures; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.OnapName; +import org.onap.policy.rest.jpa.PolicyEntity; +import org.onap.policy.rest.jpa.VarbindDictionary; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + +@Controller +@RequestMapping("/") +public class CreateClosedLoopFaultController extends RestrictedBaseController{ + + private static final Logger policyLogger = FlexLogger.getLogger(CreateClosedLoopFaultController.class); + + protected PolicyRestAdapter policyAdapter = null; + + + private static CommonClassDao commonclassdao; + + @Autowired + private CreateClosedLoopFaultController(CommonClassDao commonclassdao){ + CreateClosedLoopFaultController.commonclassdao = commonclassdao; + } + + public CreateClosedLoopFaultController(){} + + public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root){ + try{ + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + TrapDatas trapDatas = mapper.readValue(root.get("trapData").toString(), TrapDatas.class); + TrapDatas faultDatas = mapper.readValue(root.get("faultData").toString(), TrapDatas.class); + ClosedLoopGridJSONData policyJsonData = mapper.readValue(root.get("policyData").get("policy").toString(), ClosedLoopGridJSONData.class); + ClosedLoopFaultBody jsonBody = mapper.readValue(root.get("policyData").get("policy").get("jsonBodyData").toString(), ClosedLoopFaultBody.class); + + ArrayList trapSignatureDatas = new ArrayList<>(); + if(trapDatas.getTrap1() != null){ + trapSignatureDatas.add(trapDatas); + } + ArrayList faultSignatureDatas = new ArrayList<>(); + if(faultDatas.getTrap1() != null){ + faultSignatureDatas.add(faultDatas); + } + + String resultBody = ""; + if(!policyJsonData.getConnecttriggerSignatures().isEmpty()){ + resultBody = resultBody + "("; + for(int i = policyJsonData.getConnecttriggerSignatures().size()-1; i>=0 ; i--){ + String connectBody = connectTriggerSignature(i, policyJsonData.getConnecttriggerSignatures(), trapSignatureDatas.get(0)); + resultBody = resultBody + connectBody; + } + resultBody = resultBody + ")"; + }else{ + if(!trapSignatureDatas.isEmpty()){ + resultBody = callTrap("nill", trapSignatureDatas.get(0)); + } + } + ClosedLoopSignatures triggerSignatures = new ClosedLoopSignatures(); + triggerSignatures.setSignatures(resultBody); + if(policyData.getClearTimeOut() != null){ + triggerSignatures.setTimeWindow(Integer.parseInt(policyData.getClearTimeOut())); + triggerSignatures.setTrapMaxAge(Integer.parseInt(policyData.getTrapMaxAge())); + ClosedLoopFaultTriggerUISignatures uiTriggerSignatures = new ClosedLoopFaultTriggerUISignatures(); + if(!trapSignatureDatas.isEmpty()){ + uiTriggerSignatures.setSignatures(getUITriggerSignature("Trap", trapSignatureDatas.get(0))); + if(!policyJsonData.getConnecttriggerSignatures().isEmpty()){ + uiTriggerSignatures.setConnectSignatures(getUIConnectTraps(policyJsonData.getConnecttriggerSignatures())); + } + } + jsonBody.setTriggerSignaturesUsedForUI(uiTriggerSignatures); + jsonBody.setTriggerTimeWindowUsedForUI(Integer.parseInt(policyData.getClearTimeOut())); + jsonBody.setTrapMaxAgeUsedForUI(Integer.parseInt(policyData.getTrapMaxAge())); + } + + jsonBody.setTriggerSignatures(triggerSignatures); + String faultBody = ""; + if(!policyJsonData.getConnectVerificationSignatures().isEmpty()){ + faultBody = faultBody + "("; + for(int i = policyJsonData.getConnectVerificationSignatures().size()-1; i>=0 ; i--){ + String connectBody = connectTriggerSignature(i, policyJsonData.getConnectVerificationSignatures(), faultSignatureDatas.get(0)); + faultBody = faultBody + connectBody; + } + faultBody = faultBody + ")"; + }else{ + if(!faultSignatureDatas.isEmpty()){ + faultBody = callTrap("nill", faultSignatureDatas.get(0)); + } + } + ClosedLoopSignatures faultSignatures = new ClosedLoopSignatures(); + faultSignatures.setSignatures(faultBody); + if(policyData.getVerificationclearTimeOut() != null){ + faultSignatures.setTimeWindow(Integer.parseInt(policyData.getVerificationclearTimeOut())); + ClosedLoopFaultTriggerUISignatures uifaultSignatures = new ClosedLoopFaultTriggerUISignatures(); + if(!faultSignatureDatas.isEmpty()){ + uifaultSignatures.setSignatures(getUITriggerSignature("Fault", faultSignatureDatas.get(0))); + if(!policyJsonData.getConnectVerificationSignatures().isEmpty()){ + uifaultSignatures.setConnectSignatures(getUIConnectTraps(policyJsonData.getConnectVerificationSignatures())); + } + } + + jsonBody.setVerificationSignaturesUsedForUI(uifaultSignatures); + jsonBody.setVerfificationTimeWindowUsedForUI(Integer.parseInt(policyData.getVerificationclearTimeOut())); + } + jsonBody.setVerificationSignatures(faultSignatures); + ObjectWriter om = new ObjectMapper().writer(); + String json = om.writeValueAsString(jsonBody); + policyData.setJsonBody(json); + + }catch(Exception e){ + policyLogger.error("Exception Occured while setting data to Adapter" , e); + } + return policyData; + } + + + @SuppressWarnings("unchecked") + private String connectTriggerSignature(int index, ArrayList triggerSignatures, Object object) { + String resultBody = ""; + Map connectTraps = (Map) triggerSignatures.get(index); + try{ + String notBox = ""; + if(connectTraps.keySet().contains("notBox")){ + notBox = connectTraps.get("notBox"); + } + resultBody = resultBody + "(" + notBox; + }catch(NullPointerException e){ + policyLogger.info("General error" , e); + resultBody = resultBody + "("; + } + String connectTrap1 = connectTraps.get("connectTrap1"); + if(connectTrap1.startsWith("Trap") || connectTrap1.startsWith("Fault")){ + String trapBody = callTrap(connectTrap1, object); + if(trapBody!=null){ + resultBody = resultBody + trapBody; + } + }else if(connectTrap1.startsWith("C")){ + for(int i=0; i<= triggerSignatures.size(); i++){ + Map triggerSignature = (Map) triggerSignatures.get(i); + if(triggerSignature.get("id").equals(connectTrap1)){ + resultBody = resultBody + "("; + String connectBody = connectTriggerSignature(i, triggerSignatures, object); + resultBody = resultBody + connectBody + ")"; + }else{ + i++; + } + } + } + try{ + String trapCount1 = connectTraps.get("trapCount1"); + resultBody = resultBody + ", Time = " + trapCount1 + ")"; + }catch(NullPointerException e){ + policyLogger.info("General error" , e); + } + try{ + String operatorBox = connectTraps.get("operatorBox"); + resultBody = resultBody + operatorBox +"("; + }catch (NullPointerException e){ + policyLogger.info("General error" , e); + } + try{ + String connectTrap2 = connectTraps.get("connectTrap2"); + if(connectTrap2.startsWith("Trap") || connectTrap2.startsWith("Fault")){ + String trapBody = callTrap(connectTrap2, object); + if(trapBody!=null){ + resultBody = resultBody + trapBody; + } + }else if(connectTrap2.startsWith("C")){ + for(int i=0; i<= triggerSignatures.size(); i++){ + Map triggerSignature = (Map) triggerSignatures.get(i); + if(triggerSignature.get("id").equals(connectTrap2)){ + resultBody = resultBody + "("; + String connectBody = connectTriggerSignature(i, triggerSignatures, object); + resultBody = resultBody + connectBody + ")"; + }else{ + i++; + } + } + } + }catch(NullPointerException e){ + policyLogger.info("General error" , e); + } + try{ + String trapCount2 = connectTraps.get("trapCount2"); + resultBody = resultBody + ", Time = " + trapCount2 + ")"; + }catch(NullPointerException e){ + policyLogger.info("General error" , e); + } + return resultBody; + } + + + private String callTrap(String trap, Object object) { + String signatureBody = ""; + TrapDatas trapDatas = (TrapDatas) object; + ArrayList attributeList = new ArrayList<>(); + // Read the Trap + if(!trap.equals("nill")){ + try{ + if(trap.startsWith("Trap")){ + if(trap.equals("Trap1")){ + attributeList = trapDatas.getTrap1(); + }else if(trap.equals("Trap2")){ + attributeList = trapDatas.getTrap2(); + }else if(trap.equals("Trap3")){ + attributeList = trapDatas.getTrap3(); + }else if(trap.equals("Trap4")){ + attributeList = trapDatas.getTrap4(); + }else if(trap.equals("Trap5")){ + attributeList = trapDatas.getTrap5(); + }else if(trap.equals("Trap6")){ + attributeList = trapDatas.getTrap6(); + } + }else{ + if(trap.startsWith("Fault")){ + if(trap.equals("Fault1")){ + attributeList = trapDatas.getTrap1(); + }else if(trap.equals("Fault2")){ + attributeList = trapDatas.getTrap2(); + }else if(trap.equals("Fault3")){ + attributeList = trapDatas.getTrap3(); + }else if(trap.equals("Fault4")){ + attributeList = trapDatas.getTrap4(); + }else if(trap.equals("Fault5")){ + attributeList = trapDatas.getTrap5(); + }else if(trap.equals("Fault6")){ + attributeList = trapDatas.getTrap6(); + } + } + } + } catch(Exception e){ + return "(" + trap + ")"; + } + }else{ + if(trapDatas.getTrap1()!=null){ + attributeList = trapDatas.getTrap1(); + }else{ + return ""; + } + } + signatureBody = signatureBody + "(" + readAttributes(attributeList, attributeList.size()-1) + ")"; + return signatureBody; + } + + @SuppressWarnings("unchecked") + private String readAttributes(ArrayList object, int index) { + String attributes = ""; + Map trapSignatures = (Map) object.get(index); + // Read the Elements. + Object notBox = ""; + if(trapSignatures.keySet().contains("notBox")){ + notBox = trapSignatures.get("notBox"); + } + if(notBox!=null){ + attributes = attributes + notBox.toString(); + } + Object trapName1 = trapSignatures.get("trigger1"); + if(trapName1!=null){ + String attrib = trapName1.toString(); + if(attrib.startsWith("A")){ + try{ + int iy = Integer.parseInt(attrib.substring(1))-1; + attributes = attributes + "(" + readAttributes(object, iy) + ")"; + }catch(NumberFormatException e){ + try { + attrib = getVarbindOID(attrib); + attributes = attributes + "("+ URLEncoder.encode(attrib, "UTF-8")+ ")"; + } catch (UnsupportedEncodingException e1) { + //logger.error("Caused Exception while Encoding Varbind Dictionary Values"+e1); + } + } + }else{ + try { + attrib = getVarbindOID(attrib); + attributes = attributes + "("+ URLEncoder.encode(attrib, "UTF-8")+ ")"; + } catch (UnsupportedEncodingException e) { + //logger.error("Caused Exception while Encoding Varbind Dictionary Values"+e); + } + } + }else{ + return ""; + } + Object comboBox = trapSignatures.get("operatorBox"); + if(comboBox!=null){ + attributes = attributes + comboBox.toString(); + }else{ + return attributes; + } + Object trapName2 = trapSignatures.get("trigger2"); + if(trapName2!=null){ + String attrib = trapName2.toString(); + if(attrib.startsWith("A")){ + try{ + int iy = Integer.parseInt(attrib.substring(1))-1; + attributes = attributes + "(" + readAttributes(object, iy) + ")"; + }catch(NumberFormatException e){ + try { + attrib = getVarbindOID(attrib); + attributes = attributes + "("+ URLEncoder.encode(attrib, "UTF-8") + ")"; + } catch (UnsupportedEncodingException e1) { + //logger.error("Caused Exception while Encoding Varbind Dictionary Values"+e1); + } + } + }else{ + try { + attrib = getVarbindOID(attrib); + attributes = attributes + "("+ URLEncoder.encode(attrib, "UTF-8") + ")"; + } catch (UnsupportedEncodingException e) { + //logger.error("Caused Exception while Encoding Varbind Dictionary Values"+e); + } + } + } + return attributes; + } + + private String getVarbindOID(String attrib) { + VarbindDictionary varbindId = null; + try{ + varbindId = (VarbindDictionary) commonclassdao.getEntityItem(VarbindDictionary.class, "varbindName", attrib); + return varbindId.getVarbindOID(); + }catch(Exception e){ + return attrib; + } + } + + + //connect traps data set to JSON Body as String + @SuppressWarnings({ "unchecked", "rawtypes" }) + private String getUIConnectTraps(ArrayList connectTrapSignatures) { + String resultBody = ""; + String connectMainBody = ""; + for(int j = 0; j < connectTrapSignatures.size(); j++){ + Map connectTraps = (Map)connectTrapSignatures.get(j); + String connectBody = ""; + Object object = connectTraps; + if(object instanceof LinkedHashMap){ + String notBox = ""; + String connectTrap1 = ""; + String trapCount1 = ""; + String operatorBox = ""; + String connectTrap2 = ""; + String trapCount2 = ""; + if(((LinkedHashMap) object).keySet().contains("notBox")){ + notBox = ((LinkedHashMap) object).get("notBox").toString(); + } + if(((LinkedHashMap) object).get("connectTrap1") != null){ + connectTrap1 = ((LinkedHashMap) object).get("connectTrap1").toString(); + } + if(((LinkedHashMap) object).get("trapCount1") != null){ + trapCount1 = ((LinkedHashMap) object).get("trapCount1").toString(); + } + if(((LinkedHashMap) object).get("operatorBox") != null){ + operatorBox = ((LinkedHashMap) object).get("operatorBox").toString(); + } + if(((LinkedHashMap) object).get("connectTrap2") != null){ + connectTrap2 = ((LinkedHashMap) object).get("connectTrap2").toString(); + } + if(((LinkedHashMap) object).get("trapCount2") != null){ + trapCount2 = ((LinkedHashMap) object).get("trapCount2").toString(); + } + connectBody = notBox + "@!" + connectTrap1 + "@!" + trapCount1 + "@!" + operatorBox + "@!" + connectTrap2 + "@!" + trapCount2 + "#!?!"; + } + resultBody = resultBody + connectBody; + } + connectMainBody = connectMainBody + resultBody; + return connectMainBody; + } + + + + // get Trigger signature from JSON body + @SuppressWarnings({ "rawtypes", "unchecked" }) + private String getUITriggerSignature(String trap, Object object2) { + String triggerBody = ""; + TrapDatas trapDatas = (TrapDatas) object2; + ArrayList attributeList = new ArrayList<>(); + // Read the Trap + if(trap.startsWith("Trap")){ + if(trapDatas.getTrap1()!= null){ + attributeList.add(trapDatas.getTrap1()); + } + if(trapDatas.getTrap2()!= null){ + attributeList.add(trapDatas.getTrap2()); + } + if(trapDatas.getTrap3()!= null){ + attributeList.add(trapDatas.getTrap3()); + } + if(trapDatas.getTrap4()!= null){ + attributeList.add(trapDatas.getTrap4()); + } + if(trapDatas.getTrap5()!= null){ + attributeList.add(trapDatas.getTrap5()); + } + if(trapDatas.getTrap6()!= null){ + attributeList.add(trapDatas.getTrap6()); + } + }else{ + if(trap.startsWith("Fault")){ + if(trapDatas.getTrap1()!= null){ + attributeList.add(trapDatas.getTrap1()); + } + if(trapDatas.getTrap2()!= null){ + attributeList.add(trapDatas.getTrap2()); + } + if(trapDatas.getTrap3()!= null){ + attributeList.add(trapDatas.getTrap3()); + } + if(trapDatas.getTrap4()!= null){ + attributeList.add(trapDatas.getTrap4()); + } + if(trapDatas.getTrap5()!= null){ + attributeList.add(trapDatas.getTrap5()); + } + if(trapDatas.getTrap6()!= null){ + attributeList.add(trapDatas.getTrap6()); + } + } + } + + for(int j = 0; j < attributeList.size(); j++){ + String signatureBody = ""; + ArrayList connectTraps = (ArrayList) attributeList.get(j); + for(int i =0 ; i < connectTraps.size(); i++){ + String connectBody = ""; + Object object = connectTraps.get(i); + if(object instanceof LinkedHashMap){ + String notBox = ""; + String trigger1 = ""; + String operatorBox = ""; + String trigger2 = ""; + if(((LinkedHashMap) object).keySet().contains("notBox")){ + notBox = ((LinkedHashMap) object).get("notBox").toString(); + } + if(((LinkedHashMap) object).get("trigger1") != null){ + trigger1 = ((LinkedHashMap) object).get("trigger1").toString(); + } + if(((LinkedHashMap) object).get("operatorBox") != null){ + operatorBox = ((LinkedHashMap) object).get("operatorBox").toString(); + } + if(((LinkedHashMap) object).get("trigger2") != null){ + trigger2 = ((LinkedHashMap) object).get("trigger2").toString(); + } + connectBody = notBox + "@!" + trigger1 + "@!" + operatorBox + "@!" + trigger2 + "#!"; + } + signatureBody = signatureBody + connectBody; + } + triggerBody = triggerBody + signatureBody + "?!"; + } + + return triggerBody; + } + + public void prePopulateClosedLoopFaultPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + if (policyAdapter.getPolicyData() instanceof PolicyType) { + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("Fault_") +6); + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try{ + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + }catch(Exception e){ + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + // Get the target data under policy. + TargetType target = policy.getTarget(); + if (target != null) { + // Under target we have AnyOFType + List anyOfList = target.getAnyOf(); + if (anyOfList != null) { + Iterator iterAnyOf = anyOfList.iterator(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + // Under AnyOFType we have AllOFType + List allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator iterAllOf = allOfList.iterator(); + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + // Under AllOFType we have Match + List matchList = allOf.getMatch(); + if (matchList != null) { + Iterator iterMatch = matchList.iterator(); + while (iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attribute value and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + + // First match in the target is OnapName, so set that value. + if (attributeId.equals("ONAPName")) { + policyAdapter.setOnapName(value); + OnapName onapName = new OnapName(); + onapName.setOnapName(value); + policyAdapter.setOnapNameField(onapName); + } + if (attributeId.equals("RiskType")){ + policyAdapter.setRiskType(value); + } + if (attributeId.equals("RiskLevel")){ + policyAdapter.setRiskLevel(value); + } + if (attributeId.equals("guard")){ + policyAdapter.setGuard(value); + } + if (attributeId.equals("TTLDate") && !value.contains("NA")){ + String newDate = convertDate(value, true); + policyAdapter.setTtlDate(newDate); + } + } + } + } + } + } + } + } + readClosedLoopJSONFile(policyAdapter, entity); + } + + } + + private String convertDate(String dateTTL, boolean portalType) { + String formateDate = null; + String[] date; + String[] parts; + + if (portalType){ + parts = dateTTL.split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z"; + } else { + date = dateTTL.split("T"); + parts = date[0].split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + } + return formateDate; + } + + private String readClosedLoopJSONFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + ObjectMapper mapper = new ObjectMapper(); + try { + ClosedLoopFaultBody closedLoopBody = mapper.readValue(entity.getConfigurationData().getConfigBody(), ClosedLoopFaultBody.class); + if(closedLoopBody.getClosedLoopPolicyStatus().equalsIgnoreCase("ACTIVE")){ + closedLoopBody.setClosedLoopPolicyStatus("Active"); + }else{ + closedLoopBody.setClosedLoopPolicyStatus("InActive"); + } + policyAdapter.setJsonBodyData(closedLoopBody); + if(closedLoopBody.getTrapMaxAgeUsedForUI() != null){ + policyAdapter.setTrapMaxAge(closedLoopBody.getTrapMaxAgeUsedForUI().toString()); + } + if(closedLoopBody.getTriggerTimeWindowUsedForUI() != null){ + policyAdapter.setClearTimeOut(closedLoopBody.getTriggerTimeWindowUsedForUI().toString()); + } + if(closedLoopBody.getVerfificationTimeWindowUsedForUI() != null){ + policyAdapter.setVerificationclearTimeOut(closedLoopBody.getVerfificationTimeWindowUsedForUI().toString()); + } + + } catch (Exception e) { + policyLogger.error("Exception Occured"+e); + } + + return null; + } + +} + +class TrapDatas{ + private ArrayList trap1; + private ArrayList trap2; + private ArrayList trap3; + private ArrayList trap4; + private ArrayList trap5; + private ArrayList trap6; + public ArrayList getTrap1() { + return trap1; + } + public void setTrap1(ArrayList trap1) { + this.trap1 = trap1; + } + public ArrayList getTrap2() { + return trap2; + } + public void setTrap2(ArrayList trap2) { + this.trap2 = trap2; + } + public ArrayList getTrap3() { + return trap3; + } + public void setTrap3(ArrayList trap3) { + this.trap3 = trap3; + } + public ArrayList getTrap4() { + return trap4; + } + public void setTrap4(ArrayList trap4) { + this.trap4 = trap4; + } + public ArrayList getTrap5() { + return trap5; + } + public void setTrap5(ArrayList trap5) { + this.trap5 = trap5; + } + public ArrayList getTrap6() { + return trap6; + } + public void setTrap6(ArrayList trap6) { + this.trap6 = trap6; + } +} + +class ClosedLoopGridJSONData{ + + private String clearTimeOut; + private String trapMaxAge; + private String verificationclearTimeOut; + private ArrayList connecttriggerSignatures; + private ArrayList connectVerificationSignatures; + + public String getClearTimeOut() { + return clearTimeOut; + } + public void setClearTimeOut(String clearTimeOut) { + this.clearTimeOut = clearTimeOut; + } + public String getTrapMaxAge() { + return trapMaxAge; + } + public void setTrapMaxAge(String trapMaxAge) { + this.trapMaxAge = trapMaxAge; + } + public String getVerificationclearTimeOut() { + return verificationclearTimeOut; + } + public void setVerificationclearTimeOut(String verificationclearTimeOut) { + this.verificationclearTimeOut = verificationclearTimeOut; + } + + + public ArrayList getConnecttriggerSignatures() { + return connecttriggerSignatures; + } + public void setConnecttriggerSignatures(ArrayList connecttriggerSignatures) { + this.connecttriggerSignatures = connecttriggerSignatures; + } + public ArrayList getConnectVerificationSignatures() { + return connectVerificationSignatures; + } + public void setConnectVerificationSignatures(ArrayList connectVerificationSignatures) { + this.connectVerificationSignatures = connectVerificationSignatures; + } +} \ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.java new file mode 100644 index 000000000..a4d6014c9 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.java @@ -0,0 +1,208 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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 java.io.IOException; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; + +import javax.json.JsonArray; +import javax.json.JsonObject; + +import org.onap.policy.admin.PolicyManagerServlet; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.adapter.ClosedLoopPMBody; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.jpa.PolicyEntity; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + +public class CreateClosedLoopPMController{ + + private static final Logger LOGGER = FlexLogger.getLogger(CreateClosedLoopPMController.class); + + protected PolicyRestAdapter policyAdapter = null; + + public void prePopulateClosedLoopPMPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + if (policyAdapter.getPolicyData() instanceof PolicyType) { + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("PM_") +3); + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try{ + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + }catch(Exception e){ + LOGGER.info("General error" , e); + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + // Get the target data under policy. + TargetType target = policy.getTarget(); + if (target != null) { + // Under target we have AnyOFType + List anyOfList = target.getAnyOf(); + if (anyOfList != null) { + Iterator iterAnyOf = anyOfList.iterator(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + // Under AnyOFType we have AllOFType + List allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator iterAllOf = allOfList.iterator(); + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + // Under AllOFType we have Match + List matchList = allOf.getMatch(); + if (matchList != null) { + Iterator iterMatch = matchList.iterator(); + while (matchList.size()>1 && iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attribute value and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + + // First match in the target is OnapName, so set that value. + if (attributeId.equals("ONAPName")) { + policyAdapter.setOnapName(value); + } + if (attributeId.equals("RiskType")){ + policyAdapter.setRiskType(value); + } + if (attributeId.equals("RiskLevel")){ + policyAdapter.setRiskLevel(value); + } + if (attributeId.equals("guard")){ + policyAdapter.setGuard(value); + } + if (attributeId.equals("TTLDate") && !value.contains("NA")){ + String newDate = convertDate(value, true); + policyAdapter.setTtlDate(newDate); + } + if (attributeId.equals("ServiceType")){ + LinkedHashMap serviceTypePolicyName1 = new LinkedHashMap<>(); + String key = "serviceTypePolicyName"; + serviceTypePolicyName1.put(key, value); + policyAdapter.setServiceTypePolicyName(serviceTypePolicyName1); + LinkedHashMap vertica = new LinkedHashMap<>(); + vertica.put("verticaMetrics", getVertica(value)); + policyAdapter.setVerticaMetrics(vertica); + LinkedHashMap desc = new LinkedHashMap<>(); + desc.put("policyDescription", getDescription(value)); + policyAdapter.setDescription(desc); + LinkedHashMap attributes = new LinkedHashMap<>(); + attributes.put("attributes", getAttributes(value)); + policyAdapter.setAttributeFields(attributes); + } + } + } + } + } + } + } + } + readClosedLoopJSONFile(policyAdapter, entity); + } + } + + private String convertDate(String dateTTL, boolean portalType) { + String formateDate = null; + String[] date; + String[] parts; + + if (portalType){ + parts = dateTTL.split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z"; + } else { + date = dateTTL.split("T"); + parts = date[0].split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + } + return formateDate; + } + + protected void readClosedLoopJSONFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + ObjectMapper mapper = new ObjectMapper(); + try { + ClosedLoopPMBody closedLoopBody = mapper.readValue(entity.getConfigurationData().getConfigBody(), ClosedLoopPMBody.class); + policyAdapter.setJsonBodyData(closedLoopBody); + } catch (IOException e) { + LOGGER.error("Exception Occured"+e); + } + } + + //get vertica metrics data from the table + private String getVertica(String policyName){ + String verticas = null; + JsonArray data = PolicyManagerServlet.getPolicyNames(); + for(int i=0 ; i< data.size(); i++){ + if(policyName.equals(data.getJsonObject(i).getJsonString("serviceTypePolicyName").getString())){ + verticas = data.getJsonObject(i).getJsonString("verticaMetrics").getString(); + return verticas; + } + } + return verticas; + } + + //get policy description from the table + private String getDescription(String policyName){ + String description = null; + JsonArray data = PolicyManagerServlet.getPolicyNames(); + for(int i=0 ; i< data.size(); i++){ + if(policyName.equals(data.getJsonObject(i).getJsonString("serviceTypePolicyName").getString())){ + description = data.getJsonObject(i).getJsonString("policyDescription").getString(); + return description; + } + } + return description; + } + + //get Attributes + private JsonObject getAttributes(String policyName){ + JsonObject attributes = null; + JsonArray data = PolicyManagerServlet.getPolicyNames(); + for(int i=0 ; i< data.size(); i++){ + if(policyName.equals(data.getJsonObject(i).getJsonString("serviceTypePolicyName").getString())){ + attributes = data.getJsonObject(i).getJsonObject("attributes"); + return attributes; + } + } + return attributes; + } + +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java new file mode 100644 index 000000000..609a45c20 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java @@ -0,0 +1,1622 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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 java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintWriter; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.TreeMap; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.compress.utils.IOUtils; +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.apache.commons.fileupload.servlet.ServletFileUpload; +import org.apache.commons.io.FileUtils; +import org.apache.commons.lang.StringUtils; +import org.json.JSONArray; +import org.json.JSONObject; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.GroupPolicyScopeList; +import org.onap.policy.rest.jpa.MicroServiceModels; +import org.onap.policy.rest.jpa.PolicyEntity; +import org.onap.policy.rest.util.MSAttributeObject; +import org.onap.policy.rest.util.MSModelUtils; +import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +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.servlet.ModelAndView; +import org.yaml.snakeyaml.Yaml; + +import com.att.research.xacml.util.XACMLProperties; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.gson.Gson; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + +@Controller +@RequestMapping("/") +public class CreateDcaeMicroServiceController extends RestrictedBaseController { + private static final Logger LOGGER = FlexLogger.getLogger(CreateDcaeMicroServiceController.class); + + private static CommonClassDao commonClassDao; + + public static CommonClassDao getCommonClassDao() { + return commonClassDao; + } + + public static void setCommonClassDao(CommonClassDao commonClassDao) { + CreateDcaeMicroServiceController.commonClassDao = commonClassDao; + } + + private MicroServiceModels newModel; + private String newFile; + private String directory; + private List modelList = new ArrayList<>(); + private List dirDependencyList = new ArrayList<>(); + private HashMap classMap = new HashMap<>(); + //Tosca Model related Datastructure. + String referenceAttributes; + String attributeString; + String listConstraints; + String subAttributeString; + HashMap retmap = new HashMap<>(); + Set uniqueKeys= new HashSet<>(); + Set uniqueDataKeys= new HashSet<>(); + StringBuilder dataListBuffer=new StringBuilder(); + List dataConstraints= new ArrayList <>(); + + public static final String DATATYPE = "data_types.policy.data."; + public static final String PROPERTIES=".properties."; + public static final String TYPE=".type"; + public static final String STRING="string"; + public static final String INTEGER="integer"; + public static final String LIST="list"; + public static final String DEFAULT=".default"; + public static final String REQUIRED=".required"; + public static final String MANYFALSE=":MANY-false"; + + + @Autowired + private CreateDcaeMicroServiceController(CommonClassDao commonClassDao){ + CreateDcaeMicroServiceController.commonClassDao = commonClassDao; + } + + public CreateDcaeMicroServiceController(){} + + protected PolicyRestAdapter policyAdapter = null; + private int priorityCount; + private Map attributesListRefMap = new HashMap<>(); + private Map> arrayTextList = new HashMap<>(); + + public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) { + + String jsonContent = null; + try{ + jsonContent = decodeContent(root.get("policyJSON")).toString(); + constructJson(policyData, jsonContent); + }catch(Exception e){ + LOGGER.error("Error while decoding microservice content", e); + } + + return policyData; + } + + private GroupPolicyScopeList getPolicyObject(String policyScope) { + GroupPolicyScopeList groupList= (GroupPolicyScopeList) commonClassDao.getEntityItem(GroupPolicyScopeList.class, "name", policyScope); + return groupList; + } + + private PolicyRestAdapter constructJson(PolicyRestAdapter policyAdapter, String jsonContent) { + ObjectWriter om = new ObjectMapper().writer(); + String json=""; + DCAEMicroServiceObject microServiceObject = new DCAEMicroServiceObject(); + MicroServiceModels returnModel = new MicroServiceModels(); + microServiceObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_MS)); + if(policyAdapter.getServiceType() !=null){ + microServiceObject.setService(policyAdapter.getServiceType()); + microServiceObject.setVersion(policyAdapter.getVersion()); + returnModel = getAttributeObject(microServiceObject.getService(), microServiceObject.getVersion()); + } + if (returnModel.getAnnotation()==null || returnModel.getAnnotation().isEmpty()){ + if(policyAdapter.getUuid()!=null){ + microServiceObject.setUuid(policyAdapter.getUuid()); + } + if(policyAdapter.getLocation()!=null){ + microServiceObject.setLocation(policyAdapter.getLocation()); + } + if(policyAdapter.getConfigName()!=null){ + microServiceObject.setConfigName(policyAdapter.getConfigName()); + } + GroupPolicyScopeList policyScopeValue = getPolicyObject(policyAdapter.getPolicyScope()); + if(policyScopeValue!=null){ + microServiceObject.setPolicyScope(policyScopeValue.getGroupList()); + } + } + + if(policyAdapter.getPolicyName()!=null){ + microServiceObject.setPolicyName(policyAdapter.getPolicyName()); + } + if(policyAdapter.getPolicyDescription()!=null){ + microServiceObject.setDescription(policyAdapter.getPolicyDescription()); + } + if (policyAdapter.getPriority()!=null){ + microServiceObject.setPriority(policyAdapter.getPriority()); + }else { + microServiceObject.setPriority("9999"); + } + + if (policyAdapter.getRiskLevel()!=null){ + microServiceObject.setRiskLevel(policyAdapter.getRiskLevel()); + } + if (policyAdapter.getRiskType()!=null){ + microServiceObject.setRiskType(policyAdapter.getRiskType()); + } + if (policyAdapter.getGuard()!=null){ + microServiceObject.setGuard(policyAdapter.getGuard()); + } + microServiceObject.setContent(jsonContent); + + try { + json = om.writeValueAsString(microServiceObject); + } catch (JsonProcessingException e) { + LOGGER.error("Error writing out the object", e); + } + LOGGER.info(json); + String cleanJson = cleanUPJson(json); + cleanJson = removeNullAttributes(cleanJson); + policyAdapter.setJsonBody(cleanJson); + return policyAdapter; + } + + private String removeNullAttributes(String cleanJson) { + ObjectMapper mapper = new ObjectMapper(); + + try { + JsonNode rootNode = mapper.readTree(cleanJson); + JsonNode returnNode = mapper.readTree(cleanJson); + Iterator> fieldsIterator = rootNode.fields(); + boolean remove = false; + while (fieldsIterator.hasNext()) { + Map.Entry field = fieldsIterator.next(); + final String key = field.getKey(); + final JsonNode value = field.getValue(); + if (value==null || value.isNull()){ + ((ObjectNode) returnNode).remove(key); + remove = true; + } + } + if (remove){ + cleanJson = returnNode.toString(); + } + } catch (IOException e) { + LOGGER.error("Error writing out the JsonNode",e); + } + return cleanJson; + } + + // Second index of dot should be returned. + public int stringBetweenDots(String str){ + String stringToSearch=str; + String[]ss=stringToSearch.split("\\."); + if(ss!=null){ + int len= ss.length; + if(len>2){ + uniqueKeys.add(ss[2]); + } + } + + return uniqueKeys.size(); + } + + public void stringBetweenDotsForDataFields(String str){ + String stringToSearch=str; + String[]ss=stringToSearch.split("\\."); + if(ss!=null){ + int len= ss.length; + + if(len>2){ + uniqueDataKeys.add(ss[0]+"%"+ss[2]); + } + } + } + + + public Map load(String fileName) throws IOException { + File newConfiguration = new File(fileName); + InputStream is = null; + try { + is = new FileInputStream(newConfiguration); + } catch (FileNotFoundException e) { + LOGGER.error(e); + } + + Yaml yaml = new Yaml(); + @SuppressWarnings("unchecked") + Map yamlMap = (Map) yaml.load(is); + StringBuilder sb = new StringBuilder(); + Map settings = new HashMap<>(); + if (yamlMap == null) { + return settings; + } + List path = new ArrayList <>(); + serializeMap(settings, sb, path, yamlMap); + return settings; + } + + public Map load(byte[] source) throws IOException { + Yaml yaml = new Yaml(); + @SuppressWarnings("unchecked") + Map yamlMap = (Map) yaml.load(Arrays.toString(source)); + StringBuilder sb = new StringBuilder(); + Map settings = new HashMap <>(); + if (yamlMap == null) { + return settings; + } + List path = new ArrayList <>(); + serializeMap(settings, sb, path, yamlMap); + return settings; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private void serializeMap(Map settings, StringBuilder sb, List path, Map yamlMap) { + for (Map.Entry entry : yamlMap.entrySet()) { + if (entry.getValue() instanceof Map) { + path.add((String) entry.getKey()); + serializeMap(settings, sb, path, (Map) entry.getValue()); + path.remove(path.size() - 1); + } else if (entry.getValue() instanceof List) { + path.add((String) entry.getKey()); + serializeList(settings, sb, path, (List) entry.getValue()); + path.remove(path.size() - 1); + } else { + serializeValue(settings, sb, path, (String) entry.getKey(), entry.getValue()); + } + } + } + + @SuppressWarnings("unchecked") + private void serializeList(Map settings, StringBuilder sb, List path, List yamlList) { + int counter = 0; + for (Object listEle : yamlList) { + if (listEle instanceof Map) { + path.add(Integer.toString(counter)); + serializeMap(settings, sb, path, (Map) listEle); + path.remove(path.size() - 1); + } else if (listEle instanceof List) { + path.add(Integer.toString(counter)); + serializeList(settings, sb, path, (List) listEle); + path.remove(path.size() - 1); + } else { + serializeValue(settings, sb, path, Integer.toString(counter), listEle); + } + counter++; + } + } + + private void serializeValue(Map settings, StringBuilder sb, List path, String name, Object value) { + if (value == null) { + return; + } + sb.setLength(0); + for (String pathEle : path) { + sb.append(pathEle).append('.'); + } + sb.append(name); + settings.put(sb.toString(), value.toString()); + } + + void parseDataAndPolicyNodes(Map map){ + for(String key:map.keySet()){ + if(key.contains("policy.nodes.Root")) + { + continue; + } + else if(key.contains("policy.nodes")){ + String wordToFind = "policy.nodes."; + int indexForPolicyNode=key.indexOf(wordToFind); + String subNodeString= key.substring(indexForPolicyNode+13, key.length()); + + stringBetweenDots(subNodeString); + } + else if(key.contains("policy.data")){ + String wordToFind="policy.data."; + int indexForPolicyNode=key.indexOf(wordToFind); + String subNodeString= key.substring(indexForPolicyNode+12, key.length()); + + stringBetweenDotsForDataFields(subNodeString); + } + } + } + + HashMap parseDataNodes(Map map){ + HashMap dataMapForJson=new HashMap <>(); + for(String uniqueDataKey: uniqueDataKeys){ + if(uniqueDataKey.contains("%")){ + String[] uniqueDataKeySplit= uniqueDataKey.split("%"); + String findType=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+TYPE; + String typeValue=map.get(findType); + LOGGER.info(typeValue); + if(typeValue.equalsIgnoreCase(STRING)|| + typeValue.equalsIgnoreCase(INTEGER) + ) + { + String findDefault=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+DEFAULT; + String defaultValue= map.get(findDefault); + LOGGER.info("defaultValue is:"+ defaultValue); + + String findRequired=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+REQUIRED; + String requiredValue= map.get(findRequired); + LOGGER.info("requiredValue is:"+ requiredValue); + + StringBuilder attributeIndividualStringBuilder= new StringBuilder(); + attributeIndividualStringBuilder.append(typeValue+":defaultValue-"); + attributeIndividualStringBuilder.append(defaultValue+":required-"); + attributeIndividualStringBuilder.append(requiredValue+MANYFALSE); + dataMapForJson.put(uniqueDataKey, attributeIndividualStringBuilder.toString()); + } + else if(typeValue.equalsIgnoreCase(LIST)){ + String findList= DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+".entry_schema.type"; + String listValue=map.get(findList); + if(listValue!=null){ + LOGGER.info("Type of list is:"+ listValue); + //Its userdefined + if(listValue.contains(".")){ + String trimValue=listValue.substring(listValue.lastIndexOf('.')+1); + StringBuilder referenceIndividualStringBuilder= new StringBuilder(); + referenceIndividualStringBuilder.append(trimValue+":MANY-true"); + dataMapForJson.put(uniqueDataKey, referenceIndividualStringBuilder.toString()); + }//Its string + else{ + StringBuilder stringListItems= new StringBuilder(); + stringListItems.append(uniqueDataKeySplit[1].toUpperCase()+":MANY-false"); + dataMapForJson.put(uniqueDataKey, stringListItems.toString()); + dataListBuffer.append(uniqueDataKeySplit[1].toUpperCase()+"=["); + for(int i=0;i<10;i++){ + String findConstraints= DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+".entry_schema.constraints.0.valid_values."+i; + String constraintsValue=map.get(findConstraints); + LOGGER.info(constraintsValue); + if(constraintsValue==null){ + break; + } + else{ + dataConstraints.add(constraintsValue); + dataListBuffer.append(constraintsValue+","); + } + } + dataListBuffer.append("]#"); + + LOGGER.info(dataListBuffer); + } + } + } + else{ + String findUserDefined="data_types.policy.data."+uniqueDataKeySplit[0]+"."+"properties"+"."+uniqueDataKeySplit[1]+".type"; + String userDefinedValue=map.get(findUserDefined); + String trimValue=userDefinedValue.substring(userDefinedValue.lastIndexOf('.')+1); + StringBuilder referenceIndividualStringBuilder= new StringBuilder(); + referenceIndividualStringBuilder.append(trimValue+":MANY-false"); + dataMapForJson.put(uniqueDataKey, referenceIndividualStringBuilder.toString()); + + } + } + } + return dataMapForJson; + } + + void constructJsonForDataFields(HashMap dataMapForJson){ + HashMap> dataMapKey= new HashMap <>(); + HashMap hmSub; + for(Map.Entry entry: dataMapForJson.entrySet()){ + String uniqueDataKey= entry.getKey(); + String[] uniqueDataKeySplit=uniqueDataKey.split("%"); + String value= dataMapForJson.get(uniqueDataKey); + if(dataMapKey.containsKey(uniqueDataKeySplit[0])){ + hmSub = dataMapKey.get(uniqueDataKeySplit[0]); + hmSub.put(uniqueDataKeySplit[1], value); + } + else{ + hmSub=new HashMap <>(); + hmSub.put(uniqueDataKeySplit[1], value); + } + + dataMapKey.put(uniqueDataKeySplit[0], hmSub); + } + + JSONObject mainObject= new JSONObject(); + JSONObject json; + for(Map.Entry> entry: dataMapKey.entrySet()){ + String s=entry.getKey(); + json= new JSONObject(); + HashMap jsonHm=dataMapKey.get(s); + for(Map.Entry entryMap:jsonHm.entrySet()){ + String key=entryMap.getKey(); + json.put(key, jsonHm.get(key)); + } + mainObject.put(s,json); + } + Iterator keysItr = mainObject.keys(); + while(keysItr.hasNext()) { + String key = keysItr.next(); + String value = mainObject.get(key).toString(); + retmap.put(key, value); + } + + LOGGER.info("#############################################################################"); + LOGGER.info(mainObject); + LOGGER.info("###############################################################################"); + } + + + HashMap> parsePolicyNodes(Map map){ + HashMap> mapKey= new HashMap <>(); + for(String uniqueKey: uniqueKeys){ + HashMap hm; + + for(Map.Entry entry:map.entrySet()){ + String key=entry.getKey(); + if(key.contains(uniqueKey) && key.contains("policy.nodes")){ + if(mapKey.containsKey(uniqueKey)){ + hm = mapKey.get(uniqueKey); + String keyStr= key.substring(key.lastIndexOf('.')+1); + String valueStr= map.get(key); + if(("type").equals(keyStr)){ + if(!key.contains("entry_schema")) + { + hm.put(keyStr,valueStr); + } + }else{ + hm.put(keyStr,valueStr); + } + + } else { + hm = new HashMap <>(); + String keyStr= key.substring(key.lastIndexOf('.')+1); + String valueStr= map.get(key); + if(("type").equals(keyStr)){ + if(!key.contains("entry_schema")) + { + hm.put(keyStr,valueStr); + } + }else{ + hm.put(keyStr,valueStr); + } + mapKey.put(uniqueKey, hm); + } + } + } + } + return mapKey; + } + + void createAttributes(HashMap> mapKey){ + StringBuilder attributeStringBuilder= new StringBuilder(); + StringBuilder referenceStringBuilder= new StringBuilder(); + StringBuilder listBuffer= new StringBuilder(); + List constraints= new ArrayList<>(); + for(Map.Entry> entry: mapKey.entrySet()){ + String keySetString= entry.getKey(); + HashMap keyValues=mapKey.get(keySetString); + if(keyValues.get("type").equalsIgnoreCase(STRING)|| + keyValues.get("type").equalsIgnoreCase(INTEGER) + ){ + StringBuilder attributeIndividualStringBuilder= new StringBuilder(); + attributeIndividualStringBuilder.append(keySetString+"="); + attributeIndividualStringBuilder.append(keyValues.get("type")+":defaultValue-"); + attributeIndividualStringBuilder.append(keyValues.get("default")+":required-"); + attributeIndividualStringBuilder.append(keyValues.get("required")+":MANY-false"); + attributeStringBuilder.append(attributeIndividualStringBuilder+","); + + } + else if(keyValues.get("type").equalsIgnoreCase(LIST)){ + //List Datatype + Set keys= keyValues.keySet(); + Iterator itr=keys.iterator(); + while(itr.hasNext()){ + String key= itr.next(); + if((!("type").equals(key) ||("required").equals(key))) + { + String value= keyValues.get(key); + //The "." in the value determines if its a string or a user defined type. + if (!value.contains(".")){ + //This is string + constraints.add(keyValues.get(key)); + }else{ + //This is userdefined string + String trimValue=value.substring(value.lastIndexOf('.')+1); + StringBuilder referenceIndividualStringBuilder= new StringBuilder(); + referenceIndividualStringBuilder.append(keySetString+"="+trimValue+":MANY-true"); + referenceStringBuilder.append(referenceIndividualStringBuilder+","); + } + } + } + + }else{ + //User defined Datatype. + String value=keyValues.get("type"); + String trimValue=value.substring(value.lastIndexOf('.')+1); + StringBuilder referenceIndividualStringBuilder= new StringBuilder(); + referenceIndividualStringBuilder.append(keySetString+"="+trimValue+":MANY-false"); + referenceStringBuilder.append(referenceIndividualStringBuilder+","); + + } + if(constraints!=null &&constraints.isEmpty()==false){ + //List handling. + listBuffer.append(keySetString.toUpperCase()+"=["); + for(String str:constraints){ + listBuffer.append(str+","); + } + listBuffer.append("]#"); + LOGGER.info(listBuffer); + + + StringBuilder referenceIndividualStringBuilder= new StringBuilder(); + referenceIndividualStringBuilder.append(keySetString+"="+keySetString.toUpperCase()+":MANY-false"); + referenceStringBuilder.append(referenceIndividualStringBuilder+","); + constraints.clear(); + } + } + + dataListBuffer.append(listBuffer); + + + LOGGER.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"); + LOGGER.info("Whole attribute String is:"+attributeStringBuilder); + LOGGER.info("Whole reference String is:"+referenceStringBuilder); + LOGGER.info("List String is:"+listBuffer); + LOGGER.info("Data list buffer is:"+dataListBuffer); + LOGGER.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"); + + this.listConstraints=dataListBuffer.toString(); + this.referenceAttributes=referenceStringBuilder.toString(); + this.attributeString=attributeStringBuilder.toString(); + } + + + + public void parseTosca (String fileName){ + Map map= new HashMap<>(); + + try { + map=load(fileName); + + parseDataAndPolicyNodes(map); + + HashMap dataMapForJson=parseDataNodes(map); + + constructJsonForDataFields(dataMapForJson); + + HashMap> mapKey= parsePolicyNodes(map); + + createAttributes(mapKey); + + } catch (IOException e) { + LOGGER.error(e); + } + + } + + private String cleanUPJson(String json) { + String cleanJson = StringUtils.replaceEach(json, new String[]{"\\\\", "\\\\\\", "\\\\\\\\"}, new String[]{"\\", "\\", "\\"}); + cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\\"}, new String[]{"\\"}); + cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\", "[[", "]]"}, new String[]{"\\", "[", "]"}); + + cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\"", "\\\"", "\"[{", "}]\""}, new String[]{"\"", "\"", "[{", "}]"}); + cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[{", "}]\""}, new String[]{"[{", "}]"}); + cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[", "]\""}, new String[]{"[", "]"}); + cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"{", "}\""}, new String[]{"{", "}"}); + cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\"\"", "\"\""}, new String[]{"\"", "\""}); + cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\""}, new String[]{""}); + cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\""}, new String[]{"\""}); + cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\\\\\\"}, new String[]{"\""}); + cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\\\""}, new String[]{"\""}); + cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[", "]\""}, new String[]{"[", "]"}); + return cleanJson; + } + + private JSONObject decodeContent(JsonNode jsonNode){ + Iterator jsonElements = jsonNode.elements(); + Iterator jsonKeys = jsonNode.fieldNames(); + Map element = new TreeMap<>(); + while(jsonElements.hasNext() && jsonKeys.hasNext()){ + element.put(jsonKeys.next(), jsonElements.next().toString()); + } + JSONObject jsonResult = new JSONObject(); + JSONArray jsonArray = null; + String oldValue = null; + String nodeKey = null; + String arryKey = null; + Boolean isArray = false; + JsonNodeFactory nodeFactory = JsonNodeFactory.instance; + ObjectNode node = nodeFactory.objectNode(); + String prevKey = null; + String presKey = null; + for(String key: element.keySet()){ + if(key.contains(".")){ + presKey = key.substring(0,key.indexOf(".")); + }else if(key.contains("@")){ + presKey = key.substring(0,key.indexOf("@")); + }else{ + presKey = key; + } + // first check if we are different from old. + LOGGER.info(key+"\n"); + if(jsonArray!=null && jsonArray.length()>0 && key.contains("@") && !key.contains(".") && oldValue!=null){ + if(!oldValue.equals(key.substring(0,key.indexOf("@")))){ + jsonResult.put(oldValue, jsonArray); + jsonArray = new JSONArray(); + } + }else if(jsonArray!=null && jsonArray.length()>0 && !presKey.equals(prevKey) && oldValue!=null){ + jsonResult.put(oldValue, jsonArray); + isArray = false; + jsonArray = new JSONArray(); + } + + prevKey = presKey; + // + if(key.contains(".")){ + if(nodeKey==null){ + nodeKey = key.substring(0,key.indexOf(".")); + } + if(nodeKey.equals(key.substring(0,key.indexOf(".")))){ + node.put(key.substring(key.indexOf(".")+1), element.get(key)); + }else{ + if(node.size()!=0){ + if(nodeKey.contains("@")){ + if(arryKey==null){ + arryKey = nodeKey.substring(0,nodeKey.indexOf("@")); + } + if(nodeKey.endsWith("@0")){ + isArray = true; + jsonArray = new JSONArray(); + } + if(jsonArray != null && arryKey.equals(nodeKey.substring(0,nodeKey.indexOf("@")))){ + jsonArray.put(decodeContent(node)); + } + if((key.contains("@") && !arryKey.equals(key.substring(0,nodeKey.indexOf("@")))) || !key.contains("@")){ + jsonResult.put(arryKey, jsonArray); + jsonArray = new JSONArray(); + } + arryKey = nodeKey.substring(0,nodeKey.indexOf("@")); + }else{ + isArray = false; + jsonResult.put(nodeKey, decodeContent(node)); + } + node = nodeFactory.objectNode(); + } + nodeKey = key.substring(0,key.indexOf(".")); + if(nodeKey.contains("@")){ + arryKey = nodeKey.substring(0,nodeKey.indexOf("@")); + } + node.put(key.substring(key.indexOf(".")+1), element.get(key)); + } + }else if(node.size()!=0){ + if(nodeKey.contains("@")){ + if(arryKey==null){ + arryKey = nodeKey.substring(0,nodeKey.indexOf("@")); + } + if(nodeKey.endsWith("@0")){ + isArray = true; + jsonArray = new JSONArray(); + } + if(jsonArray != null && arryKey.equals(nodeKey.substring(0,nodeKey.indexOf("@")))){ + jsonArray.put(decodeContent(node)); + } + jsonResult.put(arryKey, jsonArray); + jsonArray = new JSONArray(); + arryKey = nodeKey.substring(0,nodeKey.indexOf("@")); + }else{ + isArray = false; + jsonResult.put(nodeKey, decodeContent(node)); + } + node = nodeFactory.objectNode(); + if(key.contains("@")){ + isArray = true; + if(key.endsWith("@0")|| jsonArray==null){ + jsonArray = new JSONArray(); + } + }else if(!key.contains("@")){ + isArray = false; + } + if(isArray){ + if(oldValue==null){ + oldValue = key.substring(0,key.indexOf("@")); + } + if(oldValue!=prevKey){ + oldValue = key.substring(0,key.indexOf("@")); + } + if(oldValue.equals(key.substring(0,key.indexOf("@")))){ + jsonArray.put(element.get(key)); + }else{ + jsonResult.put(oldValue, jsonArray); + jsonArray = new JSONArray(); + } + oldValue = key.substring(0,key.indexOf("@")); + }else{ + jsonResult.put(key, element.get(key)); + } + }else{ + if(key.contains("@")){ + isArray = true; + if(key.endsWith("@0")|| jsonArray==null){ + jsonArray = new JSONArray(); + } + }else if(!key.contains("@")){ + isArray = false; + } + if(isArray){ + if(oldValue==null){ + oldValue = key.substring(0,key.indexOf("@")); + } + if(oldValue!=prevKey){ + oldValue = key.substring(0,key.indexOf("@")); + } + if(oldValue.equals(key.substring(0,key.indexOf("@")))){ + jsonArray.put(element.get(key)); + }else{ + jsonResult.put(oldValue, jsonArray); + jsonArray = new JSONArray(); + } + oldValue = key.substring(0,key.indexOf("@")); + }else{ + jsonResult.put(key, element.get(key)); + } + } + } + if(node.size()>0){ + if(nodeKey.contains("@")){ + if(jsonArray==null){ + jsonArray = new JSONArray(); + } + if(arryKey==null){ + arryKey = nodeKey.substring(0,nodeKey.indexOf("@")); + } + jsonArray.put(decodeContent(node)); + jsonResult.put(arryKey, jsonArray); + isArray = false;; + }else{ + jsonResult.put(nodeKey, decodeContent(node)); + } + } + if(isArray && jsonArray.length() > 0){ + jsonResult.put(oldValue, jsonArray); + } + return jsonResult; + } + + @RequestMapping(value={"/policyController/getDCAEMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView getDCAEMSTemplateData(HttpServletRequest request, HttpServletResponse response) throws Exception{ + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + + String value = root.get("policyData").toString().replaceAll("^\"|\"$", ""); + String servicename = value.toString().split("-v")[0]; + String version = null; + if (value.toString().contains("-v")){ + version = value.toString().split("-v")[1]; + } + MicroServiceModels returnModel = getAttributeObject(servicename, version); + + String jsonModel = createMicroSeriveJson(returnModel); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + List list = new ArrayList<>(); + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(returnModel); + JSONObject j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + "}"); + list.add(j); + out.write(list.toString()); + return null; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private String createMicroSeriveJson(MicroServiceModels returnModel) { + Map attributeMap = new HashMap<>(); + Map refAttributeMap = new HashMap<>(); + String attribute = returnModel.getAttributes(); + if(attribute != null){ + attribute = attribute.trim(); + } + String refAttribute = returnModel.getRef_attributes(); + if(refAttribute != null){ + refAttribute = refAttribute.trim(); + } + String enumAttribute = returnModel.getEnumValues(); + if(enumAttribute != null){ + enumAttribute = enumAttribute.trim(); + } + if (!StringUtils.isEmpty(attribute)){ + attributeMap = convert(attribute, ","); + } + if (!StringUtils.isEmpty(refAttribute)){ + refAttributeMap = convert(refAttribute, ","); + } + + Gson gson = new Gson(); + + String subAttributes = returnModel.getSub_attributes(); + if(subAttributes != null){ + subAttributes = subAttributes.trim(); + }else{ + subAttributes = ""; + } + Map gsonObject = (Map) gson.fromJson(subAttributes, Object.class); + + JSONObject object = new JSONObject(); + JSONArray array = new JSONArray(); + + for (Entry keySet : attributeMap.entrySet()){ + array = new JSONArray(); + String value = keySet.getValue(); + if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){ + array.put(value); + object.put(keySet.getKey().trim(), array); + }else { + object.put(keySet.getKey().trim(), value.trim()); + } + } + + for (Entry keySet : refAttributeMap.entrySet()){ + array = new JSONArray(); + String value = keySet.getValue().split(":")[0]; + if (gsonObject.containsKey(value)){ + if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){ + array.put(recursiveReference(value, gsonObject, enumAttribute)); + object.put(keySet.getKey().trim(), array); + }else { + object.put(keySet.getKey().trim(), recursiveReference(value, gsonObject, enumAttribute)); + } + }else { + if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){ + array.put(value.trim()); + object.put(keySet.getKey().trim(), array); + }else { + object.put(keySet.getKey().trim(), value.trim()); + } + } + } + + return object.toString(); + } + + @SuppressWarnings("unchecked") + private JSONObject recursiveReference(String name, Map subAttributeMap, String enumAttribute) { + JSONObject object = new JSONObject(); + Map map = new HashMap<>(); + Object returnClass = subAttributeMap.get(name); + map = (Map) returnClass; + JSONArray array = new JSONArray(); + + for( Entry m:map.entrySet()){ + String[] splitValue = m.getValue().split(":"); + array = new JSONArray(); + if (subAttributeMap.containsKey(splitValue[0])){ + if (m.getValue().split("MANY-")[1].equalsIgnoreCase("true")){ + array.put(recursiveReference(splitValue[0], subAttributeMap, enumAttribute)); + object.put(m.getKey().trim(), array); + }else { + object.put(m.getKey().trim(), recursiveReference(splitValue[0], subAttributeMap, enumAttribute)); + } + } else{ + if (m.getValue().split("MANY-")[1].equalsIgnoreCase("true")){ + array.put(splitValue[0].trim()); + object.put(m.getKey().trim(), array); + }else { + object.put(m.getKey().trim(), splitValue[0].trim()); + } + } + } + + return object; + } + + + @RequestMapping(value={"/policyController/getModelServiceVersioneData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response) throws Exception{ + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + + String value = root.get("policyData").toString().replaceAll("^\"|\"$", ""); + String servicename = value.toString().split("-v")[0]; + Set returnList = getVersionList(servicename); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + List list = new ArrayList<>(); + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(returnList); + JSONObject j = new JSONObject("{dcaeModelVersionData: " + responseString +"}"); + list.add(j); + out.write(list.toString()); + return null; + } + + private Set getVersionList(String name) { + MicroServiceModels workingModel = new MicroServiceModels(); + Set list = new HashSet<>(); + List microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name); + for (int i = 0; i < microServiceModelsData.size(); i++) { + workingModel = (MicroServiceModels) microServiceModelsData.get(i); + if (workingModel.getVersion()!=null){ + list.add(workingModel.getVersion()); + }else{ + list.add("Default"); + } + } + return list; + } + + private MicroServiceModels getAttributeObject(String name, String version) { + MicroServiceModels workingModel = new MicroServiceModels(); + List microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name); + for (int i = 0; i < microServiceModelsData.size(); i++) { + workingModel = (MicroServiceModels) microServiceModelsData.get(i); + if(version != null){ + if (workingModel.getVersion()!=null){ + if (workingModel.getVersion().equals(version)){ + return workingModel; + } + }else{ + return workingModel; + } + }else{ + return workingModel; + } + + } + return workingModel; + } + + @RequestMapping(value={"/get_DCAEPriorityValues"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getDCAEPriorityValuesData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + List priorityList = new ArrayList<>(); + priorityCount = 10; + for (int i = 1; i < priorityCount; i++) { + priorityList.add(String.valueOf(i)); + } + model.put("priorityDatas", mapper.writeValueAsString(priorityList)); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(e); + } + } + + public void prePopulateDCAEMSPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + if (policyAdapter.getPolicyData() instanceof PolicyType) { + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("MS_") +3); + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try{ + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + }catch(Exception e){ + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + // Get the target data under policy. + TargetType target = policy.getTarget(); + if (target != null) { + // Under target we have AnyOFType + List anyOfList = target.getAnyOf(); + if (anyOfList != null) { + Iterator iterAnyOf = anyOfList.iterator(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + // Under AnyOFType we have AllOFType + List allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator iterAllOf = allOfList.iterator(); + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + // Under AllOFType we have Match + List matchList = allOf.getMatch(); + if (matchList != null) { + Iterator iterMatch = matchList.iterator(); + while (matchList.size()>1 && iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attribute value and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + // First match in the target is OnapName, so set that value. + if (attributeId.equals("ONAPName")) { + policyAdapter.setOnapName(value); + } + if (attributeId.equals("ConfigName")){ + policyAdapter.setConfigName(value); + } + if (attributeId.equals("uuid")){ + policyAdapter.setUuid(value); + } + if (attributeId.equals("location")){ + policyAdapter.setLocation(value); + } + if (attributeId.equals("RiskType")){ + policyAdapter.setRiskType(value); + } + if (attributeId.equals("RiskLevel")){ + policyAdapter.setRiskLevel(value); + } + if (attributeId.equals("guard")){ + policyAdapter.setGuard(value); + } + if (attributeId.equals("TTLDate") && !value.contains("NA")){ + String newDate = convertDate(value, true); + policyAdapter.setTtlDate(newDate); + } + } + readFile(policyAdapter, entity); + } + } + } + } + } + } + } + } + + private String convertDate(String dateTTL, boolean portalType) { + String formateDate = null; + String[] date = dateTTL.split("T"); + String[] parts = date[0].split("-"); + + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + return formateDate; + } + + public static Map convert(String str, String split) { + Map map = new HashMap<>(); + for(final String entry : str.split(split)) { + String[] parts = entry.split("="); + map.put(parts[0], parts[1]); + } + return map; + } + + + @SuppressWarnings("unchecked") + private void readFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + String policyScopeName = null; + ObjectMapper mapper = new ObjectMapper(); + try { + DCAEMicroServiceObject msBody = (DCAEMicroServiceObject) mapper.readValue(entity.getConfigurationData().getConfigBody(), DCAEMicroServiceObject.class); + policyScopeName = getPolicyScope(msBody.getPolicyScope()); + policyAdapter.setPolicyScope(policyScopeName); + + policyAdapter.setPriority(msBody.getPriority()); + + if (msBody.getVersion()!= null){ + policyAdapter.setServiceType(msBody.getService()); + policyAdapter.setVersion(msBody.getVersion()); + }else{ + policyAdapter.setServiceType(msBody.getService()); + } + if(msBody.getContent() != null){ + LinkedHashMap data = new LinkedHashMap<>(); + LinkedHashMap map = (LinkedHashMap) msBody.getContent(); + readRecursivlyJSONContent(map, data); + policyAdapter.setRuleData(data); + } + + } catch (Exception e) { + LOGGER.error(e); + } + + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + private void readRecursivlyJSONContent(LinkedHashMap map, LinkedHashMap data){ + for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) { + Object key = iterator.next(); + Object value = map.get(key); + if(value instanceof LinkedHashMap){ + LinkedHashMap secondObjec = new LinkedHashMap<>(); + readRecursivlyJSONContent((LinkedHashMap) value, secondObjec); + for(String objKey: secondObjec.keySet()){ + data.put(key+"." +objKey, secondObjec.get(objKey)); + } + }else if(value instanceof ArrayList){ + ArrayList jsonArrayVal = (ArrayList)value; + for(int i = 0; i < jsonArrayVal.size(); i++){ + Object arrayvalue = jsonArrayVal.get(i); + if(arrayvalue instanceof LinkedHashMap){ + LinkedHashMap newData = new LinkedHashMap<>(); + readRecursivlyJSONContent((LinkedHashMap) arrayvalue, newData); + for(String objKey: newData.keySet()){ + data.put(key+"@"+i+"." +objKey, newData.get(objKey)); + } + }else if(arrayvalue instanceof ArrayList){ + ArrayList jsonArrayVal1 = (ArrayList)value; + for(int j = 0; j < jsonArrayVal1.size(); j++){ + Object arrayvalue1 = jsonArrayVal1.get(i); + data.put(key+"@"+j, arrayvalue1.toString()); + } + }else{ + data.put(key+"@"+i, arrayvalue.toString()); + } + } + }else{ + data.put(key.toString(), value.toString()); + } + } + } + + private String getPolicyScope(String value) { + List groupList= commonClassDao.getDataById(GroupPolicyScopeList.class, "groupList", value); + if(groupList != null && !groupList.isEmpty()){ + GroupPolicyScopeList pScope = (GroupPolicyScopeList) groupList.get(0); + return pScope.getGroupName(); + } + return null; + } + + //Convert the map values and set into JSON body + public Map convertMap(Map attributesMap, Map attributesRefMap) { + Map attribute = new HashMap<>(); + String temp = null; + String key; + String value; + for (Entry entry : attributesMap.entrySet()) { + key = entry.getKey(); + value = entry.getValue(); + attribute.put(key, value); + } + for (Entry entryRef : attributesRefMap.entrySet()) { + key = entryRef.getKey(); + value = entryRef.getValue().toString(); + attribute.put(key, value); + } + for (Entry entryList : attributesListRefMap.entrySet()) { + key = entryList.getKey(); + value = entryList.getValue().toString(); + attribute.put(key, value); + } + for (Entry> arrayList : arrayTextList.entrySet()){ + key = arrayList.getKey(); + temp = null; + for (Object textList : arrayList.getValue()){ + if (temp == null){ + temp = "[" + textList; + }else{ + temp = temp + "," + textList; + } + } + attribute.put(key, temp+ "]"); + } + + return attribute; + } + + @RequestMapping(value={"/ms_dictionary/set_MSModelData"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public void SetMSModelData(HttpServletRequest request, HttpServletResponse response) throws Exception{ + List items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); + boolean zip = false; + boolean yml= false; + for (FileItem item : items) { + if(item.getName().endsWith(".zip") || item.getName().endsWith(".xmi")||item.getName().endsWith(".yml")){ + this.newModel = new MicroServiceModels(); + try{ + File file = new File(item.getName()); + OutputStream outputStream = new FileOutputStream(file); + IOUtils.copy(item.getInputStream(), outputStream); + outputStream.close(); + this.newFile = file.toString(); + this.newModel.setModelName(this.newFile.toString().split("-v")[0]); + + if (this.newFile.toString().contains("-v")){ + if (item.getName().endsWith(".zip")){ + this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".zip", "")); + zip = true; + }else if(item.getName().endsWith(".yml")){ + this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".yml", "")); + yml = true; + } + else { + this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".xmi", "")); + } + } + + }catch(Exception e){ + LOGGER.error("Upload error : " + e); + } + } + + } + List fileList = new ArrayList<>();; + this.directory = "model"; + if (zip){ + extractFolder(this.newFile); + fileList = listModelFiles(this.directory); + }else if (yml==true){ + parseTosca(this.newFile); + }else { + File file = new File(this.newFile); + fileList.add(file); + } + String modelType= ""; + if(yml==false){ + modelType="xmi"; + //Process Main Model file first + classMap = new HashMap<>(); + for (File file : fileList) { + if(!file.isDirectory() && file.getName().endsWith(".xmi")){ + retreiveDependency(file.toString(), true); + } + } + + modelList = createList(); + + cleanUp(this.newFile); + cleanUp(directory); + }else{ + modelType="yml"; + modelList.add(this.newModel.getModelName()); + String className=this.newModel.getModelName(); + MSAttributeObject msAttributes= new MSAttributeObject(); + msAttributes.setClassName(className); + + HashMap returnAttributeList =new HashMap<>(); + returnAttributeList.put(className, this.attributeString); + msAttributes.setAttribute(returnAttributeList); + + msAttributes.setSubClass(this.retmap); + + HashMap returnReferenceList =new HashMap<>(); + //String[] referenceArray=this.referenceAttributes.split("="); + returnReferenceList.put(className, this.referenceAttributes); + msAttributes.setRefAttribute(returnReferenceList); + + if(this.listConstraints!=""){ + HashMap enumList =new HashMap<>(); + String[] listArray=this.listConstraints.split("#"); + for(String str:listArray){ + String[] strArr= str.split("="); + if(strArr.length>1){ + enumList.put(strArr[0], strArr[1]); + } + } + msAttributes.setEnumType(enumList); + } + + classMap=new HashMap<>(); + classMap.put(className, msAttributes); + + } + + PrintWriter out = response.getWriter(); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + ObjectMapper mapper = new ObjectMapper(); + JSONObject j = new JSONObject(); + j.put("classListDatas", modelList); + j.put("modelDatas", mapper.writeValueAsString(classMap)); + j.put("modelType", modelType); + out.write(j.toString()); + } + + /* + * Unzip file and store in the model directory for processing + */ + @SuppressWarnings("rawtypes") + private void extractFolder(String zipFile ) { + int BUFFER = 2048; + File file = new File(zipFile); + + ZipFile zip = null; + try { + zip = new ZipFile(file); + String newPath = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4); + this.directory = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4); + checkZipDirectory(this.directory); + new File(newPath).mkdir(); + Enumeration zipFileEntries = zip.entries(); + + // Process each entry + while (zipFileEntries.hasMoreElements()){ + // grab a zip file entry + ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); + String currentEntry = entry.getName(); + File destFile = new File("model" + File.separator + currentEntry); + File destinationParent = destFile.getParentFile(); + + destinationParent.mkdirs(); + + if (!entry.isDirectory()){ + BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry)); + int currentByte; + byte data[] = new byte[BUFFER]; + FileOutputStream fos = new FileOutputStream(destFile); + BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER); + while ((currentByte = is.read(data, 0, BUFFER)) != -1) { + dest.write(data, 0, currentByte); + } + dest.flush(); + dest.close(); + is.close(); + } + + if (currentEntry.endsWith(".zip")){ + extractFolder(destFile.getAbsolutePath()); + } + } + } catch (IOException e) { + LOGGER.error("Failed to unzip model file " + zipFile); + }finally{ + try { + if(zip != null) + zip.close(); + } catch (IOException e) { + LOGGER.error("Exception Occured While closing zipfile " + e); + } + } + } + + private void retreiveDependency(String workingFile, Boolean modelClass) { + + MSModelUtils utils = new MSModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName()); + HashMap tempMap = new HashMap<>(); + + tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI); + + classMap.putAll(tempMap); + LOGGER.info(tempMap); + + return; + + } + + private List listModelFiles(String directoryName) { + File directory = new File(directoryName); + List resultList = new ArrayList<>(); + File[] fList = directory.listFiles(); + for (File file : fList) { + if (file.isFile()) { + resultList.add(file); + } else if (file.isDirectory()) { + dirDependencyList.add(file.getName()); + resultList.addAll(listModelFiles(file.getAbsolutePath())); + } + } + return resultList; + } + + private void cleanUp(String path) { + if (path!=null){ + try { + FileUtils.forceDelete(new File(path)); + } catch (IOException e) { + LOGGER.error("Failed to delete folder " + path); + } + } + } + + private void checkZipDirectory(String zipDirectory) { + Path path = Paths.get(zipDirectory); + + if (Files.exists(path)) { + cleanUp(zipDirectory); + } + } + + private List createList() { + List list = new ArrayList<>(); + for (Entry cMap : classMap.entrySet()){ + if (cMap.getValue().isPolicyTempalate()){ + list.add(cMap.getKey()); + } + + } + + if (list.isEmpty()){ + if (classMap.containsKey(this.newModel.getModelName())){ + list.add(this.newModel.getModelName()); + }else { + list.add("EMPTY"); + } + } + return list; + } + + public Map getAttributesListRefMap() { + return attributesListRefMap; + } + + public Map> getArrayTextList() { + return arrayTextList; + } + +} + +class DCAEMicroServiceObject { + + private String service; + private String location; + private String uuid; + private String policyName; + private String description; + private String configName; + private String templateVersion; + private String version; + private String priority; + private String policyScope; + private String riskType; + private String riskLevel; + private String guard = null; + + public String getGuard() { + return guard; + } + public void setGuard(String guard) { + this.guard = guard; + } + public String getRiskType() { + return riskType; + } + public void setRiskType(String riskType) { + this.riskType = riskType; + } + public String getRiskLevel() { + return riskLevel; + } + public void setRiskLevel(String riskLevel) { + this.riskLevel = riskLevel; + } + public String getPolicyScope() { + return policyScope; + } + public void setPolicyScope(String policyScope) { + this.policyScope = policyScope; + } + + public String getPriority() { + return priority; + } + public void setPriority(String priority) { + this.priority = priority; + } + public String getVersion() { + return version; + } + public void setVersion(String version) { + this.version = version; + } + private Object content; + + + public String getPolicyName() { + return policyName; + } + public void setPolicyName(String policyName) { + this.policyName = policyName; + } + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } + public String getConfigName() { + return configName; + } + public void setConfigName(String configName) { + this.configName = configName; + } + public Object getContent() { + return content; + } + public void setContent(Object content) { + this.content = content; + } + + public String getService() { + return service; + } + public void setService(String service) { + this.service = service; + } + public String getLocation() { + return location; + } + public void setLocation(String location) { + this.location = location; + } + + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + public String getTemplateVersion() { + return templateVersion; + } + public void setTemplateVersion(String templateVersion) { + this.templateVersion = templateVersion; + } + +} \ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java new file mode 100644 index 000000000..828bc3886 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java @@ -0,0 +1,929 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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 java.io.PrintWriter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.hibernate.SessionFactory; +import org.json.JSONObject; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.adapter.AddressGroupJson; +import org.onap.policy.rest.adapter.AddressJson; +import org.onap.policy.rest.adapter.AddressMembers; +import org.onap.policy.rest.adapter.DeployNowJson; +import org.onap.policy.rest.adapter.IdMap; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.adapter.PrefixIPList; +import org.onap.policy.rest.adapter.ServiceGroupJson; +import org.onap.policy.rest.adapter.ServiceListJson; +import org.onap.policy.rest.adapter.ServiceMembers; +import org.onap.policy.rest.adapter.ServicesJson; +import org.onap.policy.rest.adapter.TagDefines; +import org.onap.policy.rest.adapter.Tags; +import org.onap.policy.rest.adapter.Term; +import org.onap.policy.rest.adapter.TermCollector; +import org.onap.policy.rest.adapter.VendorSpecificData; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.AddressGroup; +import org.onap.policy.rest.jpa.FWTagPicker; +import org.onap.policy.rest.jpa.GroupServiceList; +import org.onap.policy.rest.jpa.PolicyEntity; +import org.onap.policy.rest.jpa.PrefixList; +import org.onap.policy.rest.jpa.SecurityZone; +import org.onap.policy.rest.jpa.ServiceList; +import org.onap.policy.rest.jpa.TermList; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + +@Controller +@RequestMapping("/") +public class CreateFirewallController extends RestrictedBaseController { + private static Logger policyLogger = FlexLogger.getLogger(CreateFirewallController.class); + + @Autowired + SessionFactory sessionFactory; + + private static CommonClassDao commonClassDao; + + private List tagCollectorList; + private String jsonBody; + List expandablePrefixIPList = new ArrayList<>(); + List expandableServicesList= new ArrayList<>(); + @Autowired + private CreateFirewallController(CommonClassDao commonClassDao){ + CreateFirewallController.commonClassDao = commonClassDao; + } + + public CreateFirewallController(){} + private List termCollectorList; + private ArrayList attributeList; + + + public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData){ + + termCollectorList = new ArrayList<>(); + tagCollectorList = new ArrayList<>(); + if(!policyData.getAttributes().isEmpty()){ + for(Object attribute : policyData.getAttributes()){ + if(attribute instanceof LinkedHashMap){ + String key = ((LinkedHashMap) attribute).get("key").toString(); + termCollectorList.add(key); + + String tag = ((LinkedHashMap) attribute).get("value").toString(); + tagCollectorList.add(tag); + } + } + } + jsonBody = constructJson(policyData); + if (jsonBody != null && !jsonBody.equalsIgnoreCase("")) { + policyData.setJsonBody(jsonBody); + } else { + policyData.setJsonBody("{}"); + } + policyData.setJsonBody(jsonBody); + + return policyData; + } + + private List mapping(String expandableList) { + List valueDesc= new ArrayList<>(); + List prefixListData = commonClassDao.getData(PrefixList.class); + for (int i = 0; i< prefixListData.size(); i++) { + PrefixList prefixList = (PrefixList) prefixListData.get(i); + if (prefixList.getPrefixListName().equals(expandableList)) { + String value = prefixList.getPrefixListValue(); + valueDesc.add(value); + String desc= prefixList.getDescription(); + valueDesc.add(desc); + break; + } + } + return valueDesc; + } + + private ServiceList mappingServiceList(String expandableList) { + ServiceList serviceList=null; + List serviceListData = commonClassDao.getData(ServiceList.class); + for (int i = 0; i< serviceListData.size(); i++) { + serviceList = (ServiceList) serviceListData.get(i); + if (serviceList.getServiceName().equals(expandableList)) { + break; + } + } + return serviceList; + } + + private GroupServiceList mappingServiceGroup(String expandableList) { + + GroupServiceList serviceGroup=null; + List serviceGroupData = commonClassDao.getData(GroupServiceList.class); + for (int i = 0; i< serviceGroupData.size(); i++) { + serviceGroup = (GroupServiceList) serviceGroupData.get(i); + if (serviceGroup.getGroupName().equals(expandableList)) { + break; + } + } + return serviceGroup; + } + + private AddressGroup mappingAddressGroup(String expandableList) { + + AddressGroup addressGroup=null; + List addressGroupData = commonClassDao.getData(AddressGroup.class); + for (int i = 0; i< addressGroupData.size(); i++) { + addressGroup = (AddressGroup) addressGroupData.get(i); + if (addressGroup.getGroupName().equals(expandableList)) { + break; + } + } + return addressGroup; + } + + public void prePopulateFWPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + attributeList = new ArrayList<>(); + if (policyAdapter.getPolicyData() instanceof PolicyType) { + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; + // policy name value is the policy name without any prefix and Extensions. + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("FW_") +3); + if (policyLogger.isDebugEnabled()) { + policyLogger.debug("Prepopulating form data for Config Policy selected:"+ policyAdapter.getPolicyName()); + } + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try{ + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + }catch(Exception e){ + policyLogger.info("General error", e); + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + + ObjectMapper mapper = new ObjectMapper(); + + TermCollector tc1=null; + try { + //Json conversion. + String data=null; + SecurityZone jpaSecurityZone; + data = entity.getConfigurationData().getConfigBody(); + tc1 = (TermCollector)mapper.readValue(data, TermCollector.class); + List securityZoneData = commonClassDao.getData(SecurityZone.class); + for (int i = 0; i < securityZoneData.size() ; i++) { + jpaSecurityZone = (SecurityZone) securityZoneData.get(i); + if (jpaSecurityZone.getZoneValue().equals(tc1.getSecurityZoneId())){ + policyAdapter.setSecurityZone(jpaSecurityZone.getZoneName()); + break; + } + } + } + catch(Exception e) { + policyLogger.error("Exception Caused while Retriving the JSON body data" +e); + } + + Map termTagMap=null; + if(tc1 != null){ + for(int i=0;i(); + String ruleName= tc1.getFirewallRuleList().get(i).getRuleName(); + String tagPickerName=tc1.getRuleToTag().get(i).getTagPickerName(); + termTagMap.put("key", ruleName); + termTagMap.put("value", tagPickerName); + attributeList.add(termTagMap); + } + } + policyAdapter.setAttributes(attributeList); + // Get the target data under policy. + TargetType target = policy.getTarget(); + if (target != null) { + // Under target we have AnyOFType + List anyOfList = target.getAnyOf(); + if (anyOfList != null) { + Iterator iterAnyOf = anyOfList.iterator(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + // Under AnyOFType we have AllOFType + List allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator iterAllOf = allOfList.iterator(); + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + // Under AllOFType we have Match + List matchList = allOf.getMatch(); + if (matchList != null) { + + Iterator iterMatch = matchList.iterator(); + while (iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attribute value and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + if (attributeId.equals("ConfigName")) { + policyAdapter.setConfigName(value); + } + if (attributeId.equals("RiskType")){ + policyAdapter.setRiskType(value); + } + if (attributeId.equals("RiskLevel")){ + policyAdapter.setRiskLevel(value); + } + if (attributeId.equals("guard")){ + policyAdapter.setGuard(value); + } + if (attributeId.equals("TTLDate") && !value.contains("NA")){ + String newDate = convertDate(value, true); + policyAdapter.setTtlDate(newDate); + } + } + } + } + } + } + } + } + } + } + + private String convertDate(String dateTTL, boolean portalType) { + String formateDate = null; + String[] date; + String[] parts; + + if (portalType){ + parts = dateTTL.split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z"; + } else { + date = dateTTL.split("T"); + parts = date[0].split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + } + return formateDate; + } + + @RequestMapping(value={"/policyController/ViewFWPolicyRule.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public void setFWViewRule(HttpServletRequest request, HttpServletResponse response){ + try { + termCollectorList = new ArrayList<>(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyRestAdapter policyData = (PolicyRestAdapter)mapper.readValue(root.get("policyData").toString(), PolicyRestAdapter.class); + if(!policyData.getAttributes().isEmpty()){ + for(Object attribute : policyData.getAttributes()){ + if(attribute instanceof LinkedHashMap){ + String key = ((LinkedHashMap) attribute).get("key").toString(); + termCollectorList.add(key); + } + } + } + TermList jpaTermList; + String ruleSrcList=null; + String ruleDestList=null; + String ruleSrcPort=null; + String ruleDestPort=null; + String ruleAction=null; + List valueDesc= new ArrayList<>(); + StringBuffer displayString = new StringBuffer(); + for (String id : termCollectorList) { + List tmList = commonClassDao.getDataById(TermList.class, "termName", id); + jpaTermList = (TermList) tmList.get(0); + if (jpaTermList != null){ + ruleSrcList= ((TermList) jpaTermList).getSrcIPList(); + if ((ruleSrcList!= null) && (!ruleSrcList.isEmpty()) && !ruleSrcList.equals("null")){ + displayString.append("Source IP List: " + ((TermList) jpaTermList).getSrcIPList()); + displayString.append(" ; \t\n"); + for(String srcList:ruleSrcList.split(",")){ + if(srcList.startsWith("Group_")){ + AddressGroup ag= new AddressGroup(); + ag= mappingAddressGroup(srcList); + displayString.append("\n\t"+"Group has :"+ag.getPrefixList()+"\n"); + for(String groupItems:ag.getPrefixList().split(",")){ + valueDesc=mapping(groupItems); + displayString.append("\n\t"+"Name: "+groupItems); + if(!valueDesc.isEmpty()){ + displayString.append("\n\t"+"Description: "+valueDesc.get(1)); + displayString.append("\n\t"+"Value: "+valueDesc.get(0)); + } + displayString.append("\n"); + } + }else{ + if(!srcList.equals("ANY")){ + valueDesc=mapping(srcList); + displayString.append("\n\t"+"Name: "+srcList); + displayString.append("\n\t"+"Description: "+valueDesc.get(1)); + displayString.append("\n\t"+"Value: "+valueDesc.get(0)); + displayString.append("\n"); + } + } + } + displayString.append("\n"); + } + ruleDestList= ((TermList) jpaTermList).getDestIPList(); + if ( ruleDestList!= null && (!ruleDestList.isEmpty())&& !ruleDestList.equals("null")){ + displayString.append("Destination IP List: " + ((TermList) jpaTermList).getDestIPList()); + displayString.append(" ; \t\n"); + for(String destList:ruleDestList.split(",")){ + if(destList.startsWith("Group_")){ + AddressGroup ag= new AddressGroup(); + ag= mappingAddressGroup(destList); + displayString.append("\n\t"+"Group has :"+ag.getPrefixList()+"\n"); + for(String groupItems:ag.getPrefixList().split(",")){ + valueDesc=mapping(groupItems); + displayString.append("\n\t"+"Name: "+groupItems); + displayString.append("\n\t"+"Description: "+valueDesc.get(1)); + displayString.append("\n\t"+"Value: "+valueDesc.get(0)); + displayString.append("\n\t"); + } + }else{ + if(!destList.equals("ANY")){ + valueDesc=mapping(destList); + displayString.append("\n\t"+"Name: "+destList); + displayString.append("\n\t"+"Description: "+valueDesc.get(1)); + displayString.append("\n\t"+"Value: "+valueDesc.get(0)); + displayString.append("\n\t"); + } + } + } + displayString.append("\n"); + } + + ruleSrcPort=((TermList) jpaTermList).getSrcPortList(); + if ( ruleSrcPort!= null && (!ruleSrcPort.isEmpty())&& !ruleSrcPort.equals("null")) { + displayString.append("\n"+"Source Port List:" + + ruleSrcPort); + displayString.append(" ; \t\n"); + } + + ruleDestPort= ((TermList) jpaTermList).getDestPortList(); + if (ruleDestPort != null && (!ruleDestPort.isEmpty())&& !ruleDestPort.equals("null")) { + displayString.append("\n"+"Destination Port List:" + + ruleDestPort); + displayString.append(" ; \t\n"); + for(String destServices:ruleDestPort.split(",")){ + if(destServices.startsWith("Group_")){ + GroupServiceList sg= new GroupServiceList(); + sg= mappingServiceGroup(destServices); + displayString.append("\n\t"+"Service Group has :"+sg.getServiceList()+"\n"); + for(String groupItems:sg.getServiceList().split(",")){ + ServiceList sl= new ServiceList(); + sl= mappingServiceList(groupItems); + displayString.append("\n\t"+"Name: "+ + sl.getServiceName()); + displayString.append("\n\t"+"Description: "+ + sl.getServiceDescription()); + displayString.append("\n\t"+"Transport-Protocol: "+ + sl.getServiceTransProtocol()); + displayString.append("\n\t"+"Ports: "+ + sl.getServicePorts()); + displayString.append("\n"); + } + } + else{ + if(!destServices.equals("ANY")){ + ServiceList sl= new ServiceList(); + sl= mappingServiceList(destServices); + displayString.append("\n\t"+"Name: "+ + sl.getServiceName()); + displayString.append("\n\t"+"Description: "+ + sl.getServiceDescription()); + displayString.append("\n\t"+"Transport-Protocol: "+ + sl.getServiceTransProtocol()); + displayString.append("\n\t"+"Ports: "+ + sl.getServicePorts()); + displayString.append("\n"); + } + } + } + displayString.append("\n"); + } + + ruleAction=(jpaTermList).getAction(); + if ( ruleAction!= null && (!ruleAction.isEmpty())) { + displayString.append("\n"+"Action List:" + + ruleAction); + displayString.append(" ; \t\n"); + } + } + } + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(displayString); + JSONObject j = new JSONObject("{policyData: " + responseString + "}"); + out.write(j.toString()); + } catch (Exception e) { + policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + private String constructJson(PolicyRestAdapter policyData) { + int ruleCount=1; + //Maps to assosciate the values read from the TermList dictionary + Map srcIP_map =null; + Map destIP_map=null; + Map srcPort_map =null; + Map destPort_map =null; + Map action_map=null; + Map fromZone_map=null; + Map toZone_map=null; + + String ruleDesc=null; + String ruleFromZone=null; + String ruleToZone=null; + String ruleSrcPrefixList=null; + String ruleDestPrefixList=null; + String ruleSrcPort=null; + String ruleDestPort=null; + String ruleAction=null; + + String json = null; + + + List expandableList = new ArrayList<>(); + TermList jpaTermList; + TermCollector tc = new TermCollector(); + SecurityZone jpaSecurityZone; + List termList = new ArrayList<>(); + + Tags tags=null; + ListtagsList= new ArrayList<>(); + + TagDefines tagDefine= new TagDefines(); + List tagList=null; + ServiceListJson targetSl=null; + int i=0; + try{ + String networkRole=""; + for(String tag:tagCollectorList){ + tags= new Tags(); + List tagListData = commonClassDao.getData(FWTagPicker.class); + for(int tagCounter=0; tagCounter(); + for(String val:tagValues.split("#")) { + int index=val.indexOf(":"); + String keyToStore=val.substring(0,index); + String valueToStore=val.substring(index+1,val.length()); + + tagDefine= new TagDefines(); + tagDefine.setKey(keyToStore); + tagDefine.setValue(valueToStore); + //Add to the collection. + tagList.add(tagDefine); + + } + networkRole=jpaTagPickerList.getNetworkRole(); + break; + } + } + tags.setTags(tagList); + tags.setTagPickerName(tag); + tags.setRuleName(termCollectorList.get(i)); + tags.setNetworkRole(networkRole); + tagsList.add(tags); + i++; + } + tc.setRuleToTag(tagsList); + + for (int tl = 0 ; tl< termCollectorList.size(); tl++) { + expandableList.add(termCollectorList.get(tl)); + Term targetTerm = new Term(); + //targetSl= new ServiceListJson(); + targetTerm.setRuleName(termCollectorList.get(tl)); + List termListData = commonClassDao.getData(TermList.class); + for (int j =0; j < termListData.size(); j++) { + jpaTermList = (TermList) termListData.get(j); + if (jpaTermList.getTermName().equals(termCollectorList.get(tl))){ + ruleDesc=jpaTermList.getTermDescription(); + if ((ruleDesc!=null)&& (!ruleDesc.isEmpty())){ + targetTerm.setDescription(ruleDesc); + } + ruleFromZone=jpaTermList.getFromZone(); + + if ((ruleFromZone != null) && (!ruleFromZone.isEmpty())){ + fromZone_map = new HashMap<>(); + fromZone_map.put(tl, ruleFromZone); + } + ruleToZone=jpaTermList.getToZone(); + + if ((ruleToZone != null) && (!ruleToZone.isEmpty())){ + toZone_map = new HashMap<>(); + toZone_map.put(tl, ruleToZone); + } + ruleSrcPrefixList=jpaTermList.getSrcIPList(); + + if ((ruleSrcPrefixList != null) && (!ruleSrcPrefixList.isEmpty())){ + srcIP_map = new HashMap<>(); + srcIP_map.put(tl, ruleSrcPrefixList); + } + + ruleDestPrefixList= jpaTermList.getDestIPList(); + if ((ruleDestPrefixList != null) && (!ruleDestPrefixList.isEmpty())){ + destIP_map = new HashMap<>(); + destIP_map.put(tl, ruleDestPrefixList); + } + + ruleSrcPort=jpaTermList.getSrcPortList(); + + if (ruleSrcPort != null && (!ruleSrcPort.isEmpty())){ + srcPort_map = new HashMap<>(); + srcPort_map.put(tl, ruleSrcPort); + } + + ruleDestPort= jpaTermList.getDestPortList(); + + if (ruleDestPort!= null && (!jpaTermList.getDestPortList().isEmpty())){ + destPort_map = new HashMap<>(); + destPort_map.put(tl, ruleDestPort); + } + + ruleAction=jpaTermList.getAction(); + + if (( ruleAction!= null) && (!ruleAction.isEmpty())){ + action_map = new HashMap<>(); + action_map.put(tl, ruleAction); + } + } + } + targetTerm.setEnabled(true); + targetTerm.setLog(true); + targetTerm.setNegateSource(false); + targetTerm.setNegateDestination(false); + + if(action_map!=null){ + targetTerm.setAction(action_map.get(tl)); + } + + //FromZone arrays + if(fromZone_map!=null){ + List fromZone= new ArrayList<>(); + for(String fromZoneStr:fromZone_map.get(tl).split(",") ){ + fromZone.add(fromZoneStr); + } + targetTerm.setFromZones(fromZone); + } + + //ToZone arrays + if(toZone_map!=null){ + List toZone= new ArrayList<>(); + for(String toZoneStr:toZone_map.get(tl).split(",") ){ + toZone.add(toZoneStr); + } + targetTerm.setToZones(toZone); + } + + //Destination Services. + if(destPort_map!=null){ + Set destServicesJsonList= new HashSet<>(); + for(String destServices:destPort_map.get(tl).split(",") ){ + ServicesJson destServicesJson= new ServicesJson(); + destServicesJson.setType("REFERENCE"); + if(destServices.equals("ANY")){ + destServicesJson.setName("any"); + destServicesJsonList.add(destServicesJson); + break; + }else{ + if(destServices.startsWith("Group_")){ + destServicesJson.setName(destServices.substring(6,destServices.length())); + } else{ + destServicesJson.setName(destServices); + } + destServicesJsonList.add(destServicesJson); + } + } + targetTerm.setDestServices(destServicesJsonList); + } + //ExpandableServicesList + if((srcPort_map!=null) && (destPort_map!=null)){ + String servicesCollateString = (srcPort_map.get(tl) + "," + destPort_map.get(tl)); + expandableServicesList.add(servicesCollateString); + }else if (srcPort_map!=null){ + expandableServicesList.add(srcPort_map.get(tl)); + }else if (destPort_map!=null){ + expandableServicesList.add(destPort_map.get(tl)); + } + + if(srcIP_map!=null){ + //Source List + List sourceListArrayJson= new ArrayList<>(); + for(String srcList:srcIP_map.get(tl).split(",") ){ + AddressJson srcListJson= new AddressJson(); + if(srcList.equals("ANY")){ + srcListJson.setType("any"); + sourceListArrayJson.add(srcListJson); + break; + }else{ + srcListJson.setType("REFERENCE"); + if(srcList.startsWith("Group_")){ + srcListJson.setName(srcList.substring(6,srcList.length())); + }else{ + srcListJson.setName(srcList); + } + sourceListArrayJson.add(srcListJson); + } + } + targetTerm.setSourceList(sourceListArrayJson); + } + if(destIP_map!=null){ + //Destination List + List destListArrayJson= new ArrayList<>(); + for(String destList:destIP_map.get(tl).split(",")){ + AddressJson destListJson= new AddressJson(); + if(destList.equals("ANY")){ + destListJson.setType("any"); + destListArrayJson.add(destListJson); + break; + }else{ + destListJson.setType("REFERENCE"); + if(destList.startsWith("Group_")){ + destListJson.setName(destList.substring(6,destList.length())); + }else{ + destListJson.setName(destList); + } + destListArrayJson.add(destListJson); + } + } + targetTerm.setDestinationList(destListArrayJson); + } + //ExpandablePrefixIPList + if ((srcIP_map!=null) && (destIP_map!=null)) + { + String collateString = (srcIP_map.get(tl) + "," + destIP_map + .get(tl)); + expandablePrefixIPList.add(collateString); + } + else if(srcIP_map!=null){ + expandablePrefixIPList.add(srcIP_map.get(tl)); + } + else if(destIP_map!=null){ + expandablePrefixIPList.add(destIP_map.get(tl)); + } + termList.add(targetTerm); + targetTerm.setPosition("" + (ruleCount++)); + } + + List securityZoneData = commonClassDao.getData(SecurityZone.class); + for (int j =0 ; j< securityZoneData.size() ; j++){ + jpaSecurityZone = (SecurityZone) securityZoneData.get(j); + if (jpaSecurityZone.getZoneName().equals(policyData.getSecurityZone())){ + tc.setSecurityZoneId(jpaSecurityZone.getZoneValue()); + IdMap idMapInstance= new IdMap(); + idMapInstance.setAstraId(jpaSecurityZone.getZoneValue()); + idMapInstance.setVendorId("deviceGroup:dev"); + + List idMap = new ArrayList(); + idMap.add(idMapInstance); + + VendorSpecificData vendorStructure= new VendorSpecificData(); + vendorStructure.setIdMap(idMap); + tc.setVendorSpecificData(vendorStructure); + break; + } + } + + tc.setServiceTypeId("/v0/firewall/pan"); + tc.setConfigName(policyData.getConfigName()); + tc.setVendorServiceId("vipr"); + + DeployNowJson deployNow= new DeployNowJson(); + deployNow.setDeployNow(false); + + tc.setDeploymentOption(deployNow); + + Set servListArray = new HashSet<>(); + Set servGroupArray= new HashSet<>(); + Set addrGroupArray= new HashSet<>(); + + ServiceGroupJson targetSg= null; + AddressGroupJson addressSg=null; + ServiceListJson targetAny= null; + ServiceListJson targetAnyTcp=null; + ServiceListJson targetAnyUdp=null; + + for(String serviceList:expandableServicesList){ + for(String t: serviceList.split(",")){ + if((!t.startsWith("Group_"))){ + if(!t.equals("ANY")){ + ServiceList sl = new ServiceList(); + targetSl= new ServiceListJson(); + sl= mappingServiceList(t); + targetSl.setName(sl.getServiceName()); + targetSl.setDescription(sl.getServiceDescription()); + targetSl.setTransportProtocol(sl.getServiceTransProtocol()); + targetSl.setType(sl.getServiceType()); + targetSl.setPorts(sl.getServicePorts()); + servListArray.add(targetSl); + }else{ + //Any for destinationServices. + //Add names any, any-tcp, any-udp to the serviceGroup object. + targetAny= new ServiceListJson(); + targetAny.setName("any"); + targetAny.setType("SERVICE"); + targetAny.setTransportProtocol("any"); + targetAny.setPorts("any"); + + servListArray.add(targetAny); + + targetAnyTcp= new ServiceListJson(); + targetAnyTcp.setName("any-tcp"); + targetAnyTcp.setType("SERVICE"); + targetAnyTcp.setTransportProtocol("tcp"); + targetAnyTcp.setPorts("any"); + + servListArray.add(targetAnyTcp); + + targetAnyUdp= new ServiceListJson(); + targetAnyUdp.setName("any-udp"); + targetAnyUdp.setType("SERVICE"); + targetAnyUdp.setTransportProtocol("udp"); + targetAnyUdp.setPorts("any"); + + servListArray.add(targetAnyUdp); + } + }else{//This is a group + GroupServiceList sg= new GroupServiceList(); + targetSg= new ServiceGroupJson(); + sg= mappingServiceGroup(t); + + String name=sg.getGroupName(); + //Removing the "Group_" prepending string before packing the JSON + targetSg.setName(name.substring(6,name.length())); + List servMembersList= new ArrayList<>(); + + for(String groupString: sg.getServiceList().split(",")){ + ServiceMembers serviceMembers= new ServiceMembers(); + serviceMembers.setType("REFERENCE"); + serviceMembers.setName(groupString); + servMembersList.add(serviceMembers); + //Expand the group Name + ServiceList expandGroupSl = new ServiceList(); + targetSl= new ServiceListJson(); + expandGroupSl= mappingServiceList(groupString); + + targetSl.setName(expandGroupSl.getServiceName()); + targetSl.setDescription(expandGroupSl.getServiceDescription()); + targetSl.setTransportProtocol(expandGroupSl.getServiceTransProtocol()); + targetSl.setType(expandGroupSl.getServiceType()); + targetSl.setPorts(expandGroupSl.getServicePorts()); + servListArray.add(targetSl); + } + + targetSg.setMembers(servMembersList); + servGroupArray.add(targetSg); + + } + } + } + + Set prefixIPList = new HashSet<>(); + for(String prefixList:expandablePrefixIPList){ + for(String prefixIP: prefixList.split(",")){ + if((!prefixIP.startsWith("Group_"))){ + if(!prefixIP.equals("ANY")){ + List addMembersList= new ArrayList<>(); + List valueDesc= new ArrayList<>(); + PrefixIPList targetAddressList = new PrefixIPList(); + AddressMembers addressMembers= new AddressMembers(); + targetAddressList.setName(prefixIP); + policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "PrefixList value:"+prefixIP); + valueDesc = mapping(prefixIP); + if(!valueDesc.isEmpty()){ + policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "PrefixList description:"+valueDesc.get(1)); + targetAddressList.setDescription(valueDesc.get(1)); + } + + + addressMembers.setType("SUBNET"); + if(!valueDesc.isEmpty()) { + addressMembers.setValue(valueDesc.get(0)); + } + + addMembersList.add(addressMembers); + + targetAddressList.setMembers(addMembersList); + prefixIPList.add(targetAddressList); + } + } + else{//This is a group + AddressGroup ag= new AddressGroup(); + addressSg= new AddressGroupJson(); + ag= mappingAddressGroup(prefixIP); + + String name=ag.getGroupName(); + //Removing the "Group_" prepending string before packing the JSON + addressSg.setName(name.substring(6,name.length())); + + List addrMembersList= new ArrayList<>(); + for(String groupString: ag.getPrefixList().split(",")){ + List valueDesc= new ArrayList<>(); + AddressMembers addressMembers= new AddressMembers(); + valueDesc= mapping (groupString); + if(valueDesc.size() > 0){ + addressMembers.setValue(valueDesc.get(0)); + } + addressMembers.setType("SUBNET"); + addrMembersList.add(addressMembers); + //Expand the group Name + } + addressSg.setMembers(addrMembersList); + addrGroupArray.add(addressSg); + } + + + } + } + + Set serviceGroup= new HashSet<>(); + + for(Object obj1:servGroupArray){ + serviceGroup.add(obj1); + } + + for(Object obj:servListArray){ + serviceGroup.add(obj); + } + + Set addressGroup= new HashSet<>(); + + for(Object addObj:prefixIPList){ + addressGroup.add(addObj); + } + + for(Object addObj1:addrGroupArray){ + addressGroup.add(addObj1); + } + + tc.setServiceGroups(serviceGroup); + tc.setAddressGroups(addressGroup); + tc.setFirewallRuleList(termList); + + ObjectWriter om = new ObjectMapper().writer(); + try { + json = om.writeValueAsString(tc); + } catch (Exception e) { + policyLogger.error("Exception Occured"+e); + } + + }catch (Exception e) { + policyLogger.error("Exception Occured"+e); + } + + return json; + } + +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java new file mode 100644 index 000000000..9c07876c1 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java @@ -0,0 +1,163 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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 java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.jpa.PolicyEntity; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + +@Controller +@RequestMapping("/") +public class CreatePolicyController extends RestrictedBaseController{ + + protected PolicyRestAdapter policyAdapter = null; + private ArrayList attributeList; + boolean isValidForm = false; + + private String convertDate(String dateTTL, boolean portalType) { + String formateDate = null; + String[] date; + String[] parts; + + if (portalType){ + parts = dateTTL.split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z"; + } else { + date = dateTTL.split("T"); + parts = date[0].split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + } + return formateDate; + } + + public void prePopulateBaseConfigPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + attributeList = new ArrayList<>(); + if (policyAdapter.getPolicyData() instanceof PolicyType) { + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + policyAdapter.setConfigType(entity.getConfigurationData().getConfigType()); + policyAdapter.setConfigBodyData(entity.getConfigurationData().getConfigBody()); + String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("_") + 1); + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try{ + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + }catch(Exception e){ + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + // Get the target data under policy. + TargetType target = policy.getTarget(); + if (target != null) { + // Under target we have AnyOFType + List anyOfList = target.getAnyOf(); + if (anyOfList != null) { + Iterator iterAnyOf = anyOfList.iterator(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + // Under AnyOFType we have AllOFType + List allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator iterAllOf = allOfList.iterator(); + int index = 0; + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + // Under AllOFType we have Match + List matchList = allOf.getMatch(); + if (matchList != null) { + Iterator iterMatch = matchList.iterator(); + while (iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attribute value and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + // First match in the target is OnapName, so set that value. + if (attributeId.equals("ONAPName")) { + policyAdapter.setOnapName(value); + } + if (attributeId.equals("RiskType")){ + policyAdapter.setRiskType(value); + } + if (attributeId.equals("RiskLevel")){ + policyAdapter.setRiskLevel(value); + } + if (attributeId.equals("guard")){ + policyAdapter.setGuard(value); + } + if (attributeId.equals("TTLDate") && !value.contains("NA")){ + String newDate = convertDate(value, true); + policyAdapter.setTtlDate(newDate); + } + if (attributeId.equals("ConfigName")){ + policyAdapter.setConfigName(value); + } + // After Onap and Config it is optional to have attributes, so + // check weather dynamic values or there or not. + if (index >= 7) { + Map attribute = new HashMap<>(); + attribute.put("key", attributeId); + attribute.put("value", value); + attributeList.add(attribute); + } + index++; + } + } + } + } + } + } + + policyAdapter.setAttributes(attributeList); + } + List ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); + for (Object o : ruleList) { + if (o instanceof RuleType) { + // get the condition data under the rule for rule Algorithms. + policyAdapter.setRuleID(((RuleType) o).getRuleId()); + } + } + } + } +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java new file mode 100644 index 000000000..d6d4a2c69 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java @@ -0,0 +1,430 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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 java.io.IOException; +import java.net.MalformedURLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.management.AttributeNotFoundException; +import javax.management.InstanceNotFoundException; +import javax.management.MBeanException; +import javax.management.MalformedObjectNameException; +import javax.management.ObjectName; +import javax.management.ReflectionException; +import javax.management.remote.JMXConnector; +import javax.management.remote.JMXConnectorFactory; +import javax.management.remote.JMXServiceURL; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.onap.policy.dao.SystemLogDbDao; +import org.onap.policy.model.PDPGroupContainer; +import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.dao.CommonClassDao; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +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.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.api.pap.OnapPDP; +import org.onap.policy.xacml.api.pap.OnapPDPGroup; + +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.api.pap.PDP; +import com.att.research.xacml.api.pap.PDPGroup; +import com.att.research.xacml.api.pap.PDPPolicy; +import com.att.research.xacml.util.XACMLProperties; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Controller +@RequestMapping({"/"}) +public class DashboardController extends RestrictedBaseController{ + private static final Logger policyLogger = FlexLogger.getLogger(DashboardController.class); + @Autowired + SystemLogDbDao systemDAO; + + @Autowired + CommonClassDao commonClassDao; + + private int pdpCount; + private PDPGroupContainer pdpConatiner; + private ArrayList pdpStatusData; + private ArrayList papStatusData; + private ArrayList policyActivityData; + + private PolicyController policyController; + public PolicyController getPolicyController() { + return policyController; + } + + public void setPolicyController(PolicyController policyController) { + this.policyController = policyController; + } + + private PolicyController getPolicyControllerInstance(){ + return policyController != null ? getPolicyController() : new PolicyController(); + } + + @RequestMapping(value={"/get_DashboardLoggingData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("availableLoggingDatas", mapper.writeValueAsString(systemDAO.getLoggingData())); + 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); + } + } + + @RequestMapping(value={"/get_DashboardSystemAlertData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getSystemAlertData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("systemAlertsTableDatas", mapper.writeValueAsString(systemDAO.getSystemAlertData())); + 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); + } + } + + @RequestMapping(value={"/get_DashboardPAPStatusData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPAPStatusData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); + addPAPToTable(); + model.put("papTableDatas", mapper.writeValueAsString(papStatusData)); + 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); + } + } + + @RequestMapping(value={"/get_DashboardPDPStatusData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPDPStatusData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); + PolicyController controller = getPolicyControllerInstance(); + this.pdpConatiner = new PDPGroupContainer(controller.getPapEngine()); + addPDPToTable(); + model.put("pdpTableDatas", mapper.writeValueAsString(pdpStatusData)); + 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); + } + } + + @RequestMapping(value={"/get_DashboardPolicyActivityData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPolicyActivityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); + PolicyController controller = getPolicyControllerInstance(); + this.pdpConatiner = new PDPGroupContainer(controller.getPapEngine()); + addPolicyToTable(); + model.put("policyActivityTableDatas", mapper.writeValueAsString(policyActivityData)); + 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); + } + } + + /* + * Add the PAP information to the PAP Table + */ + public void addPAPToTable(){ + papStatusData = new ArrayList<>(); + String papStatus = null; + try { + PolicyController controller = getPolicyControllerInstance(); + Set groups = controller.getPapEngine().getOnapPDPGroups(); + if (groups == null) { + papStatus = "UNKNOWN"; + throw new PAPException("PAP not running"); + }else { + papStatus = "IS_OK"; + } + } catch (PAPException | NullPointerException e1) { + papStatus = "CANNOT_CONNECT"; + policyLogger.error("Error getting PAP status, PAP not responding to requests", e1); + } + String papURL = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); + JSONObject object = new JSONObject(); + object.put("system", papURL); + object.put("status", papStatus); + List data = commonClassDao.getDataByQuery("from PolicyEntity"); + object.put("noOfPolicy", data.size()); + object.put("noOfConnectedTrap", pdpCount); + papStatusData.add(0, object); + } + + /** + * Add PDP Information to the PDP Table + * + */ + public void addPDPToTable(){ + pdpCount = 0; + pdpStatusData = new ArrayList<>(); + long naCount; + long denyCount = 0; + long permitCount = 0; + for (PDPGroup group : this.pdpConatiner.getGroups()){ + for (PDP pdp : group.getPdps()){ + naCount = -1; + if ("UP_TO_DATE".equals(pdp.getStatus().getStatus().toString()) && ((OnapPDP) pdp).getJmxPort() != 0){ + String pdpIpAddress = parseIPSystem(pdp.getId()); + int port = ((OnapPDP) pdp).getJmxPort(); + if (port != 0){ + policyLogger.debug("Getting JMX Response Counts from " + pdpIpAddress + " at JMX port " + port); + naCount = getRequestCounts(pdpIpAddress, port, "pdpEvaluationNA"); + permitCount = getRequestCounts(pdpIpAddress, port, "PdpEvaluationPermit"); + denyCount = getRequestCounts(pdpIpAddress, port, "PdpEvaluationDeny"); + } + } + if (naCount == -1){ + JSONObject object = new JSONObject(); + object.put("id", pdp.getId()); + object.put("name", pdp.getName()); + object.put("groupname", group.getName()); + object.put("status", pdp.getStatus().getStatus().toString()); + object.put("description", pdp.getDescription()); + object.put("permitCount", "NA"); + object.put("denyCount", "NA"); + object.put("naCount", "NA"); + pdpStatusData.add(object); + }else{ + JSONObject object = new JSONObject(); + object.put("id", pdp.getId()); + object.put("name", pdp.getName()); + object.put("groupname", group.getName()); + object.put("status", pdp.getStatus().getStatus().toString()); + object.put("description", pdp.getDescription()); + object.put("permitCount", permitCount); + object.put("denyCount", denyCount); + object.put("naCount", naCount); + pdpStatusData.add(object); + } + pdpCount++; + } + } + } + + private static String parseIPSystem(String line) { + Pattern pattern = Pattern.compile("://(.+?):"); + Matcher ip = pattern.matcher(line); + if (ip.find()) + { + return ip.group(1); + } + return null; + } + + /* + * Contact JMX Connector Sever and return the value of the given jmxAttribute + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + private long getRequestCounts(String host, int port, String jmxAttribute) { + + policyLogger.debug("Create an RMI connector client and connect it to the JMX connector server"); + HashMap map = new HashMap(); + map = null; + JMXConnector jmxConnection; + try { + jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map); + jmxConnection.connect(); + Object o = jmxConnection.getMBeanServerConnection().getAttribute(new ObjectName("PdpRest:type=PdpRestMonitor"), jmxAttribute); + jmxConnection.close(); + policyLogger.debug("pdpEvaluationNA value retreived: " + o); + return (long) o; + } catch (MalformedURLException e) { + policyLogger.error("MalformedURLException for JMX connection" , e); + } catch (IOException e) { + policyLogger.error("Error in reteriving" + jmxAttribute + " from JMX connection", e); + } catch (AttributeNotFoundException e) { + policyLogger.error("AttributeNotFoundException " + jmxAttribute + " for JMX connection", e); + } catch (InstanceNotFoundException e) { + policyLogger.error("InstanceNotFoundException " + host + " for JMX connection", e); + } catch (MalformedObjectNameException e) { + policyLogger.error("MalformedObjectNameException for JMX connection", e); + } catch (MBeanException e) { + policyLogger.error("MBeanException for JMX connection"); + policyLogger.error("Exception Occured"+e); + } catch (ReflectionException e) { + policyLogger.error("ReflectionException for JMX connection", e); + } + + return -1; + } + + private static JMXServiceURL createConnectionURL(String host, int port) throws MalformedURLException{ + return new JMXServiceURL("rmi", "", 0, "/jndi/rmi://" + host + ":" + port + "/jmxrmi"); + } + + + /* + * Add the information to the Policy Table + */ + private void addPolicyToTable() { + policyActivityData = new ArrayList<>(); + String policyID = null; + int policyFireCount = 0; + Map policyMap = new HashMap<>(); + Object policyList = null; + //get list of policy + + for (PDPGroup group : this.pdpConatiner.getGroups()){ + for (PDPPolicy policy : group.getPolicies()){ + try{ + policyMap.put(policy.getPolicyId().replace(" ", ""), policy.getId()); + }catch(Exception e){ + policyLogger.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID+policy.getName() +e); + } + } + + for (PDP pdp : group.getPdps()){ + // Add rows to the Policy Table + policyList = null; + if ("UP_TO_DATE".equals(pdp.getStatus().getStatus().toString()) && ((OnapPDP) pdp).getJmxPort() != 0){ + String pdpIpAddress = parseIPSystem(pdp.getId()); + policyList = getPolicy(pdpIpAddress, ((OnapPDP) pdp).getJmxPort(), "policyCount"); + } + if (policyList != null && policyList.toString().length() > 3){ + String[] splitPolicy = policyList.toString().split(","); + for (String policyKeyValue : splitPolicy){ + policyID = urnPolicyID(policyKeyValue); + policyFireCount = countPolicyID(policyKeyValue); + if (policyID != null ){ + if (policyMap.containsKey(policyID)){ + JSONObject object = new JSONObject(); + object.put("policyId", policyMap.get(policyID)); + object.put("fireCount", policyFireCount); + object.put("system", pdp.getId()); + policyActivityData.add(object); + } + } + } + }else { + if (policyList != null){ + JSONObject object = new JSONObject(); + object.put("policyId", "Unable to retrieve policy information"); + object.put("fireCount", "NA"); + object.put("system", pdp.getId()); + policyActivityData.add(object); + }else{ + JSONObject object = new JSONObject(); + object.put("policyId", "Unable to access PDP JMX Server"); + object.put("fireCount", "NA"); + object.put("system", pdp.getId()); + policyActivityData.add(object); + } + } + } + } + } + + /* + * Contact JMX Connector Sever and return the list of {policy id , count} + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + private Object getPolicy(String host, int port, String jmxAttribute){ + policyLogger.debug("Create an RMI connector client and connect it to the JMX connector server for Policy: " + host); + HashMap map = new HashMap(); + map = null; + JMXConnector jmxConnection; + try { + jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map); + jmxConnection.connect(); + Object o = jmxConnection.getMBeanServerConnection().getAttribute(new ObjectName("PdpRest:type=PdpRestMonitor"), "policyMap"); + jmxConnection.close(); + policyLogger.debug("policyMap value retreived: " + o); + return o; + } catch (MalformedURLException e) { + policyLogger.error("MalformedURLException for JMX connection" , e); + } catch (IOException e) { + policyLogger.error("AttributeNotFoundException for policyMap" , e); + } catch (AttributeNotFoundException e) { + policyLogger.error("AttributeNotFoundException for JMX connection", e); + } catch (InstanceNotFoundException e) { + policyLogger.error("InstanceNotFoundException " + host + " for JMX connection", e); + } catch (MalformedObjectNameException e) { + policyLogger.error("MalformedObjectNameException for JMX connection", e); + } catch (MBeanException e) { + policyLogger.error("MBeanException for JMX connection", e); + policyLogger.error("Exception Occured"+e); + } catch (ReflectionException e) { + policyLogger.error("ReflectionException for JMX connection", e); + } + + return null; + + } + + private static String urnPolicyID(String line){ + String[] splitLine = line.toString().split("="); + String removeSpaces = splitLine[0].replaceAll("\\s+", ""); + return removeSpaces.replace("{", ""); + } + + private static Integer countPolicyID(String line){ + String[] splitLine = line.toString().split("="); + String sCount = splitLine[1].replace("}", ""); + int intCount = Integer.parseInt(sCount); + return intCount; + } + +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java new file mode 100644 index 000000000..45369ce2f --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java @@ -0,0 +1,361 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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 java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import javax.xml.bind.JAXBElement; + +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.adapter.RainyDayParams; +import org.onap.policy.rest.adapter.YAMLParams; +import org.onap.policy.rest.jpa.PolicyEntity; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType; + +@Controller +@RequestMapping("/") +public class DecisionPolicyController extends RestrictedBaseController { + private static final Logger policyLogger = FlexLogger.getLogger(DecisionPolicyController.class); + + public DecisionPolicyController(){} + + protected PolicyRestAdapter policyAdapter = null; + private ArrayList attributeList; + private ArrayList decisionList; + private ArrayList ruleAlgorithmList; + private ArrayList treatmentList = null; + protected LinkedList ruleAlgoirthmTracker; + public static final String FUNCTION_NOT = "urn:oasis:names:tc:xacml:1.0:function:not"; + + @SuppressWarnings("unchecked") + public void prePopulateDecisionPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + attributeList = new ArrayList<>(); + decisionList = new ArrayList<>(); + ruleAlgorithmList = new ArrayList<>(); + treatmentList = new ArrayList<>(); + + if (policyAdapter.getPolicyData() instanceof PolicyType) { + RainyDayParams rainydayParams = new RainyDayParams(); + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("_") + 1); + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try{ + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + }catch(Exception e){ + policyLogger.info("General error", e); + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + // Get the target data under policy for Action. + TargetType target = policy.getTarget(); + if (target != null) { + // under target we have AnyOFType + List anyOfList = target.getAnyOf(); + if (anyOfList != null) { + Iterator iterAnyOf = anyOfList.iterator(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + // Under AntOfType we have AllOfType + List allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator iterAllOf = allOfList.iterator(); + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + // Under AllOfType we have Mathch. + List matchList = allOf.getMatch(); + int index = 0; + if (matchList != null) { + Iterator iterMatch = matchList.iterator(); + while (iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attributevalue and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + // First match in the target is OnapName, so set that value. + if (attributeId.equals("ONAPName")) { + policyAdapter.setOnapName(value); + } + // Component attributes are saved under Target here we are fetching them back. + // One row is default so we are not adding dynamic component at index 0. + if (index >= 1) { + Map attribute = new HashMap<>(); + attribute.put("key", attributeId); + attribute.put("value", value); + attributeList.add(attribute); + } + index++; + } + } + policyAdapter.setAttributes(attributeList); + } + } + } + // Setting rainy day attributes to the parameters object if they exist + boolean rainy = false; + if(!attributeList.isEmpty()) { + for(int i=0; i map = (Map)attributeList.get(i); + if(map.get("key").equals("WorkStep")){ + rainydayParams.setWorkstep(map.get("value")); + rainy=true; + }else if(map.get("key").equals("BB_ID")){ + rainydayParams.setBbid(map.get("value")); + rainy=true; + }else if(map.get("key").equals("ServiceType")){ + rainydayParams.setServiceType(map.get("value")); + rainy=true; + }else if(map.get("key").equals("VNFType")){ + rainydayParams.setVnfType(map.get("value")); + rainy=true; + } + } + } + if(rainy){ + policyAdapter.setRuleProvider("Rainy_Day"); + } + } + + List ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); + int index = 0; + for (Object object : ruleList) { + if (object instanceof VariableDefinitionType) { + VariableDefinitionType variableDefinitionType = (VariableDefinitionType) object; + Map settings = new HashMap<>(); + settings.put("key", variableDefinitionType.getVariableId()); + JAXBElement attributeValueTypeElement = (JAXBElement) variableDefinitionType.getExpression(); + if (attributeValueTypeElement != null) { + AttributeValueType attributeValueType = attributeValueTypeElement.getValue(); + settings.put("value", attributeValueType.getContent().get(0).toString()); + } + decisionList.add(settings); + } else if (object instanceof RuleType) { + // get the condition data under the rule for rule Algorithms. + if(((RuleType) object).getEffect().equals(EffectType.DENY)) { + if(((RuleType) object).getAdviceExpressions()!=null){ + if(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId().toString().equalsIgnoreCase("AAF")){ + policyAdapter.setRuleProvider("AAF"); + break; + }else if(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId().toString().equalsIgnoreCase("GUARD_YAML")){ + policyAdapter.setRuleProvider("GUARD_YAML"); + }else if(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId().toString().equalsIgnoreCase("GUARD_BL_YAML")){ + policyAdapter.setRuleProvider("GUARD_BL_YAML"); + } + }else{ + policyAdapter.setRuleProvider("Custom"); + } + ConditionType condition = ((RuleType) object).getCondition(); + if (condition != null) { + ApplyType decisionApply = (ApplyType) condition.getExpression().getValue(); + decisionApply = (ApplyType) decisionApply.getExpression().get(0).getValue(); + ruleAlgoirthmTracker = new LinkedList<>(); + if(policyAdapter.getRuleProvider()!=null && (policyAdapter.getRuleProvider().equals("GUARD_YAML")||(policyAdapter.getRuleProvider().equals("GUARD_BL_YAML")))){ + YAMLParams yamlParams = new YAMLParams(); + for(int i=0; i map = (Map)attributeList.get(i); + if(map.get("key").equals("actor")){ + yamlParams.setActor(map.get("value")); + }else if(map.get("key").equals("recipe")){ + yamlParams.setRecipe(map.get("value")); + }else if(map.get("key").equals("targets")){ + yamlParams.setTargets(Arrays.asList(map.get("value").split("\\|"))); + }else if(map.get("key").equals("clname")){ + yamlParams.setClname(map.get("value")); + } + } + ApplyType apply = ((ApplyType)((ApplyType)decisionApply.getExpression().get(0).getValue()).getExpression().get(0).getValue()); + yamlParams.setGuardActiveStart(((AttributeValueType)apply.getExpression().get(1).getValue()).getContent().get(0).toString()); + yamlParams.setGuardActiveEnd(((AttributeValueType)apply.getExpression().get(2).getValue()).getContent().get(0).toString()); + if(policyAdapter.getRuleProvider().equals("GUARD_BL_YAML")){ + apply = (ApplyType)((ApplyType)((ApplyType)decisionApply.getExpression().get(0).getValue()).getExpression().get(1).getValue()).getExpression().get(2).getValue(); + Iterator> attributes = apply.getExpression().iterator(); + List blackList = new ArrayList<>(); + while(attributes.hasNext()){ + blackList.add(((AttributeValueType)attributes.next().getValue()).getContent().get(0).toString()); + } + yamlParams.setBlackList(blackList); + }else{ + ApplyType timeWindowSection = (ApplyType)((ApplyType)decisionApply.getExpression().get(0).getValue()).getExpression().get(1).getValue(); + yamlParams.setLimit(((AttributeValueType)timeWindowSection.getExpression().get(1).getValue()).getContent().get(0).toString()); + String timeWindow = ((AttributeDesignatorType)((ApplyType)timeWindowSection.getExpression().get(0).getValue()).getExpression().get(0).getValue()).getIssuer(); + yamlParams.setTimeUnits(timeWindow.substring(timeWindow.lastIndexOf(':')+1)); + yamlParams.setTimeWindow(timeWindow.substring(timeWindow.indexOf(":tw:")+4,timeWindow.lastIndexOf(':'))); + } + policyAdapter.setYamlparams(yamlParams); + policyAdapter.setAttributes(new ArrayList()); + policyAdapter.setRuleAlgorithmschoices(new ArrayList()); + break; + } + // Populating Rule Algorithms starting from compound. + prePopulateDecisionCompoundRuleAlgorithm(index, decisionApply); + policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList); + } + } else if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals("Rainy_Day")&& ((RuleType) object).getEffect().equals(EffectType.PERMIT)) { + + TargetType ruleTarget = ((RuleType) object).getTarget(); + AdviceExpressionsType adviceExpression = ((RuleType) object).getAdviceExpressions(); + + String errorcode = ruleTarget.getAnyOf().get(0).getAllOf().get(0).getMatch(). + get(1).getAttributeValue().getContent().get(0).toString(); + JAXBElement tempTreatmentObj = (JAXBElement) adviceExpression.getAdviceExpression(). + get(0).getAttributeAssignmentExpression().get(0).getExpression(); + String treatment = tempTreatmentObj.getValue().getContent().get(0).toString(); + + prePopulateRainyDayTreatments(errorcode, treatment); + + } + } + } + } + + rainydayParams.setTreatmentTableChoices(treatmentList); + policyAdapter.setRainyday(rainydayParams); + policyAdapter.setSettings(decisionList); + } + + } + + private void prePopulateRainyDayTreatments(String errorcode, String treatment) { + Map ruleMap = new HashMap<>(); + + ruleMap.put("errorcode", errorcode); + ruleMap.put("treatment", treatment); + treatmentList.add(ruleMap); + + } + + private void prePopulateDecisionRuleAlgorithms(int index, ApplyType decisionApply, List> jaxbDecisionTypes) { + Map ruleMap = new HashMap<>(); + ruleMap.put("id", "A" + (index +1)); + Map dropDownMap = PolicyController.getDropDownMap(); + for (String key : dropDownMap.keySet()) { + String keyValue = dropDownMap.get(key); + if (keyValue.equals(decisionApply.getFunctionId())) { + ruleMap.put("dynamicRuleAlgorithmCombo", key); + } + } + // Populate the key and value fields + if (((jaxbDecisionTypes.get(0).getValue()) instanceof AttributeValueType)) { + ApplyType innerDecisionApply = (ApplyType) jaxbDecisionTypes.get(1).getValue(); + List> jaxbInnerDecisionTypes = innerDecisionApply.getExpression(); + if (jaxbInnerDecisionTypes.get(0).getValue() instanceof AttributeDesignatorType) { + AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerDecisionTypes.get(0).getValue(); + ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId()); + + // Get from Attribute Value + AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbDecisionTypes.get(0).getValue(); + String attributeValue = (String) actionConditionAttributeValue.getContent().get(0); + ruleMap.put("dynamicRuleAlgorithmField2", attributeValue); + } + } else if ((jaxbDecisionTypes.get(0).getValue()) instanceof VariableReferenceType) { + VariableReferenceType variableReference = (VariableReferenceType) jaxbDecisionTypes.get(0).getValue(); + ruleMap.put("dynamicRuleAlgorithmField1", "S_"+ variableReference.getVariableId()); + + + // Get from Attribute Value + AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbDecisionTypes.get(1).getValue(); + String attributeValue = (String) actionConditionAttributeValue.getContent().get(0); + ruleMap.put("dynamicRuleAlgorithmField2", attributeValue); + } + ruleAlgorithmList.add(ruleMap); + } + + private int prePopulateDecisionCompoundRuleAlgorithm(int index, ApplyType decisionApply) { + boolean isCompoundRule = true; + List> jaxbDecisionTypes = decisionApply.getExpression(); + for (JAXBElement jaxbElement : jaxbDecisionTypes) { + // If There is Attribute Value under Decision Type that means we came to the final child + if (policyLogger.isDebugEnabled()) { + policyLogger.debug("Prepopulating rule algoirthm: " + index); + } + // Check to see if Attribute Value exists, if yes then it is not a compound rule + if(jaxbElement.getValue() instanceof AttributeValueType) { + prePopulateDecisionRuleAlgorithms(index, decisionApply, jaxbDecisionTypes); + ruleAlgoirthmTracker.addLast(index); + isCompoundRule = false; + index++; + } + } + if (isCompoundRule) { + // As it's compound rule, Get the Apply types + for (JAXBElement jaxbElement : jaxbDecisionTypes) { + ApplyType innerDecisionApply = (ApplyType) jaxbElement.getValue(); + index = prePopulateDecisionCompoundRuleAlgorithm(index, innerDecisionApply); + } + // Populate combo box + if (policyLogger.isDebugEnabled()) { + policyLogger.debug("Prepopulating Compound rule algorithm: " + index); + } + Map rule = new HashMap<>(); + for (String key : PolicyController.getDropDownMap().keySet()) { + String keyValue = PolicyController.getDropDownMap().get(key); + if (keyValue.equals(decisionApply.getFunctionId())) { + rule.put("dynamicRuleAlgorithmCombo", key); + break; + } + } + + rule.put("id", "A" + (index +1)); + // Populate Key and values for Compound Rule + rule.put("dynamicRuleAlgorithmField1", "A" + (ruleAlgoirthmTracker.getLast() + 1 )); + ruleAlgoirthmTracker.removeLast(); + rule.put("dynamicRuleAlgorithmField2", "A" + (ruleAlgoirthmTracker.getLast() + 1)); + ruleAlgoirthmTracker.removeLast(); + ruleAlgoirthmTracker.addLast(index); + ruleAlgorithmList.add(rule); + index++; + } + + return index; + } +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java new file mode 100644 index 000000000..0f8a3c988 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java @@ -0,0 +1,394 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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 java.io.File; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +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.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.api.pap.OnapPDPGroup; +import org.onap.policy.xacml.std.pap.StdPDP; +import org.onap.policy.xacml.std.pap.StdPDPGroup; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.api.pap.PDPPolicy; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Controller +@RequestMapping({"/"}) +public class PDPController extends RestrictedBaseController { + private static final Logger policyLogger = FlexLogger.getLogger(PDPController.class); + + protected List groups = Collections.synchronizedList(new ArrayList()); + private PDPGroupContainer container; + + private static String SUPERADMIN = "super-admin"; + private static String SUPEREDITOR = "super-editor"; + private static String SUPERGUEST = "super-guest"; + + private Set groupsData; + + private boolean junit = false; + + private PolicyController policyController; + public PolicyController getPolicyController() { + return policyController; + } + + public void setPolicyController(PolicyController policyController) { + this.policyController = policyController; + } + + public synchronized void refreshGroups(HttpServletRequest request) { + synchronized(this.groups) { + this.groups.clear(); + try { + PolicyController controller = getPolicyControllerInstance(); + Set filteredPolicies = new HashSet<>(); + Set scopes = null; + List roles = null; + String userId = isJunit() ? "Test" : UserUtils.getUserSession(request).getOrgUserId(); + List userRoles = controller.getRoles(userId); + roles = new ArrayList<>(); + scopes = new HashSet<>(); + for(Object role: userRoles){ + Roles userRole = (Roles) role; + roles.add(userRole.getRole()); + if(userRole.getScope() != null){ + if(userRole.getScope().contains(",")){ + String[] multipleScopes = userRole.getScope().split(","); + for(int i =0; i < multipleScopes.length; i++){ + scopes.add(multipleScopes[i]); + } + }else{ + scopes.add(userRole.getScope()); + } + } + } + if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST) ) { + if(!junit){ + this.groups.addAll(controller.getPapEngine().getOnapPDPGroups()); + }else{ + this.groups.addAll(this.getGroupsData()); + } + }else{ + if(!userRoles.isEmpty()){ + if(!scopes.isEmpty()){ + this.groups.addAll(controller.getPapEngine().getOnapPDPGroups()); + List tempGroups = new ArrayList<>(); + if(!groups.isEmpty()){ + Iterator pdpGroup = groups.iterator(); + while(pdpGroup.hasNext()){ + OnapPDPGroup group = pdpGroup.next(); + Set policies = group.getPolicies(); + for(PDPPolicy policy : policies){ + for(String scope : scopes){ + scope = scope.replace(File.separator, "."); + String policyName = policy.getId(); + if(policyName.contains(".Config_")){ + policyName = policyName.substring(0, policyName.lastIndexOf(".Config_")); + }else if(policyName.contains(".Action_")){ + policyName = policyName.substring(0, policyName.lastIndexOf(".Action_")); + }else if(policyName.contains(".Decision_")){ + policyName = policyName.substring(0, policyName.lastIndexOf(".Decision_")); + } + if(policyName.startsWith(scope)){ + filteredPolicies.add(policy); + } + } + } + pdpGroup.remove(); + StdPDPGroup newGroup = (StdPDPGroup) group; + newGroup.setPolicies(filteredPolicies); + tempGroups.add(newGroup); + } + groups.clear(); + groups = tempGroups; + } + } + } + } + } catch (PAPException e) { + String message = "Unable to retrieve Groups from server: " + e; + policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Pap Engine is Null" + message); + } + } + } + + @RequestMapping(value={"/get_PDPGroupData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPDPGroupEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + ObjectMapper mapper = new ObjectMapper(); + refreshGroups(request); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while retrieving the PDP Group data" + e); + } + } + + @RequestMapping(value={"/pdp_Group/save_pdp_group"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public void savePDPGroup(HttpServletRequest request, HttpServletResponse response){ + try { + ObjectMapper mapper = new ObjectMapper(); + PolicyController controller = getPolicyControllerInstance(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + this.container = new PDPGroupContainer(controller.getPapEngine()); + StdPDPGroup pdpGroupData = mapper.readValue(root.get("pdpGroupData").toString().replace("groupName", "name"), StdPDPGroup.class); + try { + if(pdpGroupData.getId() == null){ + this.container.addNewGroup(pdpGroupData.getName(), pdpGroupData.getDescription()); + }else{ + this.container.updateGroup(pdpGroupData); + } + + } catch (Exception e) { + String message = "Unable to create Group. Reason:\n" + e.getMessage(); + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while creating the PDP Group" + message + e); + } + + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + refreshGroups(request); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); + JSONObject j = new JSONObject(msg); + out.write(j.toString()); + } + catch (Exception e){ + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Saving the PDP Group" + e); + response.setCharacterEncoding("UTF-8"); + PrintWriter out = null; + try { + request.setCharacterEncoding("UTF-8"); + out = response.getWriter(); + out.write(e.getMessage()); + } catch (Exception e1) { + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Saving the PDP Group" + e1); + } + } + } + + @RequestMapping(value={"/pdp_Group/remove_pdp_group"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public void removePDPGroup(HttpServletRequest request, HttpServletResponse response){ + try{ + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyController controller = getPolicyControllerInstance(); + this.container = new PDPGroupContainer(controller.getPapEngine()); + StdPDPGroup pdpGroupData = mapper.readValue(root.get("pdpGroupData").toString(), StdPDPGroup.class); + if(pdpGroupData.getName().equals("Default")) { + throw new UnsupportedOperationException("You can't remove the Default Group."); + }else{ + this.container.removeGroup(pdpGroupData, null); + } + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + refreshGroups(request); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); + JSONObject j = new JSONObject(msg); + out.write(j.toString()); + } + catch (Exception e){ + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Removing the PDP Group" + e); + PrintWriter out; + try { + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + out = response.getWriter(); + out.write(e.getMessage()); + } catch (Exception e1) { + policyLogger.error("Exception Occured"+ e1); + } + } + } + + @RequestMapping(value={"/pdp_Group/save_pdpTogroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public void savePDPToGroup(HttpServletRequest request, HttpServletResponse response){ + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyController controller = getPolicyControllerInstance(); + this.container = new PDPGroupContainer(controller.getPapEngine()); + String update = root.get("update").toString(); + PdpData pdpGroupData = (PdpData)mapper.readValue(root.get("pdpInGroup").toString(), PdpData.class); + StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class); + try { + + if(update.contains("false")){ + this.container.addNewPDP(pdpGroupData.getId(), activeGroupData, pdpGroupData.getName(), pdpGroupData.getDescription(), pdpGroupData.getJmxPort()); + }else{ + this.container.updateGroup(activeGroupData); + } + } catch (Exception e) { + String message = "Unable to create Group. Reason:\n" + e.getMessage(); + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Creating Pdp in PDP Group" + message + e); + } + + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + refreshGroups(request); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); + JSONObject j = new JSONObject(msg); + out.write(j.toString()); + } + catch (Exception e){ + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Creating Pdp in PDP Group" + e); + PrintWriter out; + try { + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + out = response.getWriter(); + out.write(e.getMessage()); + } catch (Exception e1) { + policyLogger.error("Exception Occured"+ e1); + } + } + } + + @RequestMapping(value={"/pdp_Group/remove_pdpFromGroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public void removePDPFromGroup(HttpServletRequest request, HttpServletResponse response){ + try{ + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyController controller = getPolicyControllerInstance(); + this.container = new PDPGroupContainer(controller.getPapEngine()); + StdPDP deletePdp = mapper.readValue(root.get("data").toString(), StdPDP.class); + StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class); + + this.container.removePDP(deletePdp, activeGroupData); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + refreshGroups(request); + String responseString = mapper.writeValueAsString(groups); + JSONObject j = new JSONObject("{pdpEntityDatas: " + responseString + "}"); + out.write(j.toString()); + } + catch (Exception e){ + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Removing Pdp from PDP Group" + e); + PrintWriter out; + try { + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + out = response.getWriter(); + out.write(e.getMessage()); + } catch (Exception e1) { + policyLogger.error("Exception Occured"+ e1); + } + } + } + + private PolicyController getPolicyControllerInstance(){ + return policyController != null ? getPolicyController() : new PolicyController(); + } + + public boolean isJunit() { + return junit; + } + + public void setJunit(boolean junit) { + this.junit = junit; + } + + public Set getGroupsData() { + return groupsData; + } + + public void setGroupsData(Set groupsData) { + this.groupsData = groupsData; + } +} + +class PdpData{ + String id; + int jmxPort; + String name; + String description; + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + public int getJmxPort() { + return jmxPort; + } + public void setJmxPort(int jmxPort) { + this.jmxPort = jmxPort; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } + +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java new file mode 100644 index 000000000..aa1918967 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java @@ -0,0 +1,696 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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 java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import javax.annotation.PostConstruct; +import javax.mail.MessagingException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.onap.policy.admin.PolicyNotificationMail; +import org.onap.policy.admin.RESTfulPAPEngine; +import org.onap.policy.model.PDPGroupContainer; +import org.onap.policy.model.Roles; +import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.XacmlAdminAuthorization; +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.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.openecomp.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; + +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.api.pap.PAPPolicyEngine; + +import com.att.research.xacml.util.XACMLProperties; +import com.fasterxml.jackson.databind.ObjectMapper; + +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + + +@Controller +@RequestMapping("/") +public class PolicyController extends RestrictedBaseController { + private static final Logger policyLogger = FlexLogger.getLogger(PolicyController.class); + + private static CommonClassDao commonClassDao; + + // Our authorization object + // + XacmlAdminAuthorization authorizer = new XacmlAdminAuthorization(); + // + // The PAP Engine + // + private static PAPPolicyEngine papEngine; + + private static String logTableLimit; + private static String systemAlertTableLimit; + protected static Map dropDownMap = new HashMap<>(); + public static Map getDropDownMap() { + return dropDownMap; + } + + public static void setDropDownMap(Map 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> mapDatatype2Function = null; + private static Map 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"; + + //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; + + @Autowired + private PolicyController(CommonClassDao commonClassDao){ + PolicyController.commonClassDao = commonClassDao; + } + + public PolicyController() { + } + + @PostConstruct + public void init(){ + Properties prop = new Properties(); + InputStream input = null; + try { + input = new FileInputStream("xacml.admin.properties"); + // load a properties file + prop.load(input); + //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(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(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")); + setMsPolicyName(prop.getProperty("xacml.policy.msPolicyName")); + //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); + } finally { + if (input != null) { + try { + input.close(); + } catch (IOException e) { + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured while Closing the xacml.admin.properties file" +e); + } + } + } + + //Initialize the FunctionDefinition table at Server Start up + Map> functionMap = getFunctionDatatypeMap(); + for (Datatype id : functionMap.keySet()) { + List functionDefinations = functionMap.get(id); + for (FunctionDefinition functionDef : functionDefinations) { + dropDownMap.put(functionDef.getShortname(),functionDef.getXacmlid()); + } + } + + } + + public static Map> getFunctionDatatypeMap() { + synchronized(mapAccess) { + if (mapDatatype2Function == null) { + buildFunctionMaps(); + } + } + return mapDatatype2Function; + } + + public static Map getFunctionIDMap() { + synchronized(mapAccess) { + if (mapID2Function == null) { + buildFunctionMaps(); + } + } + return mapID2Function; + } + + private static void buildFunctionMaps() { + mapDatatype2Function = new HashMap<>(); + mapID2Function = new HashMap<>(); + List 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()); + } + mapDatatype2Function.get(value.getDatatypeBean()).add(value); + } + } + + @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 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); + } + } + + public PolicyEntity getPolicyEntityData(String scope, String policyName){ + String key = scope + ":" + policyName; + List data = commonClassDao.getDataById(PolicyEntity.class, "scope:policyName", key); + return (PolicyEntity) data.get(0); + } + + public static Map getUserRoles(String userId) { + Map scopes = new HashMap<>(); + List roles = commonClassDao.getDataById(Roles.class, "loginId", userId); + if (roles != null && !roles.isEmpty()) { + for (Object role : roles) { + scopes.put(((Roles) role).getScope(), (Roles) role); + } + } + return scopes; + } + + public List getRolesOfUser(String userId) { + List rolesList = new ArrayList<>(); + List roles = commonClassDao.getDataById(Roles.class, "loginId", userId); + for (Object role: roles) { + rolesList.add(((Roles) role).getRole()); + } + return rolesList; + } + + public List getRoles(String userId) { + return commonClassDao.getDataById(Roles.class, "loginId", userId); + } + + //Get List of User Roles + @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 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 + @RequestMapping(value= {"/policy", "/policy/Editor" } , method = RequestMethod.GET) + public ModelAndView view(HttpServletRequest request){ + String myRequestURL = request.getRequestURL().toString(); + try { + // + // Set the URL for the RESTful PAP Engine + // + setPapEngine((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL)); + new PDPGroupContainer((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL)); + } catch (Exception e) { + policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception Occured while loading PAP"+e); + } + Map model = new HashMap<>(); + return new ModelAndView("policy_Editor","model", model); + } + + public PAPPolicyEngine getPapEngine() { + return papEngine; + } + + public void setPapEngine(PAPPolicyEngine papEngine) { + PolicyController.papEngine = papEngine; + } + + public String getUserName(String createdBy) { + String loginId = createdBy; + List data = commonClassDao.getDataById(UserInfo.class, "loginId", loginId); + return data.get(0).toString(); + } + + public static boolean getActivePolicy(String query) { + if(commonClassDao.getDataByQuery(query).size() > 0){ + return true; + }else{ + return false; + } + } + + 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 getData(@SuppressWarnings("rawtypes") Class className){ + return commonClassDao.getData(className); + } + + public PolicyVersion getPolicyEntityFromPolicyVersion(String query){ + return (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", query); + } + + public List getDataByQuery(String query){ + return commonClassDao.getDataByQuery(query); + } + + + @SuppressWarnings("rawtypes") + public Object getEntityItem(Class className, String columname, String key){ + return commonClassDao.getEntityItem(className, columname, key); + } + + + public void watchPolicyFunction(PolicyVersion entity, String policyName, String mode){ + PolicyNotificationMail email = new PolicyNotificationMail(); + try { + email.sendMail(entity, policyName, mode, commonClassDao); + } catch (MessagingException e) { + policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Excepton Occured while Renaming/Deleting a Policy or Scope" + e); + } + } + + //Switch Version + public JSONObject switchVersionPolicyContent(String policyName) { + 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_")){ + dbCheckName = dbCheckName.replace(".Decision_", ":Decision_"); + } + String[] splitDBCheckName = dbCheckName.split(":"); + String query = "FROM PolicyEntity where policyName like'"+splitDBCheckName[1]+"%' and scope ='"+splitDBCheckName[0]+"'"; + List policyEntity = commonClassDao.getDataByQuery(query); + List av = new ArrayList<>(); + for(Object entity : policyEntity){ + PolicyEntity pEntity = (PolicyEntity) entity; + String removeExtension = pEntity.getPolicyName().replace(".xml", ""); + String version = removeExtension.substring(removeExtension.lastIndexOf(".")+1); + av.add(version); + } + 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 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 XacmlAdminAuthorization getAuthorizer() { + return authorizer; + } + + public void setAuthorizer(XacmlAdminAuthorization authorizer) { + this.authorizer = authorizer; + } + + public static Map> getMapDatatype2Function() { + return mapDatatype2Function; + } + + public static void setMapDatatype2Function(Map> mapDatatype2Function) { + PolicyController.mapDatatype2Function = mapDatatype2Function; + } + + public static Map getMapID2Function() { + return mapID2Function; + } + + public static void setMapID2Function(Map 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; + } +} + diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java new file mode 100644 index 000000000..92794dda9 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java @@ -0,0 +1,384 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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 java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.poi.hssf.usermodel.HSSFRow; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.json.JSONObject; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.model.Roles; +import org.onap.policy.rest.adapter.PolicyExportAdapter; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.ActionBodyEntity; +import org.onap.policy.rest.jpa.ConfigurationDataEntity; +import org.onap.policy.rest.jpa.PolicyEditorScopes; +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.xacml.api.XACMLErrorConstants; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + + +@Controller +@RequestMapping("/") +public class PolicyExportAndImportController extends RestrictedBaseController { + private static Logger logger = FlexLogger.getLogger(PolicyExportAndImportController.class); + + private ArrayList selectedPolicy; + private Set scopes = null; + private List roles = null; + private static String SUPERADMIN = "super-admin"; + private static String SUPEREDITOR = "super-editor"; + private static String ADMIN = "admin"; + private static String EDITOR = "editor"; + + private static CommonClassDao commonClassDao; + + private PolicyEntity policyEntity; + private ConfigurationDataEntity configurationDataEntity; + private ActionBodyEntity actionBodyEntity; + private PolicyVersion policyVersion; + + private Workbook workbook; + + private HSSFWorkbook workBook2; + + private PolicyController policyController; + public PolicyController getPolicyController() { + return policyController; + } + + public void setPolicyController(PolicyController policyController) { + this.policyController = policyController; + } + + public static CommonClassDao getCommonClassDao() { + return commonClassDao; + } + + public static void setCommonClassDao(CommonClassDao commonClassDao) { + PolicyExportAndImportController.commonClassDao = commonClassDao; + } + + @Autowired + private PolicyExportAndImportController(CommonClassDao commonClassDao){ + PolicyExportAndImportController.commonClassDao = commonClassDao; + } + + public PolicyExportAndImportController(){} + + @RequestMapping(value={"/policy_download/exportPolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public void exportPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try{ + String file = null; + selectedPolicy = new ArrayList<>(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyExportAdapter adapter = mapper.readValue(root.get("exportData").toString(), PolicyExportAdapter.class); + for (Object policyId : adapter.getPolicyDatas()) { + LinkedHashMap selected = (LinkedHashMap)policyId; + String policyWithScope = selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml"; + String scope = policyWithScope.substring(0 , policyWithScope.lastIndexOf(File.separator)).replace(File.separator, "."); + String policyName = policyWithScope.substring(policyWithScope.lastIndexOf(File.separator)+1); + selectedPolicy.add(policyName+":"+scope); + } + List entityData = commonClassDao.getMultipleDataOnAddingConjunction(PolicyEntity.class, "policyName:scope", selectedPolicy); + + workBook2 = new HSSFWorkbook(); + HSSFSheet sheet = workBook2.createSheet("PolicyEntity"); + + HSSFRow headingRow = sheet.createRow(0); + headingRow.createCell(0).setCellValue("policyName"); + headingRow.createCell(1).setCellValue("scope"); + headingRow.createCell(2).setCellValue("version"); + headingRow.createCell(3).setCellValue("policyData"); + headingRow.createCell(4).setCellValue("description"); + headingRow.createCell(5).setCellValue("configurationbody"); + headingRow.createCell(6).setCellValue("configurationName"); + + short rowNo = 1; + for (Object object : entityData) { + PolicyEntity policyEntity = (PolicyEntity) object; + HSSFRow row = sheet.createRow(rowNo); + row.createCell(0).setCellValue(policyEntity.getPolicyName()); + row.createCell(1).setCellValue(policyEntity.getScope()); + row.createCell(2).setCellValue(policyEntity.getVersion()); + row.createCell(3).setCellValue(policyEntity.getPolicyData()); + row.createCell(4).setCellValue(policyEntity.getDescription()); + if(!policyEntity.getPolicyName().contains("Decision_")){ + if(policyEntity.getConfigurationData() != null){ + row.createCell(5).setCellValue(policyEntity.getConfigurationData().getConfigBody()); + row.createCell(6).setCellValue(policyEntity.getConfigurationData().getConfigurationName()); + } + if(policyEntity.getActionBodyEntity() != null){ + row.createCell(5).setCellValue(policyEntity.getActionBodyEntity().getActionBody()); + row.createCell(6).setCellValue(policyEntity.getActionBodyEntity().getActionBodyName()); + } + }else{ + row.createCell(5).setCellValue(""); + row.createCell(6).setCellValue(""); + } + rowNo++; + } + + String tmp = System.getProperty("catalina.base") + File.separator + "webapps" + File.separator + "temp"; + String deleteCheckPath = tmp + File.separator + "PolicyExport.xls"; + File deleteCheck = new File(deleteCheckPath); + if(deleteCheck.exists()){ + deleteCheck.delete(); + } + File temPath = new File(tmp); + if(!temPath.exists()){ + temPath.mkdir(); + } + + file = temPath + File.separator + "PolicyExport.xls"; + File filepath = new File(file); + FileOutputStream fos = new FileOutputStream(filepath); + workBook2.write(fos); + fos.flush(); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String successMap = file.toString().substring(file.toString().lastIndexOf("webapps")+8); + String responseString = mapper.writeValueAsString(successMap); + JSONObject j = new JSONObject("{data: " + responseString + "}"); + out.write(j.toString()); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception Occured while Exporting Policies"+e); + } + } + + //Policy Import + public JSONObject importRepositoryFile(String file, HttpServletRequest request) throws Exception{ + boolean configExists = false; + boolean actionExists = false; + String configName = null; + String scope = null; + boolean finalColumn = false; + PolicyController controller = policyController != null ? getPolicyController() : new PolicyController(); + String userId = UserUtils.getUserSession(request).getOrgUserId(); + UserInfo userInfo = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", userId); + + //Check if the Role and Scope Size are Null get the values from db. + List userRoles = controller.getRoles(userId); + roles = new ArrayList<>(); + scopes = new HashSet<>(); + for(Object role: userRoles){ + Roles userRole = (Roles) role; + roles.add(userRole.getRole()); + if(userRole.getScope() != null){ + if(userRole.getScope().contains(",")){ + String[] multipleScopes = userRole.getScope().split(","); + for(int i =0; i < multipleScopes.length; i++){ + scopes.add(multipleScopes[i]); + } + }else{ + scopes.add(userRole.getScope()); + } + } + } + FileInputStream excelFile = new FileInputStream(new File(file)); + workbook = new HSSFWorkbook(excelFile); + Sheet datatypeSheet = workbook.getSheetAt(0); + Iterator rowIterator = datatypeSheet.iterator(); + + while (rowIterator.hasNext()) { + policyEntity = new PolicyEntity(); + configurationDataEntity = new ConfigurationDataEntity(); + actionBodyEntity = new ActionBodyEntity(); + policyVersion = new PolicyVersion(); + Row currentRow = rowIterator.next(); + if (currentRow.getRowNum() == 0) { + continue; + } + Iterator cellIterator = currentRow.cellIterator(); + while (cellIterator.hasNext()) { + Cell cell = cellIterator.next(); + if (getCellHeaderName(cell).equalsIgnoreCase("policyName")) { + policyEntity.setPolicyName(cell.getStringCellValue()); + } + if (getCellHeaderName(cell).equalsIgnoreCase("scope")) { + policyEntity.setScope(cell.getStringCellValue()); + } + if (getCellHeaderName(cell).equalsIgnoreCase("policyData")) { + policyEntity.setPolicyData(cell.getStringCellValue()); + } + if (getCellHeaderName(cell).equalsIgnoreCase("description")) { + policyEntity.setDescription(cell.getStringCellValue()); + } + if (getCellHeaderName(cell).equalsIgnoreCase("configurationbody")) { + if(policyEntity.getPolicyName().contains("Config_")){ + configExists = true; + configurationDataEntity.setConfigBody(cell.getStringCellValue()); + }else if(policyEntity.getPolicyName().contains("Action_")){ + actionExists = true; + actionBodyEntity.setActionBody(cell.getStringCellValue()); + } + } + if (getCellHeaderName(cell).equalsIgnoreCase("configurationName")) { + finalColumn = true; + configName = cell.getStringCellValue(); + if(policyEntity.getPolicyName().contains("Config_")){ + configurationDataEntity.setConfigurationName(cell.getStringCellValue()); + }else if(policyEntity.getPolicyName().contains("Action_")){ + actionBodyEntity.setActionBodyName(cell.getStringCellValue()); + } + } + + if(finalColumn){ + scope = policyEntity.getScope().replace(".", File.separator); + String query = "FROM PolicyEntity where policyName = '"+policyEntity.getPolicyName()+"' and scope ='"+policyEntity.getScope()+"'"; + List queryData = controller.getDataByQuery(query); + if(!queryData.isEmpty()){ + continue; + } + if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR)) { + //1. if Role contains super admin create scope. + //2. if Role contains super editor don't create new scope and add to list to show to user. + + PolicyEditorScopes policyEditorScope = (PolicyEditorScopes) commonClassDao.getEntityItem(PolicyEditorScopes.class, "scopeName", scope); + if(policyEditorScope == null){ + if(roles.contains(SUPERADMIN)){ + PolicyEditorScopes policyEditorScopeEntity = new PolicyEditorScopes(); + policyEditorScopeEntity.setScopeName(scope); + policyEditorScopeEntity.setUserCreatedBy(userInfo); + policyEditorScopeEntity.setUserModifiedBy(userInfo); + commonClassDao.save(policyEditorScopeEntity); + }else{ + //Add Error Message a new Scope Exists, contact super-admin to create a new scope + continue; + } + } + } + if (roles.contains(ADMIN) || roles.contains(EDITOR)) { + if(scopes.isEmpty()){ + //return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin"); + }else{ + //1. if Role contains admin, then check if parent scope has role admin, if not don't create a scope and add to list. + if(roles.contains(ADMIN)){ + String scopeCheck = scope.substring(0, scope.lastIndexOf(".")); + if(scopes.contains(scopeCheck)){ + PolicyEditorScopes policyEditorScopeEntity = new PolicyEditorScopes(); + policyEditorScopeEntity.setScopeName(scope); + policyEditorScopeEntity.setUserCreatedBy(userInfo); + policyEditorScopeEntity.setUserModifiedBy(userInfo); + commonClassDao.save(policyEditorScopeEntity); + }else{ + continue; + } + }else{ + continue; + } + } + } + + if(configExists){ + if(configName.endsWith("json")){ + configurationDataEntity.setConfigType("JSON"); + }else if(configName.endsWith("txt")){ + configurationDataEntity.setConfigType("OTHER"); + }else if(configName.endsWith("xml")){ + configurationDataEntity.setConfigType("XML"); + }else if(configName.endsWith("properties")){ + configurationDataEntity.setConfigType("PROPERTIES"); + } + configurationDataEntity.setDeleted(false); + configurationDataEntity.setCreatedBy(userId); + configurationDataEntity.setModifiedBy(userId); + commonClassDao.save(configurationDataEntity); + } + if(actionExists){ + actionBodyEntity.setDeleted(false); + actionBodyEntity.setCreatedBy(userId); + actionBodyEntity.setModifiedBy(userId); + commonClassDao.save(actionBodyEntity); + } + if(configName != null){ + if(configName.contains("Config_")){ + ConfigurationDataEntity configuration = (ConfigurationDataEntity) commonClassDao.getEntityItem(ConfigurationDataEntity.class, "configurationName", configName); + policyEntity.setConfigurationData(configuration); + }else{ + ActionBodyEntity actionBody = (ActionBodyEntity) commonClassDao.getEntityItem(ActionBodyEntity.class, "actionBodyName", configName); + policyEntity.setActionBodyEntity(actionBody); + } + } + policyEntity.setCreatedBy(userId); + policyEntity.setModifiedBy(userId); + policyEntity.setDeleted(false); + commonClassDao.save(policyEntity); + + policyVersion = new PolicyVersion(); + String policyName = policyEntity.getPolicyName().replace(".xml", ""); + int version = Integer.parseInt(policyName.substring(policyName.lastIndexOf(".")+1)); + policyName = policyName.substring(0, policyName.lastIndexOf(".")); + + policyVersion.setPolicyName(scope.replace(".", File.separator) + File.separator + policyName); + policyVersion.setActiveVersion(version); + policyVersion.setHigherVersion(version); + policyVersion.setCreatedBy(userId); + policyVersion.setModifiedBy(userId); + commonClassDao.save(policyVersion); + } + } + } + return null; + } + + //return the column header name value + private String getCellHeaderName(Cell cell){ + String cellHeaderName = cell.getSheet().getRow(0).getCell(cell.getColumnIndex()).getRichStringCellValue().toString(); + return cellHeaderName; + } +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java new file mode 100644 index 000000000..f3291a79b --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java @@ -0,0 +1,122 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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 java.io.File; +import java.io.PrintWriter; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.WatchPolicyNotificationTable; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; + +@Controller +@RequestMapping({"/"}) +public class PolicyNotificationController extends RestrictedBaseController { + + @Autowired + CommonClassDao commonClassDao; + + @RequestMapping(value={"/watchPolicy"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView watchPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + String path = ""; + String responseValue = ""; + try { + String userId = UserUtils.getUserSession(request).getOrgUserId(); + System.out.println(userId); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + String name = root.get("watchData").get("name").toString(); + JsonNode pathList = root.get("watchData").get("path"); + String finalName = ""; + if(pathList.isArray()){ + ArrayNode arrayNode = (ArrayNode) pathList; + for (int i = 0; i < arrayNode.size(); i++) { + JsonNode individualElement = arrayNode.get(i); + if(i == 0){ + path = path + individualElement.toString().replace("\"", "").trim(); + }else{ + path = path + File.separator + individualElement.toString().replace("\"", "").trim(); + } + } + } + + if(pathList.size() > 0){ + finalName = path + File.separator + name.replace("\"", "").trim(); + }else{ + finalName = name.replace("\"", "").trim(); + } + if(finalName.contains("\\")){ + finalName = finalName.replace("\\", "\\\\"); + } + String query = "from WatchPolicyNotificationTable where POLICYNAME = '"+finalName+"' and LOGINIDS = '"+userId+"'"; + List watchList = commonClassDao.getDataByQuery(query); + if(watchList.isEmpty()){ + if(finalName.contains("\\\\")){ + finalName = finalName.replace("\\\\", File.separator); + } + WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable(); + watch.setPolicyName(finalName); + watch.setLoginIds(userId); + commonClassDao.save(watch); + responseValue = "You have Subscribed Successfully"; + }else{ + commonClassDao.delete(watchList.get(0)); + responseValue = "You have UnSubscribed Successfully"; + } + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(responseValue); + JSONObject j = new JSONObject("{watchData: " + responseString + "}"); + out.write(j.toString()); + return null; + }catch(Exception e){ + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java new file mode 100644 index 000000000..6f8b3de8e --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java @@ -0,0 +1,167 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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 java.io.PrintWriter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.PolicyEditorScopes; +import org.onap.policy.rest.jpa.PolicyRoles; +import org.onap.policy.rest.jpa.UserInfo; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +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.servlet.ModelAndView; + +import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Controller +@RequestMapping("/") +public class PolicyRolesController extends RestrictedBaseController{ + + private static final Logger LOGGER = FlexLogger.getLogger(PolicyRolesController.class); + + @Autowired + CommonClassDao commonClassDao; + + List scopelist; + + @RequestMapping(value={"/get_RolesData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPolicyRolesEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("rolesDatas", mapper.writeValueAsString(commonClassDao.getUserRoles())); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error("Exception Occured"+e); + } + } + + @RequestMapping(value={"/save_NonSuperRolesData"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView SaveRolesEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + String scopeName = null; + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + ReadScopes adapter = mapper.readValue(root.get("editRoleData").toString(), ReadScopes.class); + for(int i = 0; i < adapter.getScope().size(); i++){ + if(i == 0){ + scopeName = adapter.getScope().get(0); + }else{ + scopeName = scopeName + "," + adapter.getScope().get(i); + } + } + PolicyRoles roles = new PolicyRoles(); + roles.setId(adapter.getId()); + roles.setLoginId(adapter.getLoginId()); + roles.setRole(adapter.getRole()); + roles.setScope(scopeName); + commonClassDao.update(roles); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(commonClassDao.getUserRoles()); + JSONObject j = new JSONObject("{rolesDatas: " + responseString + "}"); + + out.write(j.toString()); + } + catch (Exception e){ + LOGGER.error("Exception Occured"+e); + } + return null; + } + + @RequestMapping(value={"/get_PolicyRolesScopeData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPolicyScopesEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + scopelist = new ArrayList<>(); + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); + List scopesData = commonClassDao.getDataByColumn(PolicyEditorScopes.class, "scopeName"); + model.put("scopeDatas", mapper.writeValueAsString(scopesData)); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error("Exception Occured"+e); + } + } +} + +class ReadScopes{ + private int id; + private UserInfo loginId; + private String role; + private ArrayList scope; + + public int getId() { + return id; + } + public void setId(int id) { + this.id = id; + } + public UserInfo getLoginId() { + return loginId; + } + public void setLoginId(UserInfo loginId) { + this.loginId = loginId; + } + public String getRole() { + return role; + } + public void setRole(String role) { + this.role = role; + } + public ArrayList getScope() { + return scope; + } + public void setScope(ArrayList scope) { + this.scope = scope; + } + +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java new file mode 100644 index 000000000..5fb0c1a7e --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java @@ -0,0 +1,776 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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 java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.io.PrintWriter; +import java.io.StringReader; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Scanner; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.json.Json; +import javax.json.JsonReader; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; + +import org.apache.commons.lang.StringUtils; +import org.dom4j.util.XMLErrorHandler; +import org.json.JSONObject; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.adapter.ClosedLoopFaultBody; +import org.onap.policy.rest.adapter.ClosedLoopPMBody; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.MicroServiceModels; +import org.onap.policy.rest.jpa.SafePolicyWarning; +import org.onap.policy.utils.PolicyUtils; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; +import org.xml.sax.InputSource; +import org.xml.sax.XMLReader; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.CharMatcher; +import com.google.common.base.Splitter; +import com.google.common.base.Strings; + +@Controller +@RequestMapping("/") +public class PolicyValidationController extends RestrictedBaseController { + + private static final Logger LOGGER = FlexLogger.getLogger(PolicyValidationController.class); + + public static final String CONFIG_POLICY = "Config"; + public static final String ACTION_POLICY = "Action"; + public static final String DECISION_POLICY = "Decision"; + public static final String CLOSEDLOOP_POLICY = "ClosedLoop_Fault"; + public static final String CLOSEDLOOP_PM = "ClosedLoop_PM"; + public static final String ENFORCER_CONFIG_POLICY= "Enforcer Config"; + public static final String MICROSERVICES="Micro Service"; + private Pattern pattern; + private Matcher matcher; + private static Map mapAttribute = new HashMap<>(); + + private static final String EMAIL_PATTERN = + "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; + + @Autowired + CommonClassDao commonClassDao; + + @RequestMapping(value={"/policyController/validate_policy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView validatePolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try{ + boolean valid = true; + StringBuilder responseString = new StringBuilder(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyRestAdapter policyData = (PolicyRestAdapter)mapper.readValue(root.get("policyData").toString(), PolicyRestAdapter.class); + if(policyData.getPolicyName() != null){ + String policyNameValidate = emptyValidator(policyData.getPolicyName()); + if(!policyNameValidate.contains("success")){ + responseString.append("PolicyName:" + policyNameValidate + "
    "); + valid = false; + }; + }else{ + responseString.append( "PolicyName: PolicyName Should not be empty" + "
    "); + valid = false; + } + if(policyData.getPolicyDescription() != null){ + String descriptionValidate = descriptionValidator(policyData.getPolicyDescription()); + if(!descriptionValidate.contains("success")){ + responseString.append("Description:" + descriptionValidate + "
    "); + valid = false; + } + } + + if(policyData.getPolicyType().equals(CONFIG_POLICY)){ + if (policyData.getConfigPolicyType().equals("Base") || policyData.getConfigPolicyType().equals(CLOSEDLOOP_POLICY) + || policyData.getConfigPolicyType().equals(CLOSEDLOOP_PM) || policyData.getConfigPolicyType().equals(ENFORCER_CONFIG_POLICY) || policyData.getConfigPolicyType().equals(MICROSERVICES)) { + if(policyData.getOnapName() != null){ + String onapNameValidate = emptyValidator(policyData.getOnapName()); + if(!onapNameValidate.contains("success")){ + responseString.append("OnapName:" + onapNameValidate + "
    "); + valid = false; + } + }else{ + responseString.append("Onap Name: Onap Name Should not be empty" + "
    "); + valid = false; + } + } + + if(policyData.getRiskType() != null){ + String riskTypeValidate = emptyValidator(policyData.getRiskType()); + if(!riskTypeValidate.contains("success")){ + responseString.append("RiskType:" + riskTypeValidate + "
    "); + valid = false; + } + }else { + responseString.append("Risk Type: Risk Type Should not be Empty" + "
    "); + valid = false; + } + + if(policyData.getRiskLevel() != null){ + String validateRiskLevel = emptyValidator(policyData.getRiskLevel()); + if(!validateRiskLevel.contains("success")){ + responseString.append("RiskLevel:" + validateRiskLevel + "
    "); + valid = false; + } + }else { + responseString.append("Risk Level: Risk Level Should not be Empty" + "
    "); + valid = false; + } + + if(policyData.getGuard() != null){ + String validateGuard = emptyValidator(policyData.getGuard()); + if(!validateGuard.contains("success")){ + responseString.append("Guard:" + validateGuard + "
    "); + valid = false; + } + }else { + responseString.append("Guard: Guard Value Should not be Empty" + "
    "); + valid = false; + } + + if(policyData.getConfigPolicyType().equals("Base")){ + if(policyData.getConfigName() != null){ + String configNameValidate = emptyValidator(policyData.getConfigName()); + if(!configNameValidate.contains("success")){ + responseString.append("ConfigName:" + configNameValidate + "
    "); + valid = false; + } + }else{ + responseString.append("Config Name: Config Name Should not be Empty" + "
    "); + valid = false; + } + if(policyData.getConfigType() != null){ + String configTypeValidate = emptyValidator(policyData.getConfigType()); + if(!configTypeValidate.contains("success")){ + responseString.append("ConfigType:" + configTypeValidate + "
    "); + valid = false; + } + }else{ + responseString.append("Config Type: Config Type Should not be Empty" + "
    "); + valid = false; + } + if(policyData.getConfigBodyData() != null){ + String configBodyData = policyData.getConfigBodyData(); + String policyType = policyData.getConfigType(); + if (policyType != null) { + if (policyType.equals("JSON")) { + if (!isJSONValid(configBodyData)) { + responseString.append("Config Body: JSON Content is not valid" + "
    "); + valid = false; + } + } else if (policyType.equals("XML")) { + if (!isXMLValid(configBodyData)) { + responseString.append("Config Body: XML Content data is not valid" + "
    "); + valid = false; + } + } else if (policyType.equals("PROPERTIES")) { + if (!isPropValid(configBodyData)||configBodyData.equals("")) { + responseString.append("Config Body: Property data is not valid" + "
    "); + valid = false; + } + } else if (policyType.equals("OTHER")) { + if (configBodyData.equals("")) { + responseString.append("Config Body: Config Body Should not be Empty" + "
    "); + valid = false; + } + } + } + }else{ + responseString.append("Config Body: Config Body Should not be Empty" + "
    "); + valid = false; + } + } + + if(policyData.getConfigPolicyType().equals("Firewall Config")){ + if(policyData.getConfigName() != null){ + String configNameValidate = PolicyUtils.emptyPolicyValidator(policyData.getConfigName()); + if(!configNameValidate.contains("success")){ + responseString.append("ConfigName:" + configNameValidate + "
    "); + valid = false; + } + }else{ + responseString.append("Config Name: Config Name is required" + "
    "); + valid = false; + } + if(policyData.getSecurityZone() == null){ + responseString.append("Security Zone: Security Zone is required" + "
    "); + valid = false; + } + } + if(policyData.getConfigPolicyType().equals("BRMS_Param")){ + if(policyData.getRuleName() == null){ + responseString.append("BRMS Template:BRMS Template is required
    "); + valid = false; + } + } + if(policyData.getConfigPolicyType().equals("BRMS_Raw")){ + if(policyData.getConfigBodyData() != null){ + String message = PolicyUtils.brmsRawValidate(policyData.getConfigBodyData()); + // If there are any error other than Annotations then this is not Valid + if(message.contains("[ERR")){ + responseString.append("Raw Rule Validate:Raw Rule has error"+ message +"
    "); + valid = false; + } + }else{ + responseString.append("Raw Rule:Raw Rule is required
    "); + valid = false; + } + } + if(policyData.getConfigPolicyType().equals("ClosedLoop_PM")){ + try{ + if(root.get("policyData").get("verticaMetrics").get("serviceTypePolicyName") == null && policyData.getServiceTypePolicyName().isEmpty()){ + responseString.append("ServiceType PolicyName:ServiceType PolicyName is required
    "); + valid = false; + } + }catch(Exception e){ + responseString.append("ServiceType PolicyName:ServiceType PolicyName is required
    "); + valid = false; + } + + if(root.get("policyData").get("jsonBodyData") != null){ + ClosedLoopPMBody pmBody = (ClosedLoopPMBody)mapper.readValue(root.get("policyData").get("jsonBodyData").toString(), ClosedLoopPMBody.class); + if(pmBody.getEmailAddress() != null){ + String result = emailValidation(pmBody.getEmailAddress(), responseString.toString()); + if(result != "success"){ + responseString.append(result + "
    "); + valid = false; + } + } + if(pmBody.getGeoLink() != null){ + String result = PolicyUtils.emptyPolicyValidator(pmBody.getGeoLink()); + if(!result.contains("success")){ + responseString.append("GeoLink:" + result + "
    "); + valid = false; + }; + } + if(pmBody.getAttributes() != null){ + for(Entry entry : pmBody.getAttributes().entrySet()){ + String key = entry.getKey(); + String value = entry.getValue(); + if(!key.contains("Message")){ + String attributeValidate = PolicyUtils.emptyPolicyValidator(value); + if(!attributeValidate.contains("success")){ + responseString.append("Attributes:" + key + " : value has spaces
    "); + valid = false; + }; + } + } + } + }else{ + responseString.append("D2/Virtualized Services:Select atleast one D2/Virtualized Services
    "); + valid = false; + } + } + if(policyData.getConfigPolicyType().equals("ClosedLoop_Fault")){ + if(root.get("policyData").get("jsonBodyData") != null){ + ClosedLoopFaultBody faultBody = (ClosedLoopFaultBody)mapper.readValue(root.get("policyData").get("jsonBodyData").toString(), ClosedLoopFaultBody.class); + if(faultBody.getEmailAddress() != null){ + String result = emailValidation(faultBody.getEmailAddress(), responseString.toString()); + if(result != "success"){ + responseString.append(result+ "
    "); + valid = false; + } + } + if((faultBody.isGama() || faultBody.isMcr() || faultBody.isTrinity() || faultBody.isvDNS() || faultBody.isvUSP()) != true){ + responseString.append("D2/Virtualized Services:Select atleast one D2/Virtualized Services
    "); + valid = false; + } + if(faultBody.getActions() == null){ + responseString.append("vPRO Actions:vPRO Actions is required
    "); + valid = false; + } + if(faultBody.getClosedLoopPolicyStatus() == null){ + responseString.append("Policy Status:Policy Status is required
    "); + valid = false; + } + if(faultBody.getConditions() == null){ + responseString.append("Conditions:Select Atleast one Condition
    "); + valid = false; + } + if(faultBody.getGeoLink() != null){ + String result = PolicyUtils.emptyPolicyValidatorWithSpaceAllowed(faultBody.getGeoLink()); + if(!result.contains("success")){ + responseString.append("GeoLink:" + result + "
    "); + valid = false; + }; + } + + if(faultBody.getTimeInterval() == 0){ + responseString.append("Time Interval:Time Interval is required
    "); + valid = false; + } + if(faultBody.getRetrys() == 0){ + responseString.append("Number of Retries:Number of Retries is required
    "); + valid = false; + } + if(faultBody.getTimeOutvPRO() == 0){ + responseString.append("APP-C Timeout:APP-C Timeout is required
    "); + valid = false; + } + if(faultBody.getTimeOutRuby() == 0){ + responseString.append("TimeOutRuby:TimeOutRuby is required
    "); + valid = false; + } + if(faultBody.getVnfType() == null){ + responseString.append("Vnf Type:Vnf Type is required
    "); + valid = false; + } + }else{ + responseString.append("D2/Virtualized Services:Select atleast one D2/Virtualized Services
    "); + responseString.append("vPRO Actions:vPRO Actions is required
    "); + responseString.append("Aging Window:Aging Window is required
    "); + responseString.append("Policy Status:Policy Status is required
    "); + responseString.append("Conditions:Select Atleast one Condition
    "); + responseString.append("PEP Name:PEP Name is required
    "); + responseString.append("PEP Action:PEP Action is required
    "); + responseString.append("Time Interval:Time Interval is required
    "); + responseString.append("Number of Retries:Number of Retries is required
    "); + responseString.append("APP-C Timeout:APP-C Timeout is required
    "); + responseString.append("TimeOutRuby:TimeOutRuby is required
    "); + responseString.append("Vnf Type:Vnf Type is required
    "); + valid = false; + } + } + + if (policyData.getConfigPolicyType().contains("Micro Service")){ + if(policyData.getServiceType() != null){ + pullJsonKeyPairs(root.get("policyJSON")); + MicroServiceModels returnModel = new MicroServiceModels(); + String service = null; + String version = null; + if (policyData.getServiceType().contains("-v")){ + service = policyData.getServiceType().split("-v")[0]; + version = policyData.getServiceType().split("-v")[1]; + }else { + service = policyData.getServiceType(); + version = policyData.getVersion(); + } + returnModel = getAttributeObject(service, version); + String annoation = returnModel.getAnnotation(); + if (!Strings.isNullOrEmpty(annoation)){ + Map rangeMap = new HashMap<>(); + rangeMap = Splitter.on(",").withKeyValueSeparator("=").split(annoation); + for (Entry rMap : rangeMap.entrySet()){ + if (rMap.getValue().contains("range::")){ + String value = mapAttribute.get(rMap.getKey().trim()); + String[] tempString = rMap.getValue().split("::")[1].split("-"); + int startNum = Integer.parseInt(tempString[0]); + int endNum = Integer.parseInt(tempString[1]); + String returnString = "Invalid Range:" + rMap.getKey() + " must be between " + + startNum + " - " + endNum + ","; + if (PolicyUtils.isInteger(value.replace("\"", ""))){ + int result = Integer.parseInt(value.replace("\"", "")); + if (result < startNum || result > endNum){ + responseString.append(returnString); + valid = false; + } + }else { + responseString.append(returnString); + valid = false; + } + } + } + } + }else{ + responseString.append("Micro Service: Micro Service is required" + "
    "); + valid = false; + } + + if(policyData.getPriority() == null){ + responseString.append("Priority: Priority is required" + "
    "); + valid = false; + } + } + } + if (policyData.getPolicyType().equals(DECISION_POLICY)){ + if(policyData.getOnapName() != null){ + String onapNameValidate = emptyValidator(policyData.getOnapName()); + if(!onapNameValidate.contains("success")){ + responseString.append("OnapName:" + onapNameValidate + "
    "); + valid = false; + } + }else{ + responseString.append("Onap Name: Onap Name Should not be empty" + "
    "); + valid = false; + } + + if("Rainy_Day".equals(policyData.getRuleProvider())){ + if(policyData.getRainyday()==null){ + responseString.append(" Rainy Day Parameters are Required
    "); + valid = false; + }else{ + if(policyData.getRainyday().getServiceType()==null){ + responseString.append("Rainy Day Service Type is Required
    "); + valid = false; + } + if(policyData.getRainyday().getVnfType()==null){ + responseString.append("Rainy Day VNF Type is Required
    "); + valid = false; + } + if(policyData.getRainyday().getBbid()==null){ + responseString.append("Rainy Day Building Block ID is Required
    "); + valid = false; + } + if(policyData.getRainyday().getWorkstep()==null){ + responseString.append("Rainy Day Work Step is Required
    "); + valid = false; + } + if(policyData.getRainyday().getServiceType()==null){ + responseString.append("Rainy Day Error Code is Required
    "); + valid = false; + } + } + } + + if("GUARD_YAML".equals(policyData.getRuleProvider()) || "GUARD_BL_YAML".equals(policyData.getRuleProvider())){ + if(policyData.getYamlparams()==null){ + responseString.append(" Guard Params are Required " + "
    "); + valid = false; + }else{ + if(policyData.getYamlparams().getActor()==null){ + responseString.append("Guard Params Actor is Required " + "
    "); + valid = false; + } + if(policyData.getYamlparams().getRecipe()==null){ + responseString.append("Guard Params Recipe is Required " + "
    "); + valid = false; + } + if(policyData.getYamlparams().getGuardActiveStart()==null){ + responseString.append("Guard Params Guard Active Start/b>is Required " + "
    "); + valid = false; + } + if(policyData.getYamlparams().getGuardActiveEnd()==null){ + responseString.append("Guard Params Guard Active Endis Required " + "
    "); + valid = false; + } + if("GUARD_YAML".equals(policyData.getRuleProvider())){ + if(policyData.getYamlparams().getLimit()==null){ + responseString.append(" Guard Params Limit is Required " + "
    "); + valid = false; + }else if(!PolicyUtils.isInteger(policyData.getYamlparams().getLimit())){ + responseString.append(" Guard Params Limit Should be Integer " + "
    "); + valid = false; + } + if(policyData.getYamlparams().getTimeWindow()==null){ + responseString.append("Guard Params Time Window is Required" + "
    "); + valid = false; + }else if(!PolicyUtils.isInteger(policyData.getYamlparams().getTimeWindow())){ + responseString.append(" Guard Params Time Window Should be Integer " + "
    "); + valid = false; + } + if(policyData.getYamlparams().getTimeUnits()==null){ + responseString.append("Guard Params Time Units is Required" + "
    "); + valid = false; + } + }else if("GUARD_BL_YAML".equals(policyData.getRuleProvider())){ + if(policyData.getYamlparams().getBlackList()==null || policyData.getYamlparams().getBlackList().isEmpty()){ + responseString.append(" Guard Params BlackList is Required " + "
    "); + valid = false; + }else{ + for(String blackList: policyData.getYamlparams().getBlackList()){ + if(blackList==null || !("success".equals(emptyValidator(blackList)))){ + responseString.append(" Guard Params BlackList Should be valid String" + "
    "); + valid = false; + break; + } + } + } + } + } + } + } + + if(policyData.getPolicyType().equals(ACTION_POLICY)){ + if(policyData.getActionPerformer() != null){ + String actionPerformer = emptyValidator(policyData.getActionPerformer()); + if(!actionPerformer.contains("success")){ + responseString.append("ActionPerformer:" + actionPerformer + "
    "); + valid = false; + }; + }else{ + responseString.append("ActionPerformer: ActionPerformer Should not be empty" + "
    "); + valid = false; + } + if(policyData.getAttributes() != null){ + for(Object attribute : policyData.getAttributes()){ + if(attribute instanceof LinkedHashMap){ + try{ + //This is for validation check if the value exists or not + String key = ((LinkedHashMap) attribute).get("key").toString(); + String value = ((LinkedHashMap) attribute).get("value").toString(); + if("".equals(key) || "".equals(value)){ + responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "
    "); + valid = false; + break; + } + }catch(Exception e){ + LOGGER.error("This is a Policy Validation check" +e); + responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "
    "); + valid = false; + break; + } + } + } + }else{ + responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "
    "); + valid = false; + } + if(policyData.getActionAttributeValue() != null){ + String actionAttribute = emptyValidator(policyData.getActionAttributeValue()); + if(!actionAttribute.contains("success")){ + responseString.append("ActionAttribute:" + actionAttribute + "
    "); + valid = false; + }; + }else{ + responseString.append("ActionAttribute: ActionAttribute Should not be empty" + "
    "); + valid = false; + } + } + + if(policyData.getPolicyType().equals(ACTION_POLICY) || policyData.getPolicyType().equals(DECISION_POLICY)){ + if(!policyData.getRuleAlgorithmschoices().isEmpty()){ + for(Object attribute : policyData.getRuleAlgorithmschoices()){ + if(attribute instanceof LinkedHashMap){ + try{ + String label = ((LinkedHashMap) attribute).get("id").toString(); + String key = ((LinkedHashMap) attribute).get("dynamicRuleAlgorithmField1").toString(); + String rule = ((LinkedHashMap) attribute).get("dynamicRuleAlgorithmCombo").toString(); + String value = ((LinkedHashMap) attribute).get("dynamicRuleAlgorithmField2").toString(); + if("".equals(label) || "".equals(key) || "".equals(rule) || "".equals(value)){ + responseString.append("Rule Algorithms: One or more Fields in Rule Algorithms is Empty." + "
    "); + valid = false; + } + }catch(Exception e){ + LOGGER.error("This is a Policy Validation check" +e); + responseString.append("Rule Algorithms: One or more Fields in Rule Algorithms is Empty." + "
    "); + valid = false; + break; + } + } + } + } + } + + if(policyData.getPolicyType().equals(CONFIG_POLICY)){ + String value = ""; + if(valid){ + List spData = commonClassDao.getDataById(SafePolicyWarning.class, "riskType", policyData.getRiskType()); + if (!spData.isEmpty()){ + SafePolicyWarning safePolicyWarningData = (SafePolicyWarning) spData.get(0); + safePolicyWarningData.getMessage(); + value = "Message:" + safePolicyWarningData.getMessage(); + } + responseString.append("success" + "@#"+ value); + } + }else{ + if(valid){ + responseString.append("success"); + } + } + + PrintWriter out = response.getWriter(); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(responseString.toString())); + JSONObject j = new JSONObject(msg); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + LOGGER.error("Exception Occured while Policy Validation" +e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + protected String emptyValidator(String field){ + String error; + if ("".equals(field) || field.contains(" ") || !field.matches("^[a-zA-Z0-9_]*$")) { + error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations"; + return error; + } else { + if(CharMatcher.ASCII.matchesAllOf((CharSequence) field)){ + error = "success"; + }else{ + error = "The Value Contains Non ASCII Characters"; + return error; + } + } + return error; + } + + protected String descriptionValidator(String field) { + String error; + if (field.contains("@CreatedBy:") || field.contains("@ModifiedBy:")) { + error = "The value in the description shouldn't contain @CreatedBy: or @ModifiedBy:"; + return error; + } else { + error = "success"; + } + return error; + } + + public String validateEmailAddress(String emailAddressValue) { + String error = "success"; + List emailList = Arrays.asList(emailAddressValue.toString().split(",")); + for(int i =0 ; i < emailList.size() ; i++){ + pattern = Pattern.compile(EMAIL_PATTERN); + matcher = pattern.matcher(emailList.get(i).trim()); + if(!matcher.matches()){ + error = "Please check the Following Email Address is not Valid .... " +emailList.get(i).toString(); + return error; + }else{ + error = "success"; + } + } + return error; + } + + protected String emailValidation(String email, String response){ + if(email != null){ + String validateEmail = PolicyUtils.validateEmailAddress(email.replace("\"", "")); + if(!validateEmail.contains("success")){ + response += "Email:" + validateEmail+ "
    "; + }else{ + return "success"; + } + } + return response; + } + + private MicroServiceModels getAttributeObject(String name, String version) { + MicroServiceModels workingModel = new MicroServiceModels(); + List microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName:version", name+":"+version); + if(microServiceModelsData != null){ + workingModel = (MicroServiceModels) microServiceModelsData.get(0); + } + return workingModel; + } + + private void pullJsonKeyPairs(JsonNode rootNode) { + Iterator> fieldsIterator = rootNode.fields(); + + while (fieldsIterator.hasNext()) { + Map.Entry field = fieldsIterator.next(); + final String key = field.getKey(); + final JsonNode value = field.getValue(); + if (value.isContainerNode() && !value.isArray()) { + pullJsonKeyPairs(value); // RECURSIVE CALL + } else { + if (value.isArray()){ + String newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, new String[]{"", "", ""}); + mapAttribute.put(key, newValue); + }else { + mapAttribute.put(key, value.toString().trim()); + } + } + } + } + + // Validation for json. + protected static boolean isJSONValid(String data) { + JsonReader jsonReader = null; + try { + new JSONObject(data); + InputStream stream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); + jsonReader = Json.createReader(stream); + LOGGER.info("Json Value is: " + jsonReader.read().toString() ); + } catch (Exception e) { + LOGGER.error("Exception Occured While Validating"+e); + return false; + }finally{ + if(jsonReader != null){ + jsonReader.close(); + } + } + return true; + } + + // Validation for XML. + private boolean isXMLValid(String data) { + SAXParserFactory factory = SAXParserFactory.newInstance(); + factory.setValidating(false); + factory.setNamespaceAware(true); + try { + SAXParser parser = factory.newSAXParser(); + XMLReader reader = parser.getXMLReader(); + reader.setErrorHandler(new XMLErrorHandler()); + reader.parse(new InputSource(new StringReader(data))); + } catch (Exception e) { + LOGGER.error("Exception Occured While Validating"+e); + return false; + } + return true; + } + + // Validation for Properties file. + public boolean isPropValid(String prop) { + Scanner scanner = new Scanner(prop); + while (scanner.hasNextLine()) { + String line = scanner.nextLine(); + line = line.replaceAll("\\s+", ""); + if (line.startsWith("#")) { + continue; + } else { + if (line.contains("=")) { + String[] parts = line.split("="); + if (parts.length < 2) { + scanner.close(); + return false; + } + } else { + scanner.close(); + return false; + } + } + } + scanner.close(); + return true; + } + +} \ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/dao/SystemLogDbDao.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/dao/SystemLogDbDao.java new file mode 100644 index 000000000..9cc6314dd --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/dao/SystemLogDbDao.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.dao; + + +import java.util.List; + +import org.onap.policy.rest.jpa.SystemLogDB; + + + +public abstract interface SystemLogDbDao { + public abstract List getLoggingData(); + public abstract List getSystemAlertData(); +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java new file mode 100644 index 000000000..05bf50f1b --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java @@ -0,0 +1,382 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.daoImp; + +import java.util.ArrayList; +import java.util.List; + +import org.hibernate.Criteria; +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.criterion.Conjunction; +import org.hibernate.criterion.Disjunction; +import org.hibernate.criterion.Projections; +import org.hibernate.criterion.Restrictions; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.PolicyRoles; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service("CommonClassDao") +public class CommonClassDaoImpl implements CommonClassDao{ + + private static final Logger LOGGER = FlexLogger.getLogger(CommonClassDaoImpl.class); + + @Autowired + SessionFactory sessionfactory; + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Override + public List getData(Class className) { + Session session = sessionfactory.openSession(); + List data = null; + try{ + Criteria cr = session.createCriteria(className); + data = cr.list(); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e); + } + } + return data; + } + + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Override + public List getDataById(Class className, String columnName, String key) { + Session session = sessionfactory.openSession(); + List data = null; + try { + Criteria cr = session.createCriteria(className); + if(columnName.contains(":") && key.contains(":")){ + String[] columns = columnName.split(":"); + String[] keys = key.split(":"); + for(int i=0; i < columns.length; i++){ + cr.add(Restrictions.eq(columns[i], keys[i])); + } + }else{ + cr.add(Restrictions.eq(columnName, key)); + } + data = cr.list(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + + @Override + public void save(Object entity) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.persist(entity); + tx.commit(); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving data to Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @Override + public void delete(Object entity) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.delete(entity); + tx.commit(); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting data from Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + + @Override + public void update(Object entity) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.update(entity); + tx.commit(); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating data to Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Override + public List checkDuplicateEntry(String value, String columnName, Class className) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List data = null; + String[] columnNames = null; + if(columnName != null && columnName.contains(":")){ + columnNames = columnName.split(":"); + } + String[] values = null; + if(value != null && value.contains(":")){ + values = value.split(":"); + } + try { + Criteria cr = session.createCriteria(className); + if(columnNames != null && values != null && columnNames.length == values.length){ + for (int i = 0; i < columnNames.length; i++){ + cr.add(Restrictions.eq(columnNames[i],values[i])); + } + }else{ + cr.add(Restrictions.eq(columnName,value)); + } + data = cr.list(); + tx.commit(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying for Duplicate Entries for Table"+e + className); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + + + @SuppressWarnings("unchecked") + @Override + public List getUserRoles() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List rolesData = null; + try { + Criteria cr = session.createCriteria(PolicyRoles.class); + Disjunction disjunction = Restrictions.disjunction(); + Conjunction conjunction1 = Restrictions.conjunction(); + conjunction1.add(Restrictions.eq("role", "admin")); + Conjunction conjunction2 = Restrictions.conjunction(); + conjunction2.add(Restrictions.eq("role", "editor")); + Conjunction conjunction3 = Restrictions.conjunction(); + conjunction3.add(Restrictions.eq("role", "guest")); + disjunction.add(conjunction1); + disjunction.add(conjunction2); + disjunction.add(conjunction3); + rolesData = cr.add(disjunction).list(); + tx.commit(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying PolicyRoles Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return rolesData; + } + + + @Override + public List checkExistingGroupListforUpdate(String arg0, String arg1) { + return null; + } + + + @Override + public void deleteAll() {} + + + @SuppressWarnings("unchecked") + @Override + public List getDataByQuery(String query) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List data = null; + try { + Query hbquery = session.createQuery(query); + data = hbquery.list(); + tx.commit(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Database Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + + + @SuppressWarnings("rawtypes") + @Override + public Object getEntityItem(Class className, String columnName, String key) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + Object data = null; + try { + Criteria cr = session.createCriteria(className); + if(columnName.contains(":") && key.contains(":")){ + String[] columns = columnName.split(":"); + String[] keys = key.split(":"); + for(int i=0; i < columns.length; i++){ + cr.add(Restrictions.eq(columns[i], keys[i])); + } + }else{ + cr.add(Restrictions.eq(columnName, key)); + } + data = cr.list().get(0); + tx.commit(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Database Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + + + @Override + public void updateClAlarms(String arg0, String arg1) {} + + + @Override + public void updateClYaml(String arg0, String arg1) {} + + + @Override + public void updateQuery(String query) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + Query hbquery = session.createQuery(query); + hbquery.executeUpdate(); + tx.commit(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating Database Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Override + public List getDataByColumn(Class className, String columnName) { + Session session = sessionfactory.openSession(); + List data = null; + try{ + Criteria cr = session.createCriteria(className); + cr.setProjection(Projections.property(columnName)); + data = cr.list(); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e); + } + } + return data; + } + + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Override + public List getMultipleDataOnAddingConjunction(Class className, String columnName, List data) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List entityData = null; + try { + Criteria cr = session.createCriteria(className); + Disjunction disjunction = Restrictions.disjunction(); + List conjunctionList = new ArrayList<>(); + String[] columNames = columnName.split(":"); + for(int i =0; i < data.size(); i++){ + String[] entiySplit = data.get(i).split(":"); + Conjunction conjunction = Restrictions.conjunction(); + conjunction.add(Restrictions.eq(columNames[0], entiySplit[0])); + conjunction.add(Restrictions.eq(columNames[1], entiySplit[1])); + conjunctionList.add(conjunction); + } + for(int j =0 ; j < conjunctionList.size(); j++){ + disjunction.add(conjunctionList.get(j)); + } + entityData = cr.add(disjunction).list(); + tx.commit(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table" +className +e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return entityData; + } + +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/SystemLogDbDaoImpl.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/SystemLogDbDaoImpl.java new file mode 100644 index 000000000..4fa64ceb3 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/SystemLogDbDaoImpl.java @@ -0,0 +1,93 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.daoImp; + + +import java.util.List; + +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.springframework.stereotype.Service; + +import org.onap.policy.xacml.api.XACMLErrorConstants; + +import org.hibernate.Transaction; +import org.hibernate.criterion.Restrictions; +import org.onap.policy.conf.HibernateSession; +import org.onap.policy.controller.PolicyController; +import org.onap.policy.dao.SystemLogDbDao; +import org.onap.policy.rest.jpa.SystemLogDB; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + + +@Service("SystemLogDbDao") +public class SystemLogDbDaoImpl implements SystemLogDbDao { + private static final Logger logger = FlexLogger.getLogger(SystemLogDbDaoImpl.class); + @SuppressWarnings("unchecked") + @Override + public List getLoggingData() { + Session session = HibernateSession.getSession(); + Transaction tx = session.beginTransaction(); + List system = null; + try { + String sqlWhere = "date > DATE_SUB(curdate(), INTERVAL 5 DAY) ORDER BY date DESC limit "+PolicyController.getLogTableLimit()+""; + Criteria cr = session.createCriteria(SystemLogDB.class); + cr.add(Restrictions.sqlRestriction(sqlWhere)); + system = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying SystemLogDB Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return system; + } + + @SuppressWarnings("unchecked") + @Override + public List getSystemAlertData() { + Session session = HibernateSession.getSession();; + Transaction tx = session.beginTransaction(); + List system = null; + try { + String sqlWhere = "date > DATE_SUB(curdate(), INTERVAL 5 DAY) and logtype = 'error' ORDER BY date DESC limit "+PolicyController.getSystemAlertTableLimit()+""; + Criteria cr = session.createCriteria(SystemLogDB.class); + cr.add(Restrictions.sqlRestriction(sqlWhere)); + system = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying SystemLogDB Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return system; + } + +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPGroupContainer.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPGroupContainer.java new file mode 100644 index 000000000..ae2144b10 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPGroupContainer.java @@ -0,0 +1,522 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.model; + + +import java.awt.Checkbox; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.utils.PolicyContainer; +import org.onap.policy.utils.PolicyItemSetChangeNotifier; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.api.pap.OnapPDP; +import org.onap.policy.xacml.api.pap.OnapPDPGroup; +import org.onap.policy.xacml.api.pap.PAPPolicyEngine; + +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.api.pap.PDP; +//import com.att.research.xacml.api.pap.PDP; +//import com.att.research.xacml.api.pap.PDPGroup; +import com.att.research.xacml.api.pap.PDPPIPConfig; +import com.att.research.xacml.api.pap.PDPPolicy; + +public class PDPGroupContainer extends PolicyItemSetChangeNotifier implements PolicyContainer.Indexed, PolicyContainer.ItemSetChangeNotifier { + private static final long serialVersionUID = 1L; + private static Logger LOGGER = FlexLogger.getLogger(PDPGroupContainer.class); + + /** + * String identifier of a file's "Id" property. + */ + private static String PROPERTY_ID = "Id"; + + /** + * String identifier of a file's "name" property. + */ + private static String PROPERTY_NAME = "Name"; + + /** + * String identifier of a file's "Description" property. + */ + private static String PROPERTY_DESCRIPTION = "Description"; + + /** + * String identifier of a file's "Default" property. + */ + private static String PROPERTY_DEFAULT = "Default"; + /** + * String identifier of a file's "Status" property. + */ + private static String PROPERTY_STATUS = "Status"; + + /** + * String identifier of a file's "PDPs" property. + */ + private static String PROPERTY_PDPS = "PDPs"; + + /** + * String identifier of a file's "Policies" property. + */ + private static String PROPERTY_POLICIES = "Policies"; + + /** + * String identifier of a file's "PIP Configurations" property. + */ + private static String PROPERTY_PIPCONFIG = "PIP Configurations"; + + /** + * String identifier of a file's "Selected" property. + */ + private static String PROPERTY_SELECTED = "Selected"; + + /** + * List of the string identifiers for the available properties. + */ + private static Collection PDP_PROPERTIES; + + private PAPPolicyEngine papEngine = null; + protected List groups = Collections.synchronizedList(new ArrayList()); + + public PDPGroupContainer(PAPPolicyEngine papPolicyEngine) { + super(); + this.setContainer(this); + // + // + // + this.papEngine = (PAPPolicyEngine) papPolicyEngine; + // + // + // + this.refreshGroups(); + } + + public boolean isSupported(Object itemId) { + if (itemId instanceof OnapPDPGroup) { + return true; + } + return false; + } + + public synchronized void refreshGroups() { + synchronized(this.groups) { + this.groups.clear(); + try { + this.groups.addAll(this.papEngine.getOnapPDPGroups()); + } catch (PAPException e) { + String message = "Unable to retrieve Groups from server: " + e; + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); + } + LOGGER.info("refreshGroups"); + } + // + // Notify that we have changed + // + this.fireItemSetChange(); + } + + public List getGroups() { + return Collections.unmodifiableList(this.groups); + } + + public void makeDefault(OnapPDPGroup group) { + try { + this.papEngine.SetDefaultGroup(group); + } catch (PAPException e) { + String message = "Unable to set Default Group on server: " + e; + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); + } + return; + } + + public void removeGroup(OnapPDPGroup group, OnapPDPGroup newGroup) throws PAPException { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("removeGroup: " + group + " new group for PDPs: " + newGroup); + } + if (group.isDefaultGroup()) { + throw new UnsupportedOperationException("You can't remove the Default Group."); + } + try { + this.papEngine.removeGroup(group, newGroup); + } catch (NullPointerException | PAPException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to removeGroup " + group.getId(), e); + throw new PAPException("Failed to remove group '" + group.getId()+ "'", e); + } + } + + public void removePDP(OnapPDP pdp, OnapPDPGroup group) throws PAPException { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("removePDP: " + pdp + " from group: " + group); + } + try { + this.papEngine.removePDP(pdp); + } catch (PAPException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to removePDP " + pdp.getId(), e); + throw new PAPException("Failed to remove pdp '" + pdp.getId()+ "'", e); + } + } + + public void updatePDP(OnapPDP pdp) { + try { + papEngine.updatePDP(pdp); + } catch (PAPException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + public void updateGroup(OnapPDPGroup group) { + try { + papEngine.updateGroup(group); + } catch (PAPException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + @Override + public Collection getContainerPropertyIds() { + return PDP_PROPERTIES; + } + + @Override + public Collection getItemIds() { + final Collection items = new ArrayList<>(); + items.addAll(this.groups); + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("getItemIds: " + items); + } + return Collections.unmodifiableCollection(items); + } + + @Override + public Class getType(Object propertyId) { + if (propertyId.equals(PROPERTY_ID)) { + return String.class; + } + if (propertyId.equals(PROPERTY_NAME)) { + return String.class; + } + if (propertyId.equals(PROPERTY_DESCRIPTION)) { + return String.class; + } + if (propertyId.equals(PROPERTY_DEFAULT)) { + return Boolean.class; + } + if (propertyId.equals(PROPERTY_STATUS)) { + return String.class; + } + if (propertyId.equals(PROPERTY_PDPS)) { + return Set.class; + } + if (propertyId.equals(PROPERTY_POLICIES)) { + return Set.class; + } + if (propertyId.equals(PROPERTY_PIPCONFIG)) { + return Set.class; + } + if (propertyId.equals(PROPERTY_SELECTED)) { + return Checkbox.class; + } + return null; + } + + @Override + public int size() { + return this.groups.size(); + } + + @Override + public boolean containsId(Object itemId) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("containsId: " + itemId); + } + if (this.isSupported(itemId) == false) { + return false; + } + return this.groups.contains(itemId); + } + + @Override + public Object addItem() throws UnsupportedOperationException { + throw new UnsupportedOperationException("PDP Container cannot add a given item."); + } + + public void addNewGroup(String name, String description) throws NullPointerException, PAPException { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("addNewGroup " + name + " " + description); + } + this.papEngine.newGroup(name, description); + } + + public void addNewPDP(String id, OnapPDPGroup group, String name, String description, int jmxport) throws NullPointerException, PAPException { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("addNewPDP " + id + " " + name + " " + description + " " + jmxport); + } + this.papEngine.newPDP(id, group, name, description, jmxport); + } + + public void movePDP(OnapPDP pdp, OnapPDPGroup group) { + try { + this.papEngine.movePDP(pdp, group); + } catch (PAPException e) { + String message = "Unable to move PDP to new group on server: " + e; + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); + } + return; + } + + @Override + public boolean addContainerProperty(Object propertyId, Class type, Object defaultValue) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Cannot add a container property."); + } + + @Override + public boolean removeContainerProperty(Object propertyId) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Cannot remove a container property."); + } + + @Override + public boolean removeAllItems() throws UnsupportedOperationException { + throw new UnsupportedOperationException("PDP Container cannot remove all items. You must have at least the Default group."); + } + + @Override + public void addItemSetChangeListener(ItemSetChangeListener listener) { + if (getItemSetChangeListeners() == null) { + setItemSetChangeListeners(new LinkedList()); + } + getItemSetChangeListeners().add(listener); + } + + @Override + public Object nextItemId(Object itemId) { + if (this.isSupported(itemId) == false) { + return null; + } + int index = this.groups.indexOf(itemId); + if (index == -1) { + // + // We don't know this group + // + return null; + } + // + // Is it the last one? + // + if (index == this.groups.size() - 1) { + // + // Yes + // + return null; + } + // + // Return the next one + // + return this.groups.get(index + 1); + } + + @Override + public Object prevItemId(Object itemId) { + if (this.isSupported(itemId) == false) { + return null; + } + int index = this.groups.indexOf(itemId); + if (index == -1) { + // + // We don't know this group + // + return null; + } + // + // Is it the first one? + // + if (index == 0) { + // + // Yes + // + return null; + } + // + // Return the previous one + // + return this.groups.get(index - 1); + } + + @Override + public Object firstItemId() { + synchronized (this.groups) { + if (this.groups.size() > 0) { + return this.groups.get(0); + } + } + return null; + } + + @Override + public Object lastItemId() { + synchronized (this.groups) { + if (this.groups.size() > 0) { + return this.groups.get(this.groups.size() - 1); + } + } + return null; + } + + @Override + public boolean isFirstId(Object itemId) { + synchronized (this.groups) { + if (this.groups.size() > 0) { + return (this.groups.get(0).equals(itemId)); + } + } + return false; + } + + @Override + public boolean isLastId(Object itemId) { + synchronized (this.groups) { + if (this.groups.size() > 0) { + return (this.groups.get(this.groups.size() - 1).equals(itemId)); + } + } + return false; + } + + @Override + public Object addItemAfter(Object previousItemId) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Cannot addItemAfter, there really is no real ordering."); + } + + @Override + public int indexOfId(Object itemId) { + return this.groups.indexOf(itemId); + } + + @Override + public Object getIdByIndex(int index) { + return this.groups.get(index); + } + + @Override + public List getItemIds(int startIndex, int numberOfItems) { + synchronized (this.groups) { + int endIndex = startIndex + numberOfItems; + if (endIndex > this.groups.size()) { + endIndex = this.groups.size() - 1; + } + return this.groups.subList(startIndex, endIndex); + } + } + + @Override + public Object addItemAt(int index) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Cannot addItemAt"); + } + + @Override + public boolean removeItem(Object itemId) throws UnsupportedOperationException { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("removeItem: " + itemId); + } + if (this.isSupported(itemId) == false) { + return false; + } + // + // You cannot remove the default group + // + if (((OnapPDPGroup) itemId).getId().equals("Default")) { + throw new UnsupportedOperationException("You can't remove the Default Group."); + } + // + // Remove PDPGroup and move any PDP's in it into the default group + // + try { + this.papEngine.removeGroup((OnapPDPGroup) itemId, this.papEngine.getDefaultGroup()); + return true; + } catch (NullPointerException | PAPException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to remove group", e); + } + return false; + } + + public class PDPGroupItem{ + private final OnapPDPGroup group; + + public PDPGroupItem(OnapPDPGroup itemId) { + this.group = itemId; + } + + public String getId() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("getId: " + this.group); + } + return this.group.getId(); + } + + public String getName() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("getName: " + this.group); + } + return this.group.getName(); + } + + public String getDescription() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("getDescription: " + this.group); + } + return this.group.getDescription(); + } + + public Boolean getDefault() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("getDefault: " + this.group); + } + return this.group.isDefaultGroup(); + } + + + public String getStatus() { + return this.group.getStatus().getStatus().toString(); + } + + public Set getPDPs() { + return Collections.unmodifiableSet(this.group.getPdps()); + } + + public Set getPolicies() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("getPolicies: " + this.group); + } + return this.group.getPolicies(); + } + + public Set getPipConfigs() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("getPIPConfigs: " + this.group); + } + return this.group.getPipConfigs(); + } + } +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPPolicyContainer.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPPolicyContainer.java new file mode 100644 index 000000000..864078439 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPPolicyContainer.java @@ -0,0 +1,348 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.model; + + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Set; + +import org.onap.policy.utils.PolicyContainer; +import org.onap.policy.utils.PolicyItemSetChangeNotifier; +import org.onap.policy.common.logging.flexlogger.*; + +import org.onap.policy.xacml.api.XACMLErrorConstants; +import com.att.research.xacml.api.pap.PDP; +import com.att.research.xacml.api.pap.PDPGroup; +import com.att.research.xacml.api.pap.PDPPolicy; +import org.onap.policy.xacml.std.pap.StdPDPPolicy; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class PDPPolicyContainer extends PolicyItemSetChangeNotifier implements PolicyContainer.Indexed { + private static final long serialVersionUID = 1L; + private static Logger LOGGER = FlexLogger.getLogger(PDPPolicyContainer.class); + + /** + * String identifier of a file's "Id" property. + */ + private static String PROPERTY_ID = "Id"; + + /** + * String identifier of a file's "name" property. + */ + private static String PROPERTY_NAME = "Name"; + + /** + * String identifier of a file's "name" property. + */ + private static String PROPERTY_VERSION = "Version"; + + /** + * String identifier of a file's "Description" property. + */ + private static String PROPERTY_DESCRIPTION = "Description"; + + /** + * String identifier of a file's "IsRoot" property. + */ + private static String PROPERTY_ISROOT = "Root"; + + /** + * List of the string identifiers for the available properties. + */ + private static Collection PDPPOLICY_PROPERTIES; + + private final Object data; + private List policies; + + @SuppressWarnings("unchecked") + public PDPPolicyContainer(Object data) { + super(); + this.data = data; + if (this.data instanceof PDPGroup) { + policies = new ArrayList (((PDPGroup) this.data).getPolicies()); + } + if (this.data instanceof PDP) { + policies = new ArrayList (((PDP) this.data).getPolicies()); + } + if (this.data instanceof Set) { + policies = new ArrayList ((Set)data); + } + if (this.policies == null) { + LOGGER.info("NULL policies"); + throw new NullPointerException("PDPPolicyContainer created with unexpected Object type '" + data.getClass().getName() + "'"); + } + this.setContainer(this); + } + + @Override + public Object nextItemId(Object itemId) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("nextItemId: " + itemId); + } + int index = this.policies.indexOf(itemId); + if (index == -1 || ((index + 1) >= this.policies.size())) { + return null; + } + return new PDPPolicyItem(this.policies.get(index + 1)); + } + + @Override + public Object prevItemId(Object itemId) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("prevItemId: " + itemId); + } + int index = this.policies.indexOf(itemId); + if (index <= 0) { + return null; + } + return new PDPPolicyItem(this.policies.get(index - 1)); + } + + @Override + public Object firstItemId() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("firstItemId: "); + } + if (this.policies.isEmpty()) { + return null; + } + return new PDPPolicyItem(this.policies.get(0)); + } + + @Override + public Object lastItemId() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("lastItemid: "); + } + if (this.policies.isEmpty()) { + return null; + } + return new PDPPolicyItem(this.policies.get(this.policies.size() - 1)); + } + + @Override + public boolean isFirstId(Object itemId) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("isFirstId: " + itemId); + } + if (this.policies.isEmpty()) { + return false; + } + return (itemId.equals(this.policies.get(0))); + } + + @Override + public boolean isLastId(Object itemId) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("isLastId: " + itemId); + } + if (this.policies.isEmpty()) { + return false; + } + return (itemId.equals(this.policies.get(this.policies.size() - 1))); + } + + @Override + public Object addItemAfter(Object previousItemId) + throws UnsupportedOperationException { + return null; + } + + @Override + public Collection getContainerPropertyIds() { + return PDPPOLICY_PROPERTIES; + } + + @Override + public Collection getItemIds() { + final Collection items = new ArrayList<>(); + items.addAll(this.policies); + return Collections.unmodifiableCollection(items); + } + + + @Override + public Class getType(Object propertyId) { + if (propertyId.equals(PROPERTY_ID)) { + return String.class; + } + if (propertyId.equals(PROPERTY_NAME)) { + return String.class; + } + if (propertyId.equals(PROPERTY_VERSION)) { + return String.class; + } + if (propertyId.equals(PROPERTY_DESCRIPTION)) { + return String.class; + } + if (propertyId.equals(PROPERTY_ISROOT)) { + return Boolean.class; + } + return null; + } + + @Override + public int size() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("size: " + this.policies.size()); + } + return this.policies.size(); + } + + @Override + public boolean containsId(Object itemId) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("containsId: " + itemId); + } + return this.policies.contains(itemId); + } + + @Override + public Object addItem() throws UnsupportedOperationException { + throw new UnsupportedOperationException("Cannot add an empty policy."); + } + + @Override + public boolean removeItem(Object itemId) + throws UnsupportedOperationException { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("removeItem: " + itemId); + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + StdPDPPolicy pdpPolicy = null; + try { + pdpPolicy = mapper.readValue(itemId.toString() , StdPDPPolicy.class); + for(int i = 0; i< policies.size(); i++){ + if(policies.get(i).getId().equalsIgnoreCase(pdpPolicy.getId())){ + return this.policies.remove(this.policies.get(i)); + } + } + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Mapping the Removing Policy from PDP Group to Std Policy"+e); + } + return this.policies.remove(itemId); + } + + @Override + public boolean addContainerProperty(Object propertyId, Class type, + Object defaultValue) throws UnsupportedOperationException { + return false; + } + + @Override + public boolean removeContainerProperty(Object propertyId) + throws UnsupportedOperationException { + return false; + } + + @Override + public boolean removeAllItems() throws UnsupportedOperationException { + return false; + } + + @Override + public int indexOfId(Object itemId) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("indexOfId: " + itemId); + } + return this.policies.indexOf(itemId); + } + + @Override + public Object getIdByIndex(int index) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("getIdByIndex: " + index); + } + return this.policies.get(index); + } + + @Override + public List getItemIds(int startIndex, int numberOfItems) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("getItemIds: " + startIndex + " " + numberOfItems); + } + if (numberOfItems < 0) { + throw new IllegalArgumentException(); + } + return this.policies.subList(startIndex, startIndex + numberOfItems); + } + + @Override + public Object addItemAt(int index) throws UnsupportedOperationException { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("addItemAt: " + index); + } + return null; + } + + public class PDPPolicyItem { + private final PDPPolicy policy; + + public PDPPolicyItem(PDPPolicy itemId) { + this.policy = itemId; + } + + public String getId() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("getId: " + this.policy); + } + return this.policy.getId(); + } + + public String getName() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("getName: " + this.policy); + } + return this.policy.getName(); + } + + public String getVersion() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("getVersion: " + this.policy); + } + return this.policy.getVersion(); + } + + public String getDescription() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("getDescription: " + this.policy); + } + return this.policy.getDescription(); + } + + public boolean getRoot() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("isRoot: " + this.policy); + } + return this.policy.isRoot(); + } + + public void setRoot(Boolean root) { + ((StdPDPPolicy)this.policy).setRoot(root); + } + + } +} \ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/model/Roles.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/model/Roles.java new file mode 100644 index 000000000..51e78d0e5 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/model/Roles.java @@ -0,0 +1,99 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.model; + + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.NamedQuery; +import javax.persistence.Table; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@Entity +@Table(name="Roles") +@NamedQuery(name="Roles.findAll", query="SELECT r FROM Roles r ") +@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) +public class Roles implements Serializable{ + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + + @Column(name="id") + private int id; + + @Column(name="loginId") + private String loginId; + + private String name; + private String scope; + private String role; + + public Roles(){ + + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + public String getLoginId() { + return this.loginId; + } + + public void setLoginId(String loginId) { + this.loginId = loginId; + + } + public String getScope() { + return this.scope; + } + + public void setScope(String scope) { + this.scope = scope; + + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + public String getRole() { + return this.role; + } + + public void setRole(String role) { + this.role = role; + } +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/ConfigurableRESTUtils.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/ConfigurableRESTUtils.java new file mode 100644 index 000000000..3e935dd74 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/ConfigurableRESTUtils.java @@ -0,0 +1,163 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.utils; + + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStreamWriter; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.Map; + +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + + +public class ConfigurableRESTUtils { + + protected Logger LOGGER = FlexLogger.getLogger(this.getClass()); + + // + // How the value is returned from the RESTful server + // httpResponseCode means the result is simply the HTTP Response code (e.g. 200, 505, etc.) + // other values identify the encoding used for the string in the body of the HTTP response + // + public enum REST_RESPONSE_FORMAT {httpResponseCode, json } + public enum RESQUEST_METHOD { + GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE; + } + + private String ERROR_RECEIVED = "ERROR - Unexpected HTTP response: "; + + public ConfigurableRESTUtils() { + //Default Constructor + } + + + /** + * Call the RESTful API and return a string containing the result. The string may be either a httpResponseCode or json body + * + * @param fullURI + * @param hardCodedHeaders + * @param httpResponseCodes + * @param responseFormat + * @param jsonBody + * @param requestMethod + * @return String + */ + public String sendRESTRequest(String fullURI, Map hardCodedHeaderMap, + Map httpResponseCodeMap, + REST_RESPONSE_FORMAT responseFormat, + String jsonBody, + RESQUEST_METHOD requestMethod ){ + + String responseString = null; + HttpURLConnection connection = null; + try { + + URL url = new URL(fullURI); + + // + // Open up the connection + // + connection = (HttpURLConnection)url.openConnection(); + // + // Setup our method and headers + // + connection.setRequestMethod(requestMethod.toString()); + + connection.setUseCaches(false); + + // add hard-coded headers + for (String headerName : hardCodedHeaderMap.keySet()) { + connection.addRequestProperty(headerName, hardCodedHeaderMap.get(headerName)); + } + + + + if (jsonBody != null){ + connection.setDoInput(true); + connection.setDoOutput(true); + OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); + out.write(jsonBody); + out.flush(); + out.close(); + } else{ + connection.connect(); + } + + int responseCode = connection.getResponseCode(); + + // check that the response is one we expected (and get the associated value at the same time) + responseString = httpResponseCodeMap.get(responseCode); + if (responseString == null) { + // the response was not configured, meaning it is unexpected and therefore an error + LOGGER.error("Unexpected HTTP response code '" + responseCode + "' from RESTful Server"); + return ERROR_RECEIVED + " code" + responseCode + " from RESTful Server"; + } + + // if the response is contained only in the http code we are done. Otherwise we need to read the body + if (responseFormat == REST_RESPONSE_FORMAT.httpResponseCode) { + return responseString; + } + + // Need to read the body and return that as the responseString. + + responseString = null; + // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file) + java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream()); + scanner.useDelimiter("\\A"); + responseString = scanner.hasNext() ? scanner.next() : ""; + scanner.close(); + LOGGER.debug("RESTful body: " + responseString); + return responseString; + + } catch (Exception e) { + LOGGER.error("HTTP Request/Response from RESTFUL server: " + e); + responseString = ERROR_RECEIVED + e; + } finally { + // cleanup the connection + if (connection != null) { + try { + // For some reason trying to get the inputStream from the connection + // throws an exception rather than returning null when the InputStream does not exist. + InputStream is = null; + try { + is = connection.getInputStream(); + } catch (Exception e1) { + LOGGER.error("Exception Occured"+e1); + } + if (is != null) { + is.close(); + } + + } catch (IOException ex) { + LOGGER.error("Failed to close connection: " + ex, ex); + } + connection.disconnect(); + } + } + return responseString; + + } + +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/PolicyContainer.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/PolicyContainer.java new file mode 100644 index 000000000..d014af031 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/PolicyContainer.java @@ -0,0 +1,121 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.utils; + +import java.io.Serializable; +import java.util.Collection; +import java.util.List; + + +public interface PolicyContainer extends Serializable{ + + public Collection getContainerPropertyIds(); + + public Collection getItemIds(); + + public Class getType(Object propertyId); + + public int size(); + + public boolean containsId(Object itemId); + + public Object addItem() throws UnsupportedOperationException; + + public boolean removeItem(Object itemId) + throws UnsupportedOperationException; + + public boolean addContainerProperty(Object propertyId, Class type, + Object defaultValue) throws UnsupportedOperationException; + + public boolean removeContainerProperty(Object propertyId) + throws UnsupportedOperationException; + + public boolean removeAllItems() throws UnsupportedOperationException; + + public interface Ordered extends PolicyContainer { + + public Object nextItemId(Object itemId); + + public Object prevItemId(Object itemId); + + public Object firstItemId(); + + public Object lastItemId(); + + public boolean isFirstId(Object itemId); + + public boolean isLastId(Object itemId); + + public Object addItemAfter(Object previousItemId) + throws UnsupportedOperationException; + + } + + + public interface Indexed extends Ordered { + + public int indexOfId(Object itemId); + + public Object getIdByIndex(int index); + + public List getItemIds(int startIndex, int numberOfItems); + + public Object addItemAt(int index) throws UnsupportedOperationException; + + public interface ItemAddEvent extends ItemSetChangeEvent { + + public Object getFirstItemId(); + + public int getFirstIndex(); + + public int getAddedItemsCount(); + } + + + public interface ItemRemoveEvent extends ItemSetChangeEvent { + + public Object getFirstItemId(); + + public int getFirstIndex(); + + public int getRemovedItemsCount(); + } + } + + public interface ItemSetChangeEvent extends Serializable { + + public PolicyContainer getContainer(); + } + + public interface ItemSetChangeListener extends Serializable { + + public void containerItemSetChange(PolicyContainer.ItemSetChangeEvent event); + } + + public interface ItemSetChangeNotifier extends Serializable { + + public void addItemSetChangeListener( + PolicyContainer.ItemSetChangeListener listener); + + public void removeItemSetChangeListener( + PolicyContainer.ItemSetChangeListener listener); + } +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/PolicyItemSetChangeNotifier.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/PolicyItemSetChangeNotifier.java new file mode 100644 index 000000000..92764aa4f --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/PolicyItemSetChangeNotifier.java @@ -0,0 +1,95 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.utils; + + +import java.io.Serializable; +import java.util.Collection; +import java.util.EventObject; +import java.util.LinkedList; + +import org.onap.policy.utils.PolicyContainer.ItemSetChangeEvent; +import org.onap.policy.utils.PolicyContainer.ItemSetChangeListener; + + + +public class PolicyItemSetChangeNotifier implements PolicyContainer.ItemSetChangeNotifier { + private static final long serialVersionUID = 1L; + private Collection itemSetChangeListeners = null; + private PolicyContainer container = null; + + public PolicyItemSetChangeNotifier() { + } + + protected void setContainer(PolicyContainer c) { + this.container = c; + } + + @Override + public void addItemSetChangeListener(ItemSetChangeListener listener) { + if (getItemSetChangeListeners() == null) { + setItemSetChangeListeners(new LinkedList()); + } + getItemSetChangeListeners().add(listener); } + + @Override + public void removeItemSetChangeListener(ItemSetChangeListener listener) { + if (getItemSetChangeListeners() != null) { + getItemSetChangeListeners().remove(listener); + } + } + + protected static class BaseItemSetChangeEvent extends EventObject implements + PolicyContainer.ItemSetChangeEvent, Serializable { + private static final long serialVersionUID = 1L; + + protected BaseItemSetChangeEvent(PolicyContainer source) { + super(source); + } + + @Override + public PolicyContainer getContainer() { + return (PolicyContainer) getSource(); + } + } + + protected void setItemSetChangeListeners( + Collection itemSetChangeListeners) { + this.itemSetChangeListeners = itemSetChangeListeners; + } + protected Collection getItemSetChangeListeners() { + return itemSetChangeListeners; + } + + protected void fireItemSetChange() { + fireItemSetChange(new BaseItemSetChangeEvent(this.container)); + } + + protected void fireItemSetChange(ItemSetChangeEvent event) { + if (getItemSetChangeListeners() != null) { + final Object[] l = getItemSetChangeListeners().toArray(); + for (int i = 0; i < l.length; i++) { + ((PolicyContainer.ItemSetChangeListener) l[i]) + .containerItemSetChange(event); + } + } + } +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/XACMLPolicyWriterWithPapNotify.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/XACMLPolicyWriterWithPapNotify.java new file mode 100644 index 000000000..f3e72cb92 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/XACMLPolicyWriterWithPapNotify.java @@ -0,0 +1,483 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.utils; + + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.UnsupportedEncodingException; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.ProtocolException; +import java.net.URL; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.DirectoryNotEmptyException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Base64; +import java.util.UUID; + +import org.onap.policy.rest.XACMLRestProperties; + +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.util.XACMLPolicyWriter; +import com.att.research.xacml.util.XACMLProperties; + +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.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + +/** + * Helper static class that wraps XACMLPolicyWriter + * + * + */ +public class XACMLPolicyWriterWithPapNotify{ + private static final Logger LOGGER = FlexLogger.getLogger(XACMLPolicyWriterWithPapNotify.class); + + /** + * Helper static class that does the work to write a policy set to a file on disk and notify PAP + * + * + */ + public static Path writePolicyFile(Path filename, PolicySetType policySet) { + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet)" + + "\nfilename = " + filename + + "\npolicySet = " + policySet); + } + //write to file + Path path = XACMLPolicyWriter.writePolicyFile(filename, policySet); + + if(path!=null){ + //write to DB + if(notifyPapOfCreateUpdate(filename.toAbsolutePath().toString())){ + return path; + }else{ + //write to DB failed. So, delete the file + try{ + Files.deleteIfExists(path); + }catch(DirectoryNotEmptyException e){ + //We are trying to delete a directory and it is not empty + LOGGER.error("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet): Files.deleteIfExists(path)" + + "\nDirectoryNotEmptyException for path = " + path + + "\nException message = " + e); + }catch(IOException e) { + // File permission problems are caught here. + LOGGER.error("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet): Files.deleteIfExists(path)" + + "\nIOException for path = " + path + + "\nException message = " + e); + }catch(Exception e){ + LOGGER.error("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet): Files.deleteIfExists(path)" + + "\nException for path = " + path + + "\nException message = " + e); + } + return null; + } + + }else{ + return null; + } + } + + /** + * Helper static class that does the work to write a policy set to an output stream and notify PAP + * + * + */ + public static void writePolicyFile(OutputStream os, PolicySetType policySet) { + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(OutputStream os, PolicySetType policySet)" + + "\nos = " + os + + "\npolicySet = " + policySet); + } + //Only used for writing a byte array output stream for a message. No file is written + XACMLPolicyWriter.writePolicyFile(os, policySet); + } + + /** + * Helper static class that does the work to write a policy to a file on disk. + * + * + */ + public static Path writePolicyFile(Path filename, PolicyType policy) { + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicyType policy)" + + "\nfilename = " + filename + + "\npolicy = " + policy); + } + + //write to file + Path path = XACMLPolicyWriter.writePolicyFile(filename, policy); + + if(path!=null){ + //write to DB + if(notifyPapOfCreateUpdate(filename.toAbsolutePath().toString())){ + return path; + }else{ + //write to DB failed so delete the file + try{ + Files.deleteIfExists(path); + }catch(DirectoryNotEmptyException e){ + //We are trying to delete a directory and it is not empty + LOGGER.error("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet)Files.deleteIfExists(path) :" + + "\nDirectoryNotEmptyException for path = " + path + + "\nException message = " + e); + }catch(IOException e) { + // File permission problems are caught here. + LOGGER.error("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet): Files.deleteIfExists(path)" + + "\nIOException for path = " + path + + "\nException message = " + e); + }catch(Exception e){ + LOGGER.error("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet): Files.deleteIfExists(path)" + + "\nException for path = " + path + + "\nException message = " + e); + } + return null; + } + + }else{ + return null; + } + } + + + /** + * Helper static class that does the work to write a policy to a file on disk. + * + * + */ + public static InputStream getXmlAsInputStream(PolicyType policy) { + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("\nXACMLPolicyWriterWithPapNotify.getXmlAsInputStream(PolicyType policy)" + + "\npolicy = " + policy); + } + return XACMLPolicyWriter.getXmlAsInputStream(policy); + } + /** + * Helper static class that does the work to write a policy set to an output stream. + * + * + */ + public static void writePolicyFile(OutputStream os, PolicyType policy) { + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(OutputStream os, PolicyType policy)" + + "\nos = " + os + + "\npolicy = " + policy); + } + //There are no references to this and if there were, it would most likely be used in an http message + XACMLPolicyWriter.writePolicyFile(os, policy); + } + + public static String changeFileNameInXmlWhenRenamePolicy(Path filename) { + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("\nXACMLPolicyWriterWithPapNotify.changeFileNameInXmlWhenRenamePolicy(Path filename)" + + "\nfilename = " + filename); + } + return XACMLPolicyWriter.changeFileNameInXmlWhenRenamePolicy(filename); + } + + public static boolean notifyPapOfPolicyRename(String oldPolicyName, String newPolicyName){ + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("\nXACMLPolicyWriterWithPapNotify.notifyPapOfCreateUpdate(String policyToCreateUpdate) " + + "\npolicyToCreateUpdate = " + " "); + } + Base64.Encoder encoder = Base64.getEncoder(); + String encoding = encoder.encodeToString((XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID)+":"+XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)).getBytes(StandardCharsets.UTF_8)); + HttpURLConnection connection = null; + UUID requestID = UUID.randomUUID(); + URL url; + try { + url = new URL(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL)+"?oldPolicyName="+ URLEncoder.encode(oldPolicyName, "UTF-8")+"&newPolicyName="+URLEncoder.encode(newPolicyName,"UTF-8")); + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("\nnotifyPapOfCreateUpdate: URL = " + url); + } + } catch (MalformedURLException e) { + LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nMalformedURLException message = " + e); + + return false; + } catch (UnsupportedEncodingException e) { + LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nUnsupportedEncodingException message = " + e); + + return false; + } + // + // Open up the connection + // + try { + connection = (HttpURLConnection)url.openConnection(); + } catch (IOException e) { + LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nurl.openConnection() IOException message = " + e); + return false; + } + // + // Setup our method and headers + // + try { + connection.setRequestMethod("PUT"); + } catch (ProtocolException e) { + LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nconnection.setRequestMethod(PUT) ProtocolException message = " + e); + connection.disconnect(); + return false; + } + connection.setRequestProperty("Authorization", "Basic " + encoding); + connection.setRequestProperty("Accept", "text/x-java-properties"); + connection.setRequestProperty("Content-Type", "text/x-java-properties"); + connection.setRequestProperty("requestID", requestID.toString()); + connection.setUseCaches(false); + // + // Adding this in. It seems the HttpUrlConnection class does NOT + // properly forward our headers for POST re-direction. It does so + // for a GET re-direction. + // + // So we need to handle this ourselves. + // + connection.setInstanceFollowRedirects(false); + connection.setDoOutput(true); + connection.setDoInput(true); + try { + connection.connect(); + } catch (IOException e) { + LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nconnection.connect() IOException message = " + e); + connection.disconnect(); + return false; + } + try { + int responseCode = connection.getResponseCode(); + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nconnection.getResponseCode() = " + responseCode); + } + if (responseCode == 200) { + connection.disconnect(); + return true; + } else { + connection.disconnect(); + return false; + } + } catch (IOException e) { + LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nconnection.getResponseCode() IOException message = " + e); + connection.disconnect(); + return false; + } + } + + public static boolean notifyPapOfDelete(String policyToDelete){ + Base64.Encoder encoder = Base64.getEncoder(); + String encoding = encoder.encodeToString((XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID)+":"+XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)).getBytes(StandardCharsets.UTF_8)); + HttpURLConnection connection = null; + UUID requestID = UUID.randomUUID(); + //loggingContext.setRequestID(requestID.toString()); + //loggingContext.transactionStarted(); + String papUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); + if(papUrl == null){ + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + + "PAP url property does not exist"); + return false; + } + String urlString = ""; + try{ + urlString = papUrl+"?groupId=0&isDeleteNotify=1&policyToDelete="+ URLEncoder.encode(policyToDelete, "UTF-8"); + } catch(UnsupportedEncodingException e){ + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + + "Invalid encoding: UTF-8", e); + return false; + } + URL url; + try { + url = new URL(urlString); + } catch (MalformedURLException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error parsing PAP url: " + + urlString + , e); + return false; + } + // + // Open up the connection + // + try { + connection = (HttpURLConnection)url.openConnection(); + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "Error opening HttpURLConnection to: " + + url.toString() + , e); + return false; + } + // + // Setup our method and headers + // + try { + connection.setRequestMethod("DELETE"); + } catch (ProtocolException e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + + "Invalid request method: DELETE", e); + connection.disconnect(); + return false; + } + connection.setRequestProperty("Authorization", "Basic " + encoding); + connection.setRequestProperty("Accept", "text/x-java-properties"); + connection.setRequestProperty("Content-Type", "text/x-java-properties"); + connection.setRequestProperty("requestID", requestID.toString()); + connection.setUseCaches(false); + // + // Adding this in. It seems the HttpUrlConnection class does NOT + // properly forward our headers for POST re-direction. It does so + // for a GET re-direction. + // + // So we need to handle this ourselves. + // + connection.setInstanceFollowRedirects(false); + connection.setDoOutput(true); + connection.setDoInput(true); + try { + connection.connect(); + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "Error connecting HttpURLConnection to: " + + connection.getURL().toString() + , e); + connection.disconnect(); + return false; + } + try { + if (connection.getResponseCode() == 200) { + connection.disconnect(); + //worked + return true; + } else { + connection.disconnect(); + return false; + } + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "Error getting HttpUrlConnection response code for: " + + connection.getURL().toString() + , e); + connection.disconnect(); + return false; + } + } + + public static boolean notifyPapOfCreateUpdate(String policyToCreateUpdate){ + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("\nXACMLPolicyWriterWithPapNotify.notifyPapOfCreateUpdate(String policyToCreateUpdate) " + + "\npolicyToCreateUpdate = " + policyToCreateUpdate); + } + Base64.Encoder encoder = Base64.getEncoder(); + String encoding = encoder.encodeToString((XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID)+":"+XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)).getBytes(StandardCharsets.UTF_8)); + HttpURLConnection connection = null; + UUID requestID = UUID.randomUUID(); + //loggingContext.setRequestID(requestID.toString()); + //loggingContext.transactionStarted(); + URL url; + try { + url = new URL(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL)+"?policyToCreateUpdate="+ URLEncoder.encode(policyToCreateUpdate, "UTF-8")); + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("\nnotifyPapOfCreateUpdate: URL = " + url); + } + } catch (MalformedURLException e) { + LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nMalformedURLException message = " + e); + + return false; + } catch (UnsupportedEncodingException e) { + LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nUnsupportedEncodingException message = " + e); + + return false; + } + // + // Open up the connection + // + try { + connection = (HttpURLConnection)url.openConnection(); + } catch (IOException e) { + LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nurl.openConnection() IOException message = " + e); + return false; + } + // + // Setup our method and headers + // + try { + connection.setRequestMethod("PUT"); + } catch (ProtocolException e) { + LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nconnection.setRequestMethod(PUT) ProtocolException message = " + e); + connection.disconnect(); + return false; + } + connection.setRequestProperty("Authorization", "Basic " + encoding); + connection.setRequestProperty("Accept", "text/x-java-properties"); + connection.setRequestProperty("Content-Type", "text/x-java-properties"); + connection.setRequestProperty("requestID", requestID.toString()); + connection.setUseCaches(false); + // + // Adding this in. It seems the HttpUrlConnection class does NOT + // properly forward our headers for POST re-direction. It does so + // for a GET re-direction. + // + // So we need to handle this ourselves. + // + connection.setInstanceFollowRedirects(false); + connection.setDoOutput(true); + connection.setDoInput(true); + try { + connection.connect(); + } catch (IOException e) { + LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nconnection.connect() IOException message = " + e); + connection.disconnect(); + return false; + } + try { + int responseCode = connection.getResponseCode(); + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nconnection.getResponseCode() = " + responseCode); + } + if (responseCode == 200) { + connection.disconnect(); + return true; + } else { + connection.disconnect(); + return false; + } + } catch (IOException e) { + LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nconnection.getResponseCode() IOException message = " + e); + connection.disconnect(); + return false; + } + } +} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/CheckPDP.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/CheckPDP.java deleted file mode 100644 index ca5aff193..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/CheckPDP.java +++ /dev/null @@ -1,181 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.admin; - - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Base64; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Properties; - -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.rest.XACMLRestProperties; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; - -import com.att.research.xacml.util.XACMLProperties; - -public class CheckPDP { - private static Path pdpPath = null; - private static Long oldModified = null; - private static HashMap pdpMap = null; - private static final Logger LOGGER = FlexLogger.getLogger(CheckPDP.class); - - private CheckPDP(){ - //default constructor - } - public static boolean validateID(String id) { - // ReadFile - try { - readFile(); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); - return false; - } - // Check ID - return (pdpMap.containsKey(id))? true: false; - } - - private static void readFile(){ - String pdpFile = null; - Long newModified = null; - try{ - pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE); - }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot read the PDP ID File" + e); - return; - } - if (pdpFile == null) { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PDP File name not Valid : " + pdpFile); - } - if (pdpPath == null) { - pdpPath = Paths.get(pdpFile); - if (!pdpPath.toFile().exists()) { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "File doesn't exist in the specified Path : " + pdpPath.toString()); - - } - if (pdpPath.toString().endsWith(".properties")) { - readProps(); - } else { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file " + pdpFile); - } - } - // Check if File is updated recently - else { - newModified = pdpPath.toFile().lastModified(); - if (!newModified.equals(oldModified)) { - // File has been updated. - readProps(); - } - } - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - private static void readProps() { - Properties pdpProp = null; - pdpProp = new Properties(); - try { - InputStream in = new FileInputStream(pdpPath.toFile()); - oldModified = pdpPath.toFile().lastModified(); - pdpProp.load(in); - // Read the Properties and Load the PDPs and encoding. - pdpMap = new HashMap<>(); - // Check the Keys for PDP_URLs - Collection unsorted = pdpProp.keySet(); - List sorted = new ArrayList(unsorted); - Collections.sort(sorted); - for (String propKey : sorted) { - loadPDPProperties(propKey, pdpProp); - } - if (pdpMap == null || pdpMap.isEmpty()) { - LOGGER.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Proceed without PDP_URLs"); - } - in.close(); - } catch (IOException e) { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); - } - } - - private static void loadPDPProperties(String propKey, Properties pdpProp){ - if (propKey.startsWith("PDP_URL")) { - String check_val = pdpProp.getProperty(propKey); - if (check_val == null) { - LOGGER.error("Properties file doesn't have the PDP_URL parameter"); - } - if (check_val != null && check_val.contains(";")) { - List pdp_default = new ArrayList<>(Arrays.asList(check_val.split("\\s*;\\s*"))); - int pdpCount = 0; - while (pdpCount < pdp_default.size()) { - String pdpVal = pdp_default.get(pdpCount); - readPDPParam(pdpVal); - pdpCount++; - } - } - } - } - - private static void readPDPParam(String pdpVal){ - if(pdpVal.contains(",")){ - List pdpValues = new ArrayList<>(Arrays.asList(pdpVal.split("\\s*,\\s*"))); - if(pdpValues.size()==3){ - // 1:2 will be UserID:Password - String userID = pdpValues.get(1); - String pass = pdpValues.get(2); - Base64.Encoder encoder = Base64.getEncoder(); - // 0 - PDPURL - pdpMap.put(pdpValues.get(0), encoder.encodeToString((userID+":"+pass).getBytes(StandardCharsets.UTF_8))); - }else{ - LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpValues); - } - }else{ - LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpVal); - } - } - - public static String getEncoding(String pdpID){ - try { - readFile(); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); - } - String encoding = null; - if(pdpMap!=null && (!pdpMap.isEmpty())){ - try{ - encoding = pdpMap.get(pdpID); - } catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); - } - return encoding; - }else{ - return null; - } - } -} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyAdapter.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyAdapter.java deleted file mode 100644 index ef25376f3..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyAdapter.java +++ /dev/null @@ -1,116 +0,0 @@ -package org.openecomp.policy.admin; - -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.controller.ActionPolicyController; -import org.openecomp.policy.controller.CreateBRMSParamController; -import org.openecomp.policy.controller.CreateBRMSRawController; -import org.openecomp.policy.controller.CreateClosedLoopFaultController; -import org.openecomp.policy.controller.CreateClosedLoopPMController; -import org.openecomp.policy.controller.CreateDcaeMicroServiceController; -import org.openecomp.policy.controller.CreateFirewallController; -import org.openecomp.policy.controller.CreatePolicyController; -import org.openecomp.policy.controller.DecisionPolicyController; -import org.openecomp.policy.rest.adapter.PolicyRestAdapter; -import org.openecomp.policy.rest.jpa.PolicyEntity; - -import com.att.research.xacml.util.XACMLProperties; - -public class PolicyAdapter { - - private static final Logger LOGGER = FlexLogger.getLogger(PolicyAdapter.class); - - public void configure(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - String policyNameValue = null ; - String configPolicyName = null ; - if(extendedOptions(policyAdapter, entity)){ - return; - } - if(policyAdapter.getPolicyName().startsWith("Config_PM")){ - policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_")); - configPolicyName = "ClosedLoop_PM"; - }else if(policyAdapter.getPolicyName().startsWith("Config_Fault")){ - policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_")); - configPolicyName = "ClosedLoop_Fault"; - }else if(policyAdapter.getPolicyName().startsWith("Config_FW")){ - policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_")); - configPolicyName = "Firewall Config"; - }else if(policyAdapter.getPolicyName().startsWith("Config_BRMS_Raw")){ - policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_")); - configPolicyName = "BRMS_Raw"; - }else if(policyAdapter.getPolicyName().startsWith("Config_BRMS_Param")){ - policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_")); - configPolicyName = "BRMS_Param"; - }else if(policyAdapter.getPolicyName().startsWith("Config_MS")){ - policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_")); - configPolicyName = "Micro Service"; - }else if(policyAdapter.getPolicyName().startsWith("Action") || policyAdapter.getPolicyName().startsWith("Decision") ){ - policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_")); - }else{ - policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_")); - configPolicyName = "Base"; - } - if (policyNameValue != null) { - policyAdapter.setPolicyType(policyNameValue); - } - if (configPolicyName != null) { - policyAdapter.setConfigPolicyType(configPolicyName); - } - - if("Action".equalsIgnoreCase(policyAdapter.getPolicyType())){ - ActionPolicyController actionController = new ActionPolicyController(); - actionController.prePopulateActionPolicyData(policyAdapter, entity); - } - if("Decision".equalsIgnoreCase(policyAdapter.getPolicyType())){ - DecisionPolicyController decisionController = new DecisionPolicyController(); - decisionController.prePopulateDecisionPolicyData(policyAdapter, entity); - } - if("Config".equalsIgnoreCase(policyAdapter.getPolicyType())){ - if("Base".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ - CreatePolicyController baseController = new CreatePolicyController(); - baseController.prePopulateBaseConfigPolicyData(policyAdapter, entity); - } - else if("BRMS_Raw".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ - CreateBRMSRawController brmsController = new CreateBRMSRawController(); - brmsController.prePopulateBRMSRawPolicyData(policyAdapter, entity); - } - else if("BRMS_Param".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ - CreateBRMSParamController paramController = new CreateBRMSParamController(); - paramController.prePopulateBRMSParamPolicyData(policyAdapter, entity); - } - else if("ClosedLoop_Fault".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ - CreateClosedLoopFaultController newFaultTemplate = new CreateClosedLoopFaultController(); - newFaultTemplate.prePopulateClosedLoopFaultPolicyData(policyAdapter, entity); - } - else if("ClosedLoop_PM".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ - CreateClosedLoopPMController pmController = new CreateClosedLoopPMController(); - pmController.prePopulateClosedLoopPMPolicyData(policyAdapter, entity); - } - else if("Micro Service".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ - CreateDcaeMicroServiceController msController = new CreateDcaeMicroServiceController(); - msController.prePopulateDCAEMSPolicyData(policyAdapter, entity); - } - else if("Firewall Config".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ - CreateFirewallController firewallController = new CreateFirewallController(); - firewallController.prePopulateFWPolicyData(policyAdapter, entity); - } - } - } - - public boolean extendedOptions(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - return false; - } - - public static PolicyAdapter getInstance() { - try { - Class policyAdapter = Class.forName(XACMLProperties.getProperty("policyAdapter.impl.className", PolicyAdapter.class.getName())); - return (PolicyAdapter) policyAdapter.newInstance(); - } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException e) { - LOGGER.error("Exception Occured"+e); - } - return null; - } - - - -} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyManagerServlet.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyManagerServlet.java deleted file mode 100644 index 1821e1031..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyManagerServlet.java +++ /dev/null @@ -1,1477 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.admin; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.nio.charset.StandardCharsets; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.json.Json; -import javax.json.JsonArray; -import javax.json.JsonReader; -import javax.servlet.ServletConfig; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebInitParam; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.compress.utils.IOUtils; -import org.apache.commons.fileupload.FileItem; -import org.apache.commons.fileupload.disk.DiskFileItemFactory; -import org.apache.commons.fileupload.servlet.ServletFileUpload; -import org.apache.http.HttpStatus; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.components.HumanPolicyComponent; -import org.openecomp.policy.controller.PolicyController; -import org.openecomp.policy.controller.PolicyExportAndImportController; -import org.openecomp.policy.model.Roles; -import org.openecomp.policy.rest.XACMLRest; -import org.openecomp.policy.rest.XACMLRestProperties; -import org.openecomp.policy.rest.adapter.PolicyRestAdapter; -import org.openecomp.policy.rest.jpa.ActionBodyEntity; -import org.openecomp.policy.rest.jpa.ConfigurationDataEntity; -import org.openecomp.policy.rest.jpa.PolicyEditorScopes; -import org.openecomp.policy.rest.jpa.PolicyEntity; -import org.openecomp.policy.rest.jpa.PolicyVersion; -import org.openecomp.policy.rest.jpa.UserInfo; -import org.openecomp.policy.utils.PolicyUtils; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.openecomp.policy.xacml.util.XACMLPolicyScanner; -import org.openecomp.portalsdk.core.web.support.UserUtils; - -import com.att.research.xacml.util.XACMLProperties; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - - -@WebServlet(value ="/fm/*", loadOnStartup = 1, initParams = { @WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.admin.properties", description = "The location of the properties file holding configuration information.") }) -public class PolicyManagerServlet extends HttpServlet { - private static final Logger LOGGER = FlexLogger.getLogger(PolicyManagerServlet.class); - private static final long serialVersionUID = -8453502699403909016L; - - private enum Mode { - LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION, EXPORT, SEARCHLIST - } - - private static PolicyController policyController; - public synchronized PolicyController getPolicyController() { - return policyController; - } - - public synchronized static void setPolicyController(PolicyController policyController) { - PolicyManagerServlet.policyController = policyController; - } - - private static String CONTENTTYPE = "application/json"; - private static String SUPERADMIN = "super-admin"; - private static String SUPEREDITOR = "super-editor"; - private static String SUPERGUEST = "super-guest"; - private static String ADMIN = "admin"; - private static String EDITOR = "editor"; - private static String GUEST = "guest"; - private static String RESULT = "result"; - - private static Path closedLoopJsonLocation; - private static JsonArray policyNames; - private static String testUserId = null; - - public static JsonArray getPolicyNames() { - return policyNames; - } - - public static void setPolicyNames(JsonArray policyNames) { - PolicyManagerServlet.policyNames = policyNames; - } - - private static List serviceTypeNamesList = new ArrayList<>(); - - public static List getServiceTypeNamesList() { - return serviceTypeNamesList; - } - - @Override - public void init(ServletConfig servletConfig) throws ServletException { - super.init(servletConfig); - // - // Common initialization - // - XACMLRest.xacmlInit(servletConfig); - // - //Initialize ClosedLoop JSON - // - PolicyManagerServlet.initializeJSONLoad(); - } - - protected static void initializeJSONLoad() { - closedLoopJsonLocation = Paths.get(XACMLProperties - .getProperty(XACMLRestProperties.PROP_ADMIN_CLOSEDLOOP)); - FileInputStream inputStream = null; - JsonReader jsonReader = null; - String location = closedLoopJsonLocation.toString(); - try { - inputStream = new FileInputStream(location); - if (location.endsWith("json")) { - jsonReader = Json.createReader(inputStream); - policyNames = jsonReader.readArray(); - serviceTypeNamesList = new ArrayList<>(); - for (int i = 0; i < policyNames.size(); i++) { - javax.json.JsonObject policyName = policyNames.getJsonObject(i); - String name = policyName.getJsonString("serviceTypePolicyName").getString(); - serviceTypeNamesList.add(name); - } - } - } catch (FileNotFoundException e) { - LOGGER.error("Exception Occured while initializing the JSONConfig file"+e); - }finally{ - try { - if(inputStream != null){ - inputStream.close(); - } - if(jsonReader != null){ - jsonReader.close(); - } - } catch (IOException e) { - LOGGER.error("Exception Occured while closing the File InputStream"+e); - } - } - } - - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - LOGGER.debug("doPost"); - try { - // if request contains multipart-form-data - if (ServletFileUpload.isMultipartContent(request)) { - uploadFile(request, response); - } - // all other post request has json params in body - else { - fileOperation(request, response); - } - } catch (Exception e) { - try { - setError(e, response); - }catch(Exception e1){ - LOGGER.error("Exception Occured"+e1); - } - } - } - - //Set Error Message for Exception - private void setError(Exception t, HttpServletResponse response) throws IOException { - try { - JSONObject responseJsonObject = error(t.getMessage()); - response.setContentType(CONTENTTYPE); - PrintWriter out = response.getWriter(); - out.print(responseJsonObject); - out.flush(); - } catch (Exception x) { - LOGGER.error("Exception Occured"+x); - response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, x.getMessage()); - } - } - - //Policy Import Functionality - private void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException { - try { - String newFile; - Map files = new HashMap<>(); - - List items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); - for (FileItem item : items) { - if (!item.isFormField()) { - // Process form file field (input type="file"). - files.put(item.getName(), item.getInputStream()); - if(item.getName().endsWith(".xls")){ - OutputStream outputStream = null; - try{ - File file = new File(item.getName()); - outputStream = new FileOutputStream(file); - IOUtils.copy(item.getInputStream(), outputStream); - outputStream.close(); - newFile = file.toString(); - PolicyExportAndImportController importController = new PolicyExportAndImportController(); - importController.importRepositoryFile(newFile, request); - }catch(Exception e){ - LOGGER.error("Upload error : " + e); - }finally{ - if(outputStream != null){ - outputStream.close(); - } - } - } - } - } - - JSONObject responseJsonObject = null; - responseJsonObject = this.success(); - response.setContentType(CONTENTTYPE); - PrintWriter out = response.getWriter(); - out.print(responseJsonObject); - out.flush(); - } catch (Exception e) { - LOGGER.debug("Cannot write file"); - throw new ServletException("Cannot write file", e); - } - } - - //File Operation Functionality - private void fileOperation(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - JSONObject responseJsonObject = null; - try { - StringBuilder sb = new StringBuilder(); - BufferedReader br = request.getReader(); - String str; - while ((str = br.readLine()) != null) { - sb.append(str); - } - br.close(); - JSONObject jObj = new JSONObject(sb.toString()); - JSONObject params = jObj.getJSONObject("params"); - Mode mode = Mode.valueOf(params.getString("mode")); - switch (mode) { - case ADDFOLDER: - case ADDSUBSCOPE: - responseJsonObject = addFolder(params, request); - break; - case COPY: - responseJsonObject = copy(params, request); - break; - case DELETE: - responseJsonObject = delete(params, request); - break; - case EDITFILE: - case VIEWPOLICY: - responseJsonObject = editFile(params); - break; - case LIST: - responseJsonObject = list(params, request); - break; - case RENAME: - responseJsonObject = rename(params, request); - break; - case DESCRIBEPOLICYFILE: - responseJsonObject = describePolicy(params); - break; - case SWITCHVERSION: - responseJsonObject = switchVersion(params, request); - break; - case SEARCHLIST: - responseJsonObject = searchPolicyList(params, request); - break; - default: - throw new ServletException("not implemented"); - } - if (responseJsonObject == null) { - responseJsonObject = error("generic error : responseJsonObject is null"); - } - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While doing File Operation" + e); - responseJsonObject = error(e.getMessage()); - } - response.setContentType(CONTENTTYPE); - PrintWriter out = response.getWriter(); - out.print(responseJsonObject); - out.flush(); - } - - private JSONObject searchPolicyList(JSONObject params, HttpServletRequest request) { - Set scopes = null; - List roles = null; - List policyData = new ArrayList<>(); - JSONArray policyList = null; - if(params.has("policyList")){ - policyList = (JSONArray) params.get("policyList"); - } - PolicyController controller = getPolicyControllerInstance(); - List resultList = new ArrayList<>(); - try { - //Get the Login Id of the User from Request - String userId = UserUtils.getUserSession(request).getOrgUserId(); - //Check if the Role and Scope Size are Null get the values from db. - List userRoles = controller.getRoles(userId); - roles = new ArrayList<>(); - scopes = new HashSet<>(); - for(Object role: userRoles){ - Roles userRole = (Roles) role; - roles.add(userRole.getRole()); - if(userRole.getScope() != null){ - if(userRole.getScope().contains(",")){ - String[] multipleScopes = userRole.getScope().split(","); - for(int i =0; i < multipleScopes.length; i++){ - scopes.add(multipleScopes[i]); - } - }else{ - scopes.add(userRole.getScope()); - } - } - } - if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) { - if(scopes.isEmpty()){ - return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin"); - } - Set tempScopes = scopes; - for(String scope : tempScopes){ - List scopesList = queryPolicyEditorScopes(scope); - if(!scopesList.isEmpty()){ - for(int i = 0; i < scopesList.size(); i++){ - PolicyEditorScopes tempScope = (PolicyEditorScopes) scopesList.get(i); - scopes.add(tempScope.getScopeName()); - } - } - } - } - if(policyList!= null){ - for(int i = 0; i < policyList.length(); i++){ - String policyName = policyList.get(i).toString().replace(".xml", ""); - String version = policyName.substring(policyName.lastIndexOf(".")+1); - policyName = policyName.substring(0, policyName.lastIndexOf(".")).replace(".", File.separator); - if(policyName.contains("\\")){ - policyName = policyName.replace("\\", "\\\\"); - } - String policyVersionQuery = "From PolicyVersion where policy_name ='"+policyName+"' and active_version = '"+version+"'and id >0"; - List activeData = controller.getDataByQuery(policyVersionQuery); - if(!activeData.isEmpty()){ - PolicyVersion policy = (PolicyVersion) activeData.get(0); - JSONObject el = new JSONObject(); - el.put("name", policy.getPolicyName().replace(File.separator, "/")); - el.put("date", policy.getModifiedDate()); - el.put("version", policy.getActiveVersion()); - el.put("size", ""); - el.put("type", "file"); - el.put("createdBy", getUserName(policy.getCreatedBy())); - el.put("modifiedBy", getUserName(policy.getModifiedBy())); - resultList.add(el); - } - } - }else{ - if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST) ){ - policyData = controller.getData(PolicyVersion.class); - }else{ - List filterdatas = controller.getData(PolicyVersion.class); - for(Object filter : filterdatas){ - PolicyVersion filterdata = (PolicyVersion) filter; - try{ - String scopeName = filterdata.getPolicyName().substring(0, filterdata.getPolicyName().lastIndexOf(File.separator)); - if(scopes.contains(scopeName)){ - policyData.add(filterdata); - } - }catch(Exception e){ - LOGGER.error("Exception occured while filtering policyversion data"+e); - } - } - } - - if(!policyData.isEmpty()){ - for(int i =0; i < policyData.size(); i++){ - PolicyVersion policy = (PolicyVersion) policyData.get(i); - JSONObject el = new JSONObject(); - el.put("name", policy.getPolicyName().replace(File.separator, "/")); - el.put("date", policy.getModifiedDate()); - el.put("version", policy.getActiveVersion()); - el.put("size", ""); - el.put("type", "file"); - el.put("createdBy", getUserName(policy.getCreatedBy())); - el.put("modifiedBy", getUserName(policy.getModifiedBy())); - resultList.add(el); - } - } - } - }catch(Exception e){ - LOGGER.error("Exception occured while reading policy Data from Policy Version table for Policy Search Data"+e); - } - - return new JSONObject().put(RESULT, resultList); - } - - //Switch Version Functionality - private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException{ - String path = params.getString("path"); - String userId = null; - try { - userId = UserUtils.getUserSession(request).getOrgUserId(); - } catch (Exception e) { - LOGGER.error("Exception Occured while reading userid from cookie" +e); - } - String policyName; - String removeExtension = path.replace(".xml", ""); - if(path.startsWith("/")){ - policyName = removeExtension.substring(1, removeExtension.lastIndexOf(".")); - }else{ - policyName = removeExtension.substring(0, removeExtension.lastIndexOf(".")); - } - - String activePolicy = null; - PolicyController controller = getPolicyControllerInstance(); - if(params.toString().contains("activeVersion")){ - String activeVersion = params.getString("activeVersion"); - String highestVersion = params.get("highestVersion").toString(); - if(Integer.parseInt(activeVersion) > Integer.parseInt(highestVersion)){ - return error("The Version shouldn't be greater than Highest Value"); - }else{ - activePolicy = policyName + "." + activeVersion + ".xml"; - String dbCheckName = activePolicy.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_")){ - dbCheckName = dbCheckName.replace(".Decision_", ":Decision_"); - } - String[] splitDBCheckName = dbCheckName.split(":"); - String peQuery = "FROM PolicyEntity where policyName = '"+splitDBCheckName[1]+"' and scope ='"+splitDBCheckName[0]+"'"; - List policyEntity = controller.getDataByQuery(peQuery); - PolicyEntity pentity = (PolicyEntity) policyEntity.get(0); - if(pentity.isDeleted()){ - return error("The Policy is Not Existing in Workspace"); - }else{ - if(policyName.contains("/")){ - policyName = policyName.replace("/", File.separator); - } - policyName = policyName.substring(policyName.indexOf(File.separator)+1); - if(policyName.contains("\\")){ - policyName = policyName.replace(File.separator, "\\"); - } - policyName = splitDBCheckName[0].replace(".", File.separator)+File.separator+policyName; - String watchPolicyName = policyName; - if(policyName.contains("/")){ - policyName = policyName.replace("/", File.separator); - } - if(policyName.contains("\\")){ - policyName = policyName.replace("\\", "\\\\"); - } - String query = "update PolicyVersion set active_version='"+activeVersion+"' where policy_name ='"+policyName+"' and id >0"; - //query the database - controller.executeQuery(query); - //Policy Notification - PolicyVersion entity = new PolicyVersion(); - entity.setPolicyName(watchPolicyName); - entity.setActiveVersion(Integer.parseInt(activeVersion)); - entity.setModifiedBy(userId); - controller.watchPolicyFunction(entity, activePolicy, "SwitchVersion"); - return success(); - } - } - } - return controller.switchVersionPolicyContent(policyName); - } - - //Describe Policy - private JSONObject describePolicy(JSONObject params) throws ServletException{ - JSONObject object = null; - String path = params.getString("path"); - String policyName = null; - if(path.startsWith("/")){ - path = path.substring(1); - policyName = path.substring(path.lastIndexOf("/") +1); - path = path.replace("/", "."); - }else{ - path = path.replace("/", "."); - policyName = path; - } - if(path.contains("Config_")){ - path = path.replace(".Config_", ":Config_"); - }else if(path.contains("Action_")){ - path = path.replace(".Action_", ":Action_"); - }else if(path.contains("Decision_")){ - path = path.replace(".Decision_", ":Decision_"); - } - PolicyController controller = getPolicyControllerInstance(); - String[] split = path.split(":"); - String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'"; - List queryData = controller.getDataByQuery(query); - if(!queryData.isEmpty()){ - PolicyEntity entity = (PolicyEntity) queryData.get(0); - File temp = null; - BufferedWriter bw = null; - try { - temp = File.createTempFile(policyName, ".tmp"); - bw = new BufferedWriter(new FileWriter(temp)); - bw.write(entity.getPolicyData()); - bw.close(); - object = HumanPolicyComponent.DescribePolicy(temp); - } catch (IOException e) { - LOGGER.error("Exception Occured while Describing the Policy"+e); - }finally{ - if(temp != null){ - temp.delete(); - } - if(bw != null){ - try { - bw.close(); - } catch (IOException e) { - LOGGER.error("Exception Occured while Closing the File Writer"+e); - } - } - } - }else{ - return error("Error Occured while Describing the Policy"); - } - - return object; - } - - //Get the List of Policies and Scopes for Showing in Editor tab - private JSONObject list(JSONObject params, HttpServletRequest request) throws ServletException { - Set scopes = null; - List roles = null; - try { - PolicyController controller = getPolicyControllerInstance(); - //Get the Login Id of the User from Request - String testUserID = getTestUserId(); - String userId = testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId(); - //Check if the Role and Scope Size are Null get the values from db. - List userRoles = controller.getRoles(userId); - roles = new ArrayList<>(); - scopes = new HashSet<>(); - for(Object role: userRoles){ - Roles userRole = (Roles) role; - roles.add(userRole.getRole()); - if(userRole.getScope() != null){ - if(userRole.getScope().contains(",")){ - String[] multipleScopes = userRole.getScope().split(","); - for(int i =0; i < multipleScopes.length; i++){ - scopes.add(multipleScopes[i]); - } - }else{ - scopes.add(userRole.getScope()); - } - } - } - - List resultList = new ArrayList<>(); - boolean onlyFolders = params.getBoolean("onlyFolders"); - String path = params.getString("path"); - if(path.contains("..xml")){ - path = path.replaceAll("..xml", "").trim(); - } - - if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) { - if(scopes.isEmpty()){ - return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin"); - }else{ - if(!"/".equals(path)){ - String tempScope = path.substring(1, path.length()); - tempScope = tempScope.replace("/", File.separator); - scopes.add(tempScope); - } - } - } - - if("/".equals(path)){ - if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){ - List scopesList = queryPolicyEditorScopes(null); - for(Object list : scopesList){ - PolicyEditorScopes scope = (PolicyEditorScopes) list; - if(!(scope.getScopeName().contains(File.separator))){ - JSONObject el = new JSONObject(); - el.put("name", scope.getScopeName()); - el.put("date", scope.getCreatedDate()); - el.put("size", ""); - el.put("type", "dir"); - el.put("createdBy", scope.getUserCreatedBy().getUserName()); - el.put("modifiedBy", scope.getUserModifiedBy().getUserName()); - resultList.add(el); - } - } - }else if(roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)){ - for(Object scope : scopes){ - JSONObject el = new JSONObject(); - List scopesList = queryPolicyEditorScopes(scope.toString()); - if(!scopesList.isEmpty()){ - PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0); - el.put("name", scopeById.getScopeName()); - el.put("date", scopeById.getCreatedDate()); - el.put("size", ""); - el.put("type", "dir"); - el.put("createdBy", scopeById.getUserCreatedBy().getUserName()); - el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName()); - resultList.add(el); - } - } - } - }else{ - try{ - String scopeName = path.substring(path.indexOf("/") +1); - activePolicyList(scopeName, resultList, roles, scopes, onlyFolders); - } catch (Exception ex) { - LOGGER.error("Error Occured While reading Policy Files List"+ex ); - } - } - - return new JSONObject().put(RESULT, resultList); - } catch (Exception e) { - LOGGER.error("list", e); - return error(e.getMessage()); - } - } - - private List queryPolicyEditorScopes(String scopeName){ - String scopeNamequery = ""; - if(scopeName == null){ - scopeNamequery = "from PolicyEditorScopes"; - }else{ - scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"%'"; - } - PolicyController controller = getPolicyControllerInstance(); - List scopesList = controller.getDataByQuery(scopeNamequery); - return scopesList; - } - - //Get Active Policy List based on Scope Selection form Policy Version table - private void activePolicyList(String scopeName, List resultList, List roles, Set scopes, boolean onlyFolders){ - PolicyController controller = getPolicyControllerInstance(); - if(scopeName.contains("/")){ - scopeName = scopeName.replace("/", File.separator); - } - if(scopeName.contains("\\")){ - scopeName = scopeName.replace("\\", "\\\\\\\\"); - } - String query = "from PolicyVersion where POLICY_NAME like '" +scopeName+"%'"; - String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like '" +scopeName+"%'"; - List activePolicies = controller.getDataByQuery(query); - List scopesList = controller.getDataByQuery(scopeNamequery); - for(Object list : scopesList){ - PolicyEditorScopes scopeById = (PolicyEditorScopes) list; - String scope = scopeById.getScopeName(); - if(scope.contains(File.separator)){ - String checkScope = scope.substring(0, scope.lastIndexOf(File.separator)); - if(scopeName.contains("\\\\")){ - scopeName = scopeName.replace("\\\\", File.separator); - } - if(scope.contains(File.separator)){ - scope = scope.substring(checkScope.length()+1); - if(scope.contains(File.separator)){ - scope = scope.substring(0, scope.indexOf(File.separator)); - } - } - if(scopeName.equalsIgnoreCase(checkScope)){ - JSONObject el = new JSONObject(); - el.put("name", scope); - el.put("date", scopeById.getModifiedDate()); - el.put("size", ""); - el.put("type", "dir"); - el.put("createdBy", scopeById.getUserCreatedBy().getUserName()); - el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName()); - resultList.add(el); - } - } - } - String scopeNameCheck = null; - for (Object list : activePolicies) { - PolicyVersion policy = (PolicyVersion) list; - String scopeNameValue = policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator)); - if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){ - if((scopeName.contains("\\\\"))){ - scopeNameCheck = scopeName.replace("\\\\", File.separator); - }else{ - scopeNameCheck = scopeName; - } - if(scopeNameValue.equals(scopeNameCheck)){ - JSONObject el = new JSONObject(); - el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1)); - el.put("date", policy.getModifiedDate()); - el.put("version", policy.getActiveVersion()); - el.put("size", ""); - el.put("type", "file"); - el.put("createdBy", getUserName(policy.getCreatedBy())); - el.put("modifiedBy", getUserName(policy.getModifiedBy())); - resultList.add(el); - } - }else if(!scopes.isEmpty()){ - if(scopes.contains(scopeNameValue)){ - JSONObject el = new JSONObject(); - el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1)); - el.put("date", policy.getModifiedDate()); - el.put("version", policy.getActiveVersion()); - el.put("size", ""); - el.put("type", "file"); - el.put("createdBy", getUserName(policy.getCreatedBy())); - el.put("modifiedBy", getUserName(policy.getModifiedBy())); - resultList.add(el); - } - } - } - } - - private String getUserName(String loginId){ - PolicyController controller = getPolicyControllerInstance(); - UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId); - if(userInfo == null){ - return SUPERADMIN; - } - return userInfo.getUserName(); - } - - //Rename Policy - private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException { - try { - boolean isActive = false; - List policyActiveInPDP = new ArrayList<>(); - Set scopeOfPolicyActiveInPDP = new HashSet<>(); - String userId = UserUtils.getUserSession(request).getOrgUserId(); - String oldPath = params.getString("path"); - String newPath = params.getString("newPath"); - oldPath = oldPath.substring(oldPath.indexOf("/")+1); - newPath = newPath.substring(newPath.indexOf("/")+1); - if(oldPath.endsWith(".xml")){ - JSONObject result = policyRename(oldPath, newPath, userId); - if(!(Boolean)(result.getJSONObject("result").get("success"))){ - return result; - } - }else{ - String scopeName = oldPath; - String newScopeName = newPath; - if(scopeName.contains("/")){ - scopeName = scopeName.replace("/", File.separator); - newScopeName = newScopeName.replace("/", File.separator); - } - if(scopeName.contains("\\")){ - scopeName = scopeName.replace("\\", "\\\\\\\\"); - newScopeName = newScopeName.replace("\\", "\\\\\\\\"); - } - PolicyController controller = getPolicyControllerInstance(); - String query = "from PolicyVersion where POLICY_NAME like'" +scopeName+"%'"; - String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"%'"; - List activePolicies = controller.getDataByQuery(query); - List scopesList = controller.getDataByQuery(scopeNamequery); - for(Object object : activePolicies){ - PolicyVersion activeVersion = (PolicyVersion) object; - String policyOldPath = activeVersion.getPolicyName().replace(File.separator, "/") + "." + activeVersion.getActiveVersion() + ".xml"; - String policyNewPath = policyOldPath.replace(oldPath, newPath); - JSONObject result = policyRename(policyOldPath, policyNewPath, userId); - if(!(Boolean)(result.getJSONObject("result").get("success"))){ - isActive = true; - policyActiveInPDP.add(policyOldPath); - String scope = policyOldPath.substring(0, policyOldPath.lastIndexOf("/")); - scopeOfPolicyActiveInPDP.add(scope.replace("/", File.separator)); - } - } - boolean rename = false; - if(activePolicies.size() != policyActiveInPDP.size()){ - rename = true; - } - - UserInfo userInfo = new UserInfo(); - userInfo.setUserLoginId(userId); - if(policyActiveInPDP.size() == 0){ - renameScope(scopesList, scopeName, newScopeName, controller); - }else if(rename){ - renameScope(scopesList, scopeName, newScopeName, controller); - for(String scope : scopeOfPolicyActiveInPDP){ - PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes(); - editorScopeEntity.setScopeName(scope.replace("\\", "\\\\\\\\")); - editorScopeEntity.setUserCreatedBy(userInfo); - editorScopeEntity.setUserModifiedBy(userInfo); - controller.saveData(editorScopeEntity); - } - } - if(isActive){ - return error("The Following policies rename failed. Since they are active in PDP Groups" +policyActiveInPDP); - } - } - return success(); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e); - return error(e.getMessage()); - } - } - - private void renameScope(List scopesList, String scopeName, String newScopeName, PolicyController controller){ - for(Object object : scopesList){ - PolicyEditorScopes editorScopeEntity = (PolicyEditorScopes) object; - if(scopeName.contains("\\\\\\\\")){ - scopeName = scopeName.replace("\\\\\\\\", File.separator); - newScopeName = newScopeName.replace("\\\\\\\\", File.separator); - } - String scope = editorScopeEntity.getScopeName().replace(scopeName, newScopeName); - editorScopeEntity.setScopeName(scope); - controller.updateData(editorScopeEntity); - } - } - - private JSONObject policyRename(String oldPath, String newPath, String userId) throws ServletException { - try { - PolicyEntity entity = null; - PolicyController controller = getPolicyControllerInstance(); - - String policyVersionName = newPath.replace(".xml", ""); - String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf(".")).replace("/", File.separator); - - String oldpolicyVersionName = oldPath.replace(".xml", ""); - String oldpolicyName = oldpolicyVersionName.substring(0, oldpolicyVersionName.lastIndexOf(".")).replace("/", File.separator); - - String newpolicyName = newPath.replace("/", "."); - String newPolicyCheck = newpolicyName; - if(newPolicyCheck.contains("Config_")){ - newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_"); - }else if(newPolicyCheck.contains("Action_")){ - newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_"); - }else if(newPolicyCheck.contains("Decision_")){ - newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_"); - } - String[] newPolicySplit = newPolicyCheck.split(":"); - - String orignalPolicyName = oldPath.replace("/", "."); - String oldPolicyCheck = orignalPolicyName; - if(oldPolicyCheck.contains("Config_")){ - oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_"); - }else if(oldPolicyCheck.contains("Action_")){ - oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_"); - }else if(oldPolicyCheck.contains("Decision_")){ - oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_"); - } - String[] oldPolicySplit = oldPolicyCheck.split(":"); - - //Check PolicyEntity table with newPolicy Name - String policyEntityquery = "FROM PolicyEntity where policyName = '"+newPolicySplit[1]+"' and scope ='"+newPolicySplit[0]+"'"; - List queryData = controller.getDataByQuery(policyEntityquery); - if(!queryData.isEmpty()){ - entity = (PolicyEntity) queryData.get(0); - return error("Policy rename failed. Since, the policy with same name already exists."); - } - - //Query the Policy Entity with oldPolicy Name - String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf(".")); - String oldpolicyEntityquery = "FROM PolicyEntity where policyName like '"+policyEntityCheck+"%' and scope ='"+oldPolicySplit[0]+"'"; - List oldEntityData = controller.getDataByQuery(oldpolicyEntityquery); - if(!oldEntityData.isEmpty()){ - String groupQuery = "FROM PolicyGroupEntity where ("; - for(int i=0; i groupEntityData = controller.getDataByQuery(groupQuery); - if(groupEntityData.size() > 0){ - return error("Policy rename failed. Since the policy or its version is active in PDP Groups."); - } - for(int i=0; i queryData = controller.getDataByQuery(policyEntityquery); - if(!queryData.isEmpty()){ - return error("Policy already exists with same name"); - } - - //Query the Policy Entity with oldPolicy Name - policyEntityquery = "FROM PolicyEntity where policyName = '"+oldPolicySplit[1]+"' and scope ='"+oldPolicySplit[0]+"'"; - queryData = controller.getDataByQuery(policyEntityquery); - if(!queryData.isEmpty()){ - entity = (PolicyEntity) queryData.get(0); - } - if(entity != null){ - cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId); - success = true; - } - - if(success){ - PolicyVersion entityItem = new PolicyVersion(); - entityItem.setActiveVersion(Integer.parseInt(version)); - entityItem.setHigherVersion(Integer.parseInt(version)); - entityItem.setPolicyName(policyName); - entityItem.setCreatedBy(userId); - entityItem.setModifiedBy(userId); - controller.saveData(entityItem); - } - - LOGGER.debug("copy from: {} to: {}" + oldPath +newPath); - - return success(); - } catch (Exception e) { - LOGGER.error("copy", e); - return error(e.getMessage()); - } - } - - //Delete Policy or Scope Functionality - private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException { - PolicyController controller = getPolicyControllerInstance(); - PolicyRestController restController = new PolicyRestController(); - PolicyEntity policyEntity = null; - String policyNamewithoutExtension; - try { - String userId = UserUtils.getUserSession(request).getOrgUserId(); - String deleteVersion = ""; - String path = params.getString("path"); - LOGGER.debug("delete {}" +path); - if(params.has("deleteVersion")){ - deleteVersion = params.getString("deleteVersion"); - } - path = path.substring(path.indexOf("/")+1); - String policyNamewithExtension = path.replace("/", File.separator); - String policyVersionName = policyNamewithExtension.replace(".xml", ""); - String query = ""; - if(path.endsWith(".xml")){ - policyNamewithoutExtension = policyVersionName.substring(0, policyVersionName.lastIndexOf(".")); - policyNamewithoutExtension = policyNamewithoutExtension.replace(File.separator, "."); - String splitPolicyName = null; - if(policyNamewithoutExtension.contains("Config_")){ - splitPolicyName = policyNamewithoutExtension.replace(".Config_", ":Config_"); - }else if(policyNamewithoutExtension.contains("Action_")){ - splitPolicyName = policyNamewithoutExtension.replace(".Action_", ":Action_"); - }else if(policyNamewithoutExtension.contains("Decision_")){ - splitPolicyName = policyNamewithoutExtension.replace(".Decision_", ":Decision_"); - } - String[] split = splitPolicyName.split(":"); - query = "FROM PolicyEntity where policyName like '"+split[1]+"%' and scope ='"+split[0]+"'"; - }else{ - policyNamewithoutExtension = path.replace(File.separator, "."); - query = "FROM PolicyEntity where scope like '"+policyNamewithoutExtension+"%'"; - } - - List policyEntityobjects = controller.getDataByQuery(query); - String activePolicyName = null; - boolean pdpCheck = false; - if(path.endsWith(".xml")){ - policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator); - int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf(".")+1)); - if("ALL".equals(deleteVersion)){ - if(!policyEntityobjects.isEmpty()){ - for(Object object : policyEntityobjects){ - policyEntity = (PolicyEntity) object; - String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'"; - List groupobject = controller.getDataByQuery(groupEntityquery); - if(!groupobject.isEmpty()){ - pdpCheck = true; - activePolicyName = policyEntity.getScope() +"."+ policyEntity.getPolicyName(); - }else{ - //Delete the entity from Elastic Search Database - String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); - restController.deleteElasticData(searchFileName); - //Delete the entity from Policy Entity table - controller.deleteData(policyEntity); - if(policyNamewithoutExtension.contains("Config_")){ - controller.deleteData(policyEntity.getConfigurationData()); - }else if(policyNamewithoutExtension.contains("Action_")){ - controller.deleteData(policyEntity.getActionBodyEntity()); - } - } - } - } - //Policy Notification - PolicyVersion versionEntity = new PolicyVersion(); - versionEntity.setPolicyName(policyNamewithoutExtension); - versionEntity.setModifiedBy(userId); - controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll"); - if(pdpCheck){ - //Delete from policyVersion table - String getActivePDPPolicyVersion = activePolicyName.replace(".xml", ""); - getActivePDPPolicyVersion = getActivePDPPolicyVersion.substring(getActivePDPPolicyVersion.lastIndexOf(".")+1); - String policyVersionQuery = "update PolicyVersion set active_version='"+getActivePDPPolicyVersion+"' , highest_version='"+getActivePDPPolicyVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0"; - if(policyVersionQuery != null){ - controller.executeQuery(policyVersionQuery); - } - return error("Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: "+activePolicyName); - }else{ - //No Active Policy in PDP. So, deleting all entries from policyVersion table - String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0"; - if(policyVersionQuery != null){ - controller.executeQuery(policyVersionQuery); - } - } - }else if("CURRENT".equals(deleteVersion)){ - String currentVersionPolicyName = policyNamewithExtension.substring(policyNamewithExtension.lastIndexOf(File.separator)+1); - String currentVersionScope = policyNamewithExtension.substring(0, policyNamewithExtension.lastIndexOf(File.separator)).replace(File.separator, "."); - query = "FROM PolicyEntity where policyName = '"+currentVersionPolicyName+"' and scope ='"+currentVersionScope+"'"; - List policyEntitys = controller.getDataByQuery(query); - if(!policyEntitys.isEmpty()){ - policyEntity = (PolicyEntity) policyEntitys.get(0); - } - if(policyEntity != null){ - String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"' and policyid > 0"; - List groupobject = controller.getDataByQuery(groupEntityquery); - if(groupobject.isEmpty()){ - //Delete the entity from Elastic Search Database - String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); - restController.deleteElasticData(searchFileName); - //Delete the entity from Policy Entity table - controller.deleteData(policyEntity); - if(policyNamewithoutExtension.contains("Config_")){ - controller.deleteData(policyEntity.getConfigurationData()); - }else if(policyNamewithoutExtension.contains("Action_")){ - controller.deleteData(policyEntity.getActionBodyEntity()); - } - - if(version > 1){ - int highestVersion = 0; - if(!policyEntityobjects.isEmpty()){ - for(Object object : policyEntityobjects){ - policyEntity = (PolicyEntity) object; - String policyEntityName = policyEntity.getPolicyName().replace(".xml", ""); - int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf(".")+1)); - if(policyEntityVersion > highestVersion && policyEntityVersion != version){ - highestVersion = policyEntityVersion; - } - } - } - - //Policy Notification - PolicyVersion entity = new PolicyVersion(); - entity.setPolicyName(policyNamewithoutExtension); - entity.setActiveVersion(highestVersion); - entity.setModifiedBy(userId); - controller.watchPolicyFunction(entity, policyNamewithExtension, "DeleteOne"); - - String updatequery = "update PolicyVersion set active_version='"+highestVersion+"' , highest_version='"+highestVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"'"; - controller.executeQuery(updatequery); - }else{ - String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0"; - if(policyVersionQuery != null){ - controller.executeQuery(policyVersionQuery); - } - } - }else{ - return error("Policy can't be deleted, it is active in PDP Groups. PolicyName: '"+policyEntity.getScope() + "." +policyEntity.getPolicyName()+"'"); - } - } - } - }else{ - List activePoliciesInPDP = new ArrayList(); - if(!policyEntityobjects.isEmpty()){ - for(Object object : policyEntityobjects){ - policyEntity = (PolicyEntity) object; - String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'"; - List groupobject = controller.getDataByQuery(groupEntityquery); - if(!groupobject.isEmpty()){ - pdpCheck = true; - activePoliciesInPDP.add(policyEntity.getScope()+"."+policyEntity.getPolicyName()); - }else{ - //Delete the entity from Elastic Search Database - String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); - restController.deleteElasticData(searchFileName); - //Delete the entity from Policy Entity table - controller.deleteData(policyEntity); - policyNamewithoutExtension = policyEntity.getPolicyName(); - if(policyNamewithoutExtension.contains("Config_")){ - controller.deleteData(policyEntity.getConfigurationData()); - }else if(policyNamewithoutExtension.contains("Action_")){ - controller.deleteData(policyEntity.getActionBodyEntity()); - } - } - } - //Delete from policyVersion and policyEditor Scope table - String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"+path.replace("\\", "\\\\")+"%' and id >0"; - controller.executeQuery(policyVersionQuery); - - //Policy Notification - PolicyVersion entity = new PolicyVersion(); - entity.setPolicyName(path); - entity.setModifiedBy(userId); - controller.watchPolicyFunction(entity, path, "DeleteScope"); - if(pdpCheck){ - //Add Active Policies List to PolicyVersionTable - for(int i =0; i < activePoliciesInPDP.size(); i++){ - String activePDPPolicyName = activePoliciesInPDP.get(i).replace(".xml", ""); - int activePDPPolicyVersion = Integer.parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf(".")+1)); - activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf(".")).replace(".", File.separator); - PolicyVersion insertactivePDPVersion = new PolicyVersion(); - insertactivePDPVersion.setPolicyName(activePDPPolicyName); - insertactivePDPVersion.setHigherVersion(activePDPPolicyVersion); - insertactivePDPVersion.setActiveVersion(activePDPPolicyVersion); - insertactivePDPVersion.setCreatedBy(userId); - insertactivePDPVersion.setModifiedBy(userId); - controller.saveData(insertactivePDPVersion); - } - - return error("All the Policies has been deleted in Scope. Except the following list of Policies:"+activePoliciesInPDP); - }else{ - String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0"; - controller.executeQuery(policyScopeQuery); - } - }else{ - String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0"; - controller.executeQuery(policyScopeQuery); - } - } - return success(); - } catch (Exception e) { - LOGGER.error("delete", e); - return error(e.getMessage()); - } - } - - //Edit the Policy - private JSONObject editFile(JSONObject params) throws ServletException { - // get content - try { - PolicyController controller = getPolicyControllerInstance(); - String mode = params.getString("mode"); - String path = params.getString("path"); - LOGGER.debug("editFile path: {}"+ path); - - String domain = path.substring(1, path.lastIndexOf("/")); - domain = domain.replace("/", "."); - - path = path.substring(1); - path = path.replace("/", "."); - String dbCheckName = path; - if(dbCheckName.contains("Config_")){ - dbCheckName = dbCheckName.replace(".Config_", ":Config_"); - }else if(dbCheckName.contains("Action_")){ - dbCheckName = dbCheckName.replace(".Action_", ":Action_"); - }else if(dbCheckName.contains("Decision_")){ - dbCheckName = dbCheckName.replace(".Decision_", ":Decision_"); - } - - String[] split = dbCheckName.split(":"); - String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'"; - List queryData = controller.getDataByQuery(query); - PolicyEntity entity = (PolicyEntity) queryData.get(0); - InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8)); - - - Object policy = XACMLPolicyScanner.readPolicy(stream); - PolicyRestAdapter policyAdapter = new PolicyRestAdapter(); - policyAdapter.setData(policy); - - if("viewPolicy".equalsIgnoreCase(mode)){ - policyAdapter.setReadOnly(true); - policyAdapter.setEditPolicy(false); - }else{ - policyAdapter.setReadOnly(false); - policyAdapter.setEditPolicy(true); - } - policyAdapter.setDomain(domain); - policyAdapter.setDomainDir(domain); - policyAdapter.setPolicyData(policy); - String policyName = path.replace(".xml", ""); - policyName = policyName.substring(0, policyName.lastIndexOf(".")); - policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf(".")+1)); - - PolicyAdapter setpolicyAdapter = PolicyAdapter.getInstance(); - setpolicyAdapter.configure(policyAdapter,entity); - - policyAdapter.setParentPath(null); - ObjectMapper mapper = new ObjectMapper(); - String json = mapper.writeValueAsString(policyAdapter); - JsonNode jsonNode = mapper.readTree(json); - - return new JSONObject().put(RESULT, jsonNode); - } catch (Exception e) { - LOGGER.error("editFile", e); - return error(e.getMessage()); - } - } - - //Add Scopes - private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException { - PolicyController controller = getPolicyControllerInstance(); - String name = ""; - try { - String userId = UserUtils.getUserSession(request).getOrgUserId(); - String path = params.getString("path"); - try{ - if(params.has("subScopename")){ - if(!params.getString("subScopename").equals("")){ - name = params.getString("path").replace("/", File.separator) + File.separator +params.getString("subScopename"); - } - }else{ - name = params.getString("name"); - } - }catch(Exception e){ - name = params.getString("name"); - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope"+e); - } - String validateName; - if(name.contains(File.separator)){ - validateName = name.substring(name.lastIndexOf(File.separator)+1); - }else{ - validateName = name; - } - if(!name.isEmpty()){ - String validate = PolicyUtils.emptyPolicyValidator(validateName); - if(!validate.contains("success")){ - return error(validate); - } - } - LOGGER.debug("addFolder path: {} name: {}" + path +name); - if(!name.equals("")){ - if(name.startsWith(File.separator)){ - name = name.substring(1); - } - PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, "scopeName", name); - if(entity == null){ - UserInfo userInfo = new UserInfo(); - userInfo.setUserLoginId(userId); - PolicyEditorScopes newScope = new PolicyEditorScopes(); - newScope.setScopeName(name); - newScope.setUserCreatedBy(userInfo); - newScope.setUserModifiedBy(userInfo); - controller.saveData(newScope); - }else{ - return error("Scope Already Exists"); - } - } - return success(); - } catch (Exception e) { - LOGGER.error("addFolder", e); - return error(e.getMessage()); - } - } - - //Return Error Object - private JSONObject error(String msg) throws ServletException { - try { - JSONObject result = new JSONObject(); - result.put("success", false); - result.put("error", msg); - return new JSONObject().put(RESULT, result); - } catch (JSONException e) { - throw new ServletException(e); - } - } - - //Return Success Object - private JSONObject success() throws ServletException { - try { - JSONObject result = new JSONObject(); - result.put("success", true); - result.put("error", (Object) null); - return new JSONObject().put(RESULT, result); - } catch (JSONException e) { - throw new ServletException(e); - } - } - - private PolicyController getPolicyControllerInstance(){ - return policyController != null ? getPolicyController() : new PolicyController(); - } - - public String getTestUserId() { - return testUserId; - } - - public static void setTestUserId(String testUserId) { - PolicyManagerServlet.testUserId = testUserId; - } -} \ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyNotificationMail.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyNotificationMail.java deleted file mode 100644 index 1a535dc76..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyNotificationMail.java +++ /dev/null @@ -1,163 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.admin; - -import java.io.File; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.List; -import java.util.Properties; - -import javax.mail.MessagingException; -import javax.mail.internet.InternetAddress; -import javax.mail.internet.MimeMessage; - -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.controller.PolicyController; -import org.openecomp.policy.rest.dao.CommonClassDao; -import org.openecomp.policy.rest.jpa.PolicyVersion; -import org.openecomp.policy.rest.jpa.WatchPolicyNotificationTable; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.springframework.beans.factory.annotation.Configurable; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.mail.javamail.JavaMailSenderImpl; -import org.springframework.mail.javamail.MimeMessageHelper; - -@Configurable -public class PolicyNotificationMail{ - private static Logger policyLogger = FlexLogger.getLogger(PolicyNotificationMail.class); - - @Bean - public JavaMailSenderImpl javaMailSenderImpl(){ - JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); - mailSender.setHost(PolicyController.getSmtpHost()); - mailSender.setPort(Integer.parseInt(PolicyController.getSmtpPort())); - mailSender.setUsername(PolicyController.getSmtpUsername()); - mailSender.setPassword(PolicyController.getSmtpPassword()); - Properties prop = mailSender.getJavaMailProperties(); - prop.put("mail.transport.protocol", "smtp"); - prop.put("mail.smtp.auth", "true"); - prop.put("mail.smtp.starttls.enable", "true"); - prop.put("mail.debug", "true"); - return mailSender; - } - - public void sendMail(PolicyVersion entityItem, String policyName, String mode, CommonClassDao policyNotificationDao) throws MessagingException { - String from = PolicyController.getSmtpUsername(); - String to = ""; - String subject = ""; - String message = ""; - DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); - Date date = new Date(); - if("EditPolicy".equalsIgnoreCase(mode)){ - subject = "Policy has been Updated : "+entityItem.getPolicyName(); - message = "The Policy Which you are watching in " + PolicyController.getSmtpApplicationName() + " has been Updated" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' + "Active Version : " +entityItem.getActiveVersion() - + '\n' + '\n' + "Modified By : " +entityItem.getModifiedBy() + '\n' + "Modified Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; - } - if("Rename".equalsIgnoreCase(mode)){ - subject = "Policy has been Renamed : "+entityItem.getPolicyName(); - message = "The Policy Which you are watching in " + PolicyController.getSmtpApplicationName() + " has been Renamed" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' + "Active Version : " +entityItem.getActiveVersion() - + '\n' + '\n' + "Renamed By : " +entityItem.getModifiedBy() + '\n' + "Renamed Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; - } - if("DeleteAll".equalsIgnoreCase(mode)){ - subject = "Policy has been Deleted : "+entityItem.getPolicyName(); - message = "The Policy Which you are watching in " + PolicyController.getSmtpApplicationName() + " has been Deleted with All Versions" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' - + '\n' + '\n' + "Deleted By : " +entityItem.getModifiedBy() + '\n' + "Deleted Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; - } - if("DeleteOne".equalsIgnoreCase(mode)){ - subject = "Policy has been Deleted : "+entityItem.getPolicyName(); - message = "The Policy Which you are watching in " + PolicyController.getSmtpApplicationName() + " has been Deleted" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' +"Policy Version : " +entityItem.getActiveVersion() - + '\n' + '\n' + "Deleted By : " +entityItem.getModifiedBy() + '\n' + "Deleted Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; - } - if("DeleteScope".equalsIgnoreCase(mode)){ - subject = "Scope has been Deleted : "+entityItem.getPolicyName(); - message = "The Scope Which you are watching in " + PolicyController.getSmtpApplicationName() + " has been Deleted" + '\n' + '\n' + '\n'+ "Scope + Scope Name : " + policyName + '\n' - + '\n' + '\n' + "Deleted By : " +entityItem.getModifiedBy() + '\n' + "Deleted Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; - } - if("SwitchVersion".equalsIgnoreCase(mode)){ - subject = "Policy has been SwitchedVersion : "+entityItem.getPolicyName(); - message = "The Policy Which you are watching in " + PolicyController.getSmtpApplicationName() + " has been SwitchedVersion" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' + "Active Version : " +entityItem.getActiveVersion() - + '\n' + '\n' + "Switched By : " +entityItem.getModifiedBy() + '\n' + "Switched Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; - } - if("Move".equalsIgnoreCase(mode)){ - subject = "Policy has been Moved to Other Scope : "+entityItem.getPolicyName(); - message = "The Policy Which you are watching in " + PolicyController.getSmtpApplicationName() + " has been Moved to Other Scope" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' + "Active Version : " +entityItem.getActiveVersion() - + '\n' + '\n' + "Moved By : " +entityItem.getModifiedBy() + '\n' + "Moved Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; - } - String policyFileName = entityItem.getPolicyName(); - String checkPolicyName = policyName; - if(policyFileName.contains("/")){ - policyFileName = policyFileName.substring(0, policyFileName.indexOf("/")); - policyFileName = policyFileName.replace("/", File.separator); - } - if(policyFileName.contains("\\")){ - policyFileName = policyFileName.substring(0, policyFileName.indexOf("\\")); - policyFileName = policyFileName.replace("\\", "\\\\"); - } - - String query = "from WatchPolicyNotificationTable where policyName like'" +policyFileName+"%'"; - boolean sendFlag = false; - List watchList = policyNotificationDao.getDataByQuery(query); - if(watchList != null && !watchList.isEmpty()){ - for(Object watch : watchList){ - WatchPolicyNotificationTable list = (WatchPolicyNotificationTable) watch; - String watchPolicyName = list.getPolicyName(); - if(watchPolicyName.contains("Config_") || watchPolicyName.contains("Action_") || watchPolicyName.contains("Decision_")){ - if(watchPolicyName.equals(checkPolicyName)){ - sendFlag = true; - }else{ - sendFlag = false; - } - } - if(sendFlag){ - AnnotationConfigApplicationContext ctx = null; - try { - to = list.getLoginIds()+"@"+PolicyController.getSmtpEmailExtension(); - to = to.trim(); - ctx = new AnnotationConfigApplicationContext(); - ctx.register(PolicyNotificationMail.class); - ctx.refresh(); - JavaMailSenderImpl mailSender = ctx.getBean(JavaMailSenderImpl.class); - MimeMessage mimeMessage = mailSender.createMimeMessage(); - MimeMessageHelper mailMsg = new MimeMessageHelper(mimeMessage); - mailMsg.setFrom(new InternetAddress(from, "Policy Notification System")); - mailMsg.setTo(to); - mailMsg.setSubject(subject); - mailMsg.setText(message); - mailSender.send(mimeMessage); - if(mode.equalsIgnoreCase("Rename") || mode.contains("Delete") || mode.contains("Move")){ - policyNotificationDao.delete(watch); - } - } catch (Exception e) { - policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Exception Occured in Policy Notification" +e); - }finally{ - if(ctx != null){ - ctx.close(); - } - } - } - } - } - } -} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyRestController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyRestController.java deleted file mode 100644 index 08ef99f94..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyRestController.java +++ /dev/null @@ -1,443 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.admin; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.net.HttpURLConnection; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Base64; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.fileupload.FileItem; -import org.apache.commons.fileupload.disk.DiskFileItemFactory; -import org.apache.commons.fileupload.servlet.ServletFileUpload; -import org.apache.commons.io.IOUtils; -import org.json.JSONObject; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.controller.CreateClosedLoopFaultController; -import org.openecomp.policy.controller.CreateDcaeMicroServiceController; -import org.openecomp.policy.controller.CreateFirewallController; -import org.openecomp.policy.controller.PolicyController; -import org.openecomp.policy.rest.XACMLRestProperties; -import org.openecomp.policy.rest.adapter.PolicyRestAdapter; -import org.openecomp.policy.rest.dao.CommonClassDao; -import org.openecomp.policy.rest.jpa.PolicyVersion; -import org.openecomp.policy.utils.PolicyUtils; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.openecomp.portalsdk.core.controller.RestrictedBaseController; -import org.openecomp.portalsdk.core.web.support.UserUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.client.HttpClientErrorException; -import org.springframework.web.client.RestTemplate; -import org.springframework.web.servlet.ModelAndView; - -import com.att.research.xacml.util.XACMLProperties; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; - -@RestController -@RequestMapping("/") -public class PolicyRestController extends RestrictedBaseController{ - - private static final Logger policyLogger = FlexLogger.getLogger(PolicyRestController.class); - - private static final String modal = "model"; - private static final String importDictionary = "import_dictionary"; - - @Autowired - CommonClassDao commonClassDao; - - @RequestMapping(value={"/policycreation/save_policy"}, method={RequestMethod.POST}) - public void policyCreationController(HttpServletRequest request, HttpServletResponse response) { - String userId = UserUtils.getUserSession(request).getOrgUserId(); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - try{ - JsonNode root = mapper.readTree(request.getReader()); - - PolicyRestAdapter policyData = mapper.readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class); - - if("file".equals(root.get(PolicyController.getPolicydata()).get(modal).get("type").toString().replace("\"", ""))){ - policyData.setEditPolicy(true); - } - if(root.get(PolicyController.getPolicydata()).get(modal).get("path").size() != 0){ - String dirName = ""; - for(int i = 0; i < root.get(PolicyController.getPolicydata()).get(modal).get("path").size(); i++){ - dirName = dirName.replace("\"", "") + root.get(PolicyController.getPolicydata()).get(modal).get("path").get(i).toString().replace("\"", "") + File.separator; - } - if(policyData.isEditPolicy()){ - policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator))); - }else{ - policyData.setDomainDir(dirName + root.get(PolicyController.getPolicydata()).get(modal).get("name").toString().replace("\"", "")); - } - }else{ - String domain = root.get(PolicyController.getPolicydata()).get("model").get("name").toString(); - if(domain.contains("/")){ - domain = domain.substring(0, domain.lastIndexOf('/')).replace("/", File.separator); - } - domain = domain.replace("\"", ""); - policyData.setDomainDir(domain); - } - - if(policyData.getConfigPolicyType() != null){ - if("ClosedLoop_Fault".equalsIgnoreCase(policyData.getConfigPolicyType())){ - CreateClosedLoopFaultController faultController = new CreateClosedLoopFaultController(); - policyData = faultController.setDataToPolicyRestAdapter(policyData, root); - }else if("Firewall Config".equalsIgnoreCase(policyData.getConfigPolicyType())){ - CreateFirewallController fwController = new CreateFirewallController(); - policyData = fwController.setDataToPolicyRestAdapter(policyData); - }else if("Micro Service".equalsIgnoreCase(policyData.getConfigPolicyType())){ - CreateDcaeMicroServiceController msController = new CreateDcaeMicroServiceController(); - policyData = msController.setDataToPolicyRestAdapter(policyData, root); - } - } - - policyData.setUserId(userId); - - String result; - String body = PolicyUtils.objectToJsonString(policyData); - String uri = request.getRequestURI(); - ResponseEntity responseEntity = sendToPAP(body, uri, HttpMethod.POST); - if(responseEntity != null && responseEntity.getBody().equals(HttpServletResponse.SC_CONFLICT)){ - result = "PolicyExists"; - }else if(responseEntity != null){ - result = responseEntity.getBody().toString(); - String policyName = responseEntity.getHeaders().get("policyName").get(0); - if(policyData.isEditPolicy() && "success".equalsIgnoreCase(result)){ - PolicyNotificationMail email = new PolicyNotificationMail(); - String mode = "EditPolicy"; - String watchPolicyName = policyName.replace(".xml", ""); - String version = watchPolicyName.substring(watchPolicyName.lastIndexOf('.')+1); - watchPolicyName = watchPolicyName.substring(0, watchPolicyName.lastIndexOf('.')).replace(".", File.separator); - String policyVersionName = watchPolicyName.replace(".", File.separator); - watchPolicyName = watchPolicyName + "." + version + ".xml"; - PolicyVersion entityItem = new PolicyVersion(); - entityItem.setPolicyName(policyVersionName); - entityItem.setActiveVersion(Integer.parseInt(version)); - entityItem.setModifiedBy(userId); - email.sendMail(entityItem, watchPolicyName, mode, commonClassDao); - } - }else{ - result = "Response is null from PAP"; - } - - response.setCharacterEncoding(PolicyController.getCharacterencoding()); - response.setContentType(PolicyController.getContenttype()); - request.setCharacterEncoding(PolicyController.getCharacterencoding()); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(result); - JSONObject j = new JSONObject("{policyData: " + responseString + "}"); - out.write(j.toString()); - }catch(Exception e){ - policyLogger.error("Exception Occured while saving policy" , e); - } - } - - - private ResponseEntity sendToPAP(String body, String requestURI, HttpMethod method){ - String papUrl = PolicyController.getPapUrl(); - String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); - String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS); - - Base64.Encoder encoder = Base64.getEncoder(); - String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8)); - HttpHeaders headers = new HttpHeaders(); - headers.set("Authorization", "Basic " + encoding); - headers.set("Content-Type", PolicyController.getContenttype()); - - RestTemplate restTemplate = new RestTemplate(); - HttpEntity requestEntity = new HttpEntity<>(body, headers); - ResponseEntity result = null; - HttpClientErrorException exception = null; - - try{ - result = restTemplate.exchange(papUrl + requestURI, method, requestEntity, String.class); - }catch(Exception e){ - policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl, e); - exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage()); - if("409 Conflict".equals(e.getMessage())){ - return ResponseEntity.ok(HttpServletResponse.SC_CONFLICT); - } - } - if(exception != null && exception.getStatusCode()!=null){ - if(exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)){ - String message = XACMLErrorConstants.ERROR_PERMISSIONS +":"+exception.getStatusCode()+":" + "ERROR_AUTH_GET_PERM" ; - policyLogger.error(message); - } - if(exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)){ - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString(); - policyLogger.error(message); - } - if(exception.getStatusCode().equals(HttpStatus.NOT_FOUND)){ - String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl + exception; - policyLogger.error(message); - } - String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString(); - policyLogger.error(message); - } - return result; - } - - private String callPAP(HttpServletRequest request , String method, String uriValue){ - String uri = uriValue; - String boundary = null; - String papUrl = PolicyController.getPapUrl(); - String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); - String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS); - - Base64.Encoder encoder = Base64.getEncoder(); - String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8)); - HttpHeaders headers = new HttpHeaders(); - headers.set("Authorization", "Basic " + encoding); - headers.set("Content-Type", PolicyController.getContenttype()); - - - HttpURLConnection connection = null; - List items; - FileItem item = null; - File file = null; - if(uri.contains(importDictionary)){ - try { - items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); - item = items.get(0); - file = new File(item.getName()); - String newFile = file.toString(); - uri = uri +"&dictionaryName="+newFile; - } catch (Exception e2) { - policyLogger.error("Exception Occured while calling PAP with import dictionary request"+e2); - } - } - - try { - URL url = new URL(papUrl + uri); - connection = (HttpURLConnection)url.openConnection(); - connection.setRequestMethod(method); - connection.setUseCaches(false); - connection.setInstanceFollowRedirects(false); - connection.setRequestProperty("Authorization", "Basic " + encoding); - connection.setDoOutput(true); - connection.setDoInput(true); - - if(!uri.contains("searchPolicy?action=delete&")){ - - if(!(uri.endsWith("set_BRMSParamData") || uri.contains(importDictionary))){ - connection.setRequestProperty("Content-Type",PolicyController.getContenttype()); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = null; - try { - root = mapper.readTree(request.getReader()); - }catch (Exception e1) { - policyLogger.error("Exception Occured while calling PAP"+e1); - } - - ObjectMapper mapper1 = new ObjectMapper(); - mapper1.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true); - - Object obj = mapper1.treeToValue(root, Object.class); - String json = mapper1.writeValueAsString(obj); - - Object content = new ByteArrayInputStream(json.getBytes()); - - if (content instanceof InputStream) { - // send current configuration - try (OutputStream os = connection.getOutputStream()) { - int count = IOUtils.copy((InputStream) content, os); - if (policyLogger.isDebugEnabled()) { - policyLogger.debug("copied to output, bytes=" + count); - } - } - } - }else{ - if(uri.endsWith("set_BRMSParamData")){ - connection.setRequestProperty("Content-Type",PolicyController.getContenttype()); - try (OutputStream os = connection.getOutputStream()) { - IOUtils.copy((InputStream) request.getInputStream(), os); - } - }else{ - boundary = "===" + System.currentTimeMillis() + "==="; - connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary); - try (OutputStream os = connection.getOutputStream()) { - if(item != null){ - IOUtils.copy((InputStream) item.getInputStream(), os); - } - } - } - } - } - - connection.connect(); - - int responseCode = connection.getResponseCode(); - if(responseCode == 200){ - // get the response content into a String - String responseJson = null; - // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file) - java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream()); - scanner.useDelimiter("\\A"); - responseJson = scanner.hasNext() ? scanner.next() : ""; - scanner.close(); - policyLogger.info("JSON response from PAP: " + responseJson); - return responseJson; - } - - } catch (Exception e) { - policyLogger.error("Exception Occured"+e); - }finally{ - if(file != null && file.exists() && file.delete()){ - policyLogger.info("File Deleted Successfully"); - } - if (connection != null) { - try { - // For some reason trying to get the inputStream from the connection - // throws an exception rather than returning null when the InputStream does not exist. - InputStream is = connection.getInputStream(); - if (is != null) { - is.close(); - } - } catch (IOException ex) { - policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex); - } - connection.disconnect(); - } - } - return null; - } - - @RequestMapping(value={"/getDictionary/*"}, method={RequestMethod.GET}) - public void getDictionaryController(HttpServletRequest request, HttpServletResponse response){ - String uri = request.getRequestURI().replace("/getDictionary", ""); - String body = null; - ResponseEntity responseEntity = sendToPAP(null, uri, HttpMethod.GET); - if(responseEntity != null){ - body = responseEntity.getBody().toString(); - }else{ - body = ""; - } - try { - response.getWriter().write(body); - } catch (IOException e) { - policyLogger.error("Exception occured while getting Dictionary entries", e); - } - } - - @RequestMapping(value={"/saveDictionary/*/*"}, method={RequestMethod.POST}) - public ModelAndView saveDictionaryController(HttpServletRequest request, HttpServletResponse response) throws Exception{ - String uri = request.getRequestURI().replace("/saveDictionary", ""); - if(uri.contains(importDictionary)){ - String userId = UserUtils.getUserSession(request).getOrgUserId(); - uri = uri+ "?userId=" +userId; - } - String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim()); - response.getWriter().write(body); - return null; - } - - @RequestMapping(value={"/deleteDictionary/*/*"}, method={RequestMethod.POST}) - public ModelAndView deletetDictionaryController(HttpServletRequest request, HttpServletResponse response) throws Exception{ - String uri = request.getRequestURI().replace("/deleteDictionary", ""); - String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim()); - response.getWriter().write(body); - return null; - } - - @RequestMapping(value={"/searchDictionary"}, method={RequestMethod.POST}) - public ModelAndView searchDictionaryController(HttpServletRequest request, HttpServletResponse response) throws Exception{ - Object resultList = null; - String uri = request.getRequestURI(); - try{ - String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim()); - if(body.contains("CouldNotConnectException")){ - List data = new ArrayList<>(); - data.add("Elastic Search Server is down"); - resultList = data; - }else{ - JSONObject json = new JSONObject(body); - resultList = json.get("policyresult"); - } - }catch(Exception e){ - policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception Occured while querying Elastic Search: " + e); - List data = new ArrayList<>(); - data.add("Elastic Search Server is down"); - resultList = data; - } - - response.setCharacterEncoding(PolicyController.getCharacterencoding()); - response.setContentType(PolicyController.getContenttype()); - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{result: " + resultList + "}"); - out.write(j.toString()); - return null; - } - - @RequestMapping(value={"/searchPolicy"}, method={RequestMethod.POST}) - public ModelAndView searchPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ - Object resultList = null; - String uri = request.getRequestURI()+"?action=search"; - String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim()); - - JSONObject json = new JSONObject(body); - try{ - resultList = json.get("policyresult"); - }catch(Exception e){ - List data = new ArrayList<>(); - data.add("Elastic Search Server is down"); - resultList = data; - policyLogger.error("Exception Occured while searching for Policy in Elastic Database" +e); - } - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{result: " + resultList + "}"); - out.write(j.toString()); - return null; - } - - public void deleteElasticData(String fileName){ - String uri = "searchPolicy?action=delete&policyName='"+fileName+"'"; - callPAP(null, "POST", uri.trim()); - } - -} \ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyUserInfoController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyUserInfoController.java deleted file mode 100644 index 4e6201880..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyUserInfoController.java +++ /dev/null @@ -1,62 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.admin; - -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.json.JSONObject; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.portalsdk.core.controller.RestrictedBaseController; -import org.openecomp.portalsdk.core.web.support.JsonMessage; -import org.openecomp.portalsdk.core.web.support.UserUtils; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -import com.fasterxml.jackson.databind.ObjectMapper; - -@Controller -@RequestMapping("/") -public class PolicyUserInfoController extends RestrictedBaseController{ - - private static final Logger LOGGER = FlexLogger.getLogger(PolicyUserInfoController.class); - - @RequestMapping(value="/get_PolicyUserInfo", method = RequestMethod.GET) - private void getPolicyUserInfo(HttpServletRequest request, HttpServletResponse response){ - JsonMessage msg = null; - try { - String userId = UserUtils.getUserSession(request).getOrgUserId(); - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("userid", userId); - msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } catch (Exception e) { - LOGGER.error("Exception Occured"+e); - } - } - -} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/RESTfulPAPEngine.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/RESTfulPAPEngine.java deleted file mode 100644 index 090476a93..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/RESTfulPAPEngine.java +++ /dev/null @@ -1,517 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.admin; - - - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.util.Base64; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.io.IOUtils; -import org.openecomp.policy.rest.XACMLRestProperties; -import org.openecomp.policy.rest.adapter.PolicyRestAdapter; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.openecomp.policy.xacml.api.pap.EcompPDP; -import org.openecomp.policy.xacml.api.pap.EcompPDPGroup; -import org.openecomp.policy.xacml.api.pap.PAPPolicyEngine; -import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; -import org.openecomp.policy.xacml.std.pap.StdPDP; -import org.openecomp.policy.xacml.std.pap.StdPDPGroup; -import org.openecomp.policy.xacml.std.pap.StdPDPItemSetChangeNotifier; -import org.openecomp.policy.xacml.std.pap.StdPDPPolicy; -import org.openecomp.policy.xacml.std.pap.StdPDPStatus; -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.api.pap.PDPPolicy; -import com.att.research.xacml.api.pap.PDPStatus; -import com.att.research.xacml.util.XACMLProperties; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.type.CollectionType; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; - -/** - * Implementation of the PAPEngine interface that communicates with a PAP engine in a remote servlet - * through a RESTful interface - * - * - */ -public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyEngine { - private static final Logger LOGGER = FlexLogger.getLogger(RESTfulPAPEngine.class); - - private static final String groupID = "groupId="; - - // - // URL of the PAP Servlet that this Admin Console talks to - // - private String papServletURLString; - - /** - * Set up link with PAP Servlet and get our initial set of Groups - * @throws Exception - */ - public RESTfulPAPEngine (String myURLString) throws PAPException, IOException { - // - // Get our URL to the PAP servlet - // - this.papServletURLString = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); - if (this.papServletURLString == null || this.papServletURLString.length() == 0) { - String message = "The property 'POLICYENGINE_ADMIN_ACTIVE' was not set during installation. Admin Console cannot call PAP."; - LOGGER.error(message); - throw new PAPException(message); - } - - // - // register this Admin Console with the PAP Servlet to get updates - // - Object newURL = sendToPAP("PUT", null, null, null, "adminConsoleURL=" + myURLString); - if (newURL != null) { - // assume this was a re-direct and try again - LOGGER.warn("Redirecting to '" + newURL + "'"); - this.papServletURLString = (String)newURL; - newURL = sendToPAP("PUT", null, null, null, "adminConsoleURL=" + myURLString); - if (newURL != null) { - LOGGER.error("Failed to redirect to " + this.papServletURLString); - throw new PAPException("Failed to register with PAP"); - } - } - } - - - // - // High-level commands used by the Admin Console code through the PAPEngine Interface - // - - @Override - public EcompPDPGroup getDefaultGroup() throws PAPException { - return (EcompPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID, "default="); - } - - @Override - public void SetDefaultGroup(EcompPDPGroup group) throws PAPException { - sendToPAP("POST", null, null, null, groupID + group.getId(), "default=true"); - } - - @SuppressWarnings("unchecked") - @Override - public Set getEcompPDPGroups() throws PAPException { - Set newGroupSet; - newGroupSet = (Set) this.sendToPAP("GET", null, Set.class, StdPDPGroup.class, groupID); - return Collections.unmodifiableSet(newGroupSet); - } - - - @Override - public EcompPDPGroup getGroup(String id) throws PAPException { - return (EcompPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID + id); - } - - @Override - public void newGroup(String name, String description) - throws PAPException, NullPointerException { - String escapedName = null; - String escapedDescription = null; - try { - escapedName = URLEncoder.encode(name, "UTF-8"); - escapedDescription = URLEncoder.encode(description, "UTF-8"); - } catch (UnsupportedEncodingException e) { - throw new PAPException("Unable to send name or description to PAP: " + e.getMessage() +e); - } - - this.sendToPAP("POST", null, null, null, groupID, "groupName="+escapedName, "groupDescription=" + escapedDescription); - } - - - /** - * Update the configuration on the PAP for a single Group. - * - * @param group - * @return - * @throws PAPException - */ - public void updateGroup(EcompPDPGroup group) throws PAPException { - - try { - - // - // ASSUME that all of the policies mentioned in this group are already located in the correct directory on the PAP! - // - // Whenever a Policy is added to the group, that file must be automatically copied to the PAP from the Workspace. - // - - - // Copy all policies from the local machine's workspace to the PAP's PDPGroup directory. - // This is not efficient since most of the policies will already exist there. - // However, the policy files are (probably!) not too huge, and this is a good way to ensure that any corrupted files on the PAP get refreshed. - - - // now update the group object on the PAP - - sendToPAP("PUT", group, null, null, groupID + group.getId()); - } catch (Exception e) { - String message = "Unable to PUT policy '" + group.getId() + "', e:" + e; - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); - throw new PAPException(message); - } - } - - - @Override - public void removeGroup(EcompPDPGroup group, EcompPDPGroup newGroup) - throws PAPException, NullPointerException { - String moveToGroupString = null; - if (newGroup != null) { - moveToGroupString = "movePDPsToGroupId=" + newGroup.getId(); - } - sendToPAP("DELETE", null, null, null, groupID + group.getId(), moveToGroupString); - } - - @Override - public EcompPDPGroup getPDPGroup(EcompPDP pdp) throws PAPException { - return getPDPGroup(pdp.getId()); - } - - - public EcompPDPGroup getPDPGroup(String pdpId) throws PAPException { - return (EcompPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID, "pdpId=" + pdpId, "getPDPGroup="); - } - - @Override - public EcompPDP getPDP(String pdpId) throws PAPException { - return (EcompPDP)sendToPAP("GET", null, null, StdPDP.class, groupID, "pdpId=" + pdpId); - } - - @Override - public void newPDP(String id, EcompPDPGroup group, String name, String description, int jmxport) throws PAPException, - NullPointerException { - StdPDP newPDP = new StdPDP(id, name, description, jmxport); - sendToPAP("PUT", newPDP, null, null, groupID + group.getId(), "pdpId=" + id); - return; - } - - @Override - public void movePDP(EcompPDP pdp, EcompPDPGroup newGroup) throws PAPException { - sendToPAP("POST", null, null, null, groupID + newGroup.getId(), "pdpId=" + pdp.getId()); - return; - } - - @Override - public void updatePDP(EcompPDP pdp) throws PAPException { - EcompPDPGroup group = getPDPGroup(pdp); - sendToPAP("PUT", pdp, null, null, groupID + group.getId(), "pdpId=" + pdp.getId()); - return; - } - - @Override - public void removePDP(EcompPDP pdp) throws PAPException { - EcompPDPGroup group = getPDPGroup(pdp); - sendToPAP("DELETE", null, null, null, groupID + group.getId(), "pdpId=" + pdp.getId()); - return; - } - - //Validate the Policy Data - public boolean validatePolicyRequest(PolicyRestAdapter policyAdapter, String policyType) throws PAPException { - Boolean isValidData = false; - StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getConfigBodyData(), policyAdapter.getConfigType(), "Base"); - - //send JSON object to PAP - isValidData = (Boolean) sendToPAP("PUT", newPAPPolicy, null, null, "operation=validate", "apiflag=admin", "policyType=" + policyType); - return isValidData; - } - - - - @Override - public void publishPolicy(String id, String name, boolean isRoot, - InputStream policy, EcompPDPGroup group) throws PAPException { - - - // copy the (one) file into the target directory on the PAP servlet - copyFile(id, group, policy); - - // adjust the local copy of the group to include the new policy - PDPPolicy pdpPolicy = new StdPDPPolicy(id, isRoot, name); - group.getPolicies().add(pdpPolicy); - - // tell the PAP servlet to include the policy in the configuration - updateGroup(group); - - return; - } - - /** - * Copy a single Policy file from the input stream to the PAP Servlet. - * Either this works (silently) or it throws an exception. - * - * @param policyId - * @param group - * @param policy - * @return - * @throws PAPException - */ - public void copyFile(String policyId, EcompPDPGroup group, InputStream policy) throws PAPException { - // send the policy file to the PAP Servlet - try { - sendToPAP("POST", policy, null, null, groupID + group.getId(), "policyId="+policyId); - } catch (Exception e) { - String message = "Unable to PUT policy '" + policyId + "', e:" + e; - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); - throw new PAPException(message); - } - } - - - @Override - public void copyPolicy(PDPPolicy policy, EcompPDPGroup group) throws PAPException { - if (policy == null || group == null) { - throw new PAPException("Null input policy="+policy+" group="+group); - } - try (InputStream is = new FileInputStream(new File(policy.getLocation())) ) { - copyFile(policy.getId(), group, is ); - } catch (Exception e) { - String message = "Unable to PUT policy '" + policy.getId() + "', e:" + e; - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); - throw new PAPException(message); - } - } - - @Override - public void removePolicy(PDPPolicy policy, EcompPDPGroup group) throws PAPException { - throw new PAPException("NOT IMPLEMENTED"); - - } - - - /** - * Special operation - Similar to the normal PAP operations but this one contacts the PDP directly - * to get detailed status info. - * - * @param pdp - * @return - * @throws PAPException - */ - - public PDPStatus getStatus(EcompPDP pdp) throws PAPException { - return (StdPDPStatus)sendToPAP("GET", pdp, null, StdPDPStatus.class); - } - - - // - // Internal Operations called by the PAPEngine Interface methods - // - - /** - * Send a request to the PAP Servlet and get the response. - * - * The content is either an InputStream to be copied to the Request OutputStream - * OR it is an object that is to be encoded into JSON and pushed into the Request OutputStream. - * - * The Request parameters may be encoded in multiple "name=value" sets, or parameters may be combined by the caller. - * - * @param method - * @param content - EITHER an InputStream OR an Object to be encoded in JSON - * @param collectionTypeClass - * @param responseContentClass - * @param parameters - * @return - * @throws Exception - */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - private Object sendToPAP(String method, Object content, Class collectionTypeClass, Class responseContentClass, String... parameters ) throws PAPException { - HttpURLConnection connection = null; - String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); - LOGGER.info("User Id is " + papID); - String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS); - Base64.Encoder encoder = Base64.getEncoder(); - String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8)); - LOGGER.info("Encoding for the PAP is: " + encoding); - try { - String fullURL = papServletURLString; - if (parameters != null && parameters.length > 0) { - String queryString = ""; - for (String p : parameters) { - queryString += "&" + p; - } - fullURL += "?" + queryString.substring(1); - } - - // special case - Status (actually the detailed status) comes from the PDP directly, not the PAP - if (method.equals("GET") && (content instanceof EcompPDP) && responseContentClass == StdPDPStatus.class) { - // Adjust the url and properties appropriately - String pdpID =((EcompPDP)content).getId(); - fullURL = pdpID + "?type=Status"; - content = null; - if(CheckPDP.validateID(pdpID)){ - encoding = CheckPDP.getEncoding(pdpID); - } - } - - - URL url = new URL(fullURL); - - // - // Open up the connection - // - connection = (HttpURLConnection)url.openConnection(); - // - // Setup our method and headers - // - connection.setRequestMethod(method); - connection.setUseCaches(false); - // - // Adding this in. It seems the HttpUrlConnection class does NOT - // properly forward our headers for POST re-direction. It does so - // for a GET re-direction. - // - // So we need to handle this ourselves. - // - connection.setInstanceFollowRedirects(false); - connection.setRequestProperty("Authorization", "Basic " + encoding); - connection.setDoOutput(true); - connection.setDoInput(true); - - if (content != null) { - if (content instanceof InputStream) { - try { - // - // Send our current policy configuration - // - try (OutputStream os = connection.getOutputStream()) { - int count = IOUtils.copy((InputStream)content, os); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("copied to output, bytes="+count); - } - } - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to write content in '" + method + "'", e); - } - } else { - // The content is an object to be encoded in JSON - ObjectMapper mapper = new ObjectMapper(); - mapper.writeValue(connection.getOutputStream(), content); - } - } - // - // Do the connect - // - connection.connect(); - if (connection.getResponseCode() == 204) { - LOGGER.info("Success - no content."); - return null; - } else if (connection.getResponseCode() == 200) { - LOGGER.info("Success. We have a return object."); - String isValidData = connection.getHeaderField("isValidData"); - String isSuccess = connection.getHeaderField("successMapKey"); - Map successMap = new HashMap<>(); - if (isValidData != null && isValidData.equalsIgnoreCase("true")){ - LOGGER.info("Policy Data is valid."); - return true; - } else if (isValidData != null && isValidData.equalsIgnoreCase("false")) { - LOGGER.info("Policy Data is invalid."); - return false; - } else if (isSuccess != null && isSuccess.equalsIgnoreCase("success")) { - LOGGER.info("Policy Created Successfully!" ); - String finalPolicyPath = connection.getHeaderField("finalPolicyPath"); - successMap.put("success", finalPolicyPath); - return successMap; - } else if (isSuccess != null && isSuccess.equalsIgnoreCase("error")) { - LOGGER.info("There was an error while creating the policy!"); - successMap.put("error", "error"); - return successMap; - } else { - // get the response content into a String - String json = null; - // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file) - java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream()); - scanner.useDelimiter("\\A"); - json = scanner.hasNext() ? scanner.next() : ""; - scanner.close(); - LOGGER.info("JSON response from PAP: " + json); - - // convert Object sent as JSON into local object - ObjectMapper mapper = new ObjectMapper(); - mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); - if (collectionTypeClass != null) { - // collection of objects expected - final CollectionType javaType = - mapper.getTypeFactory().constructCollectionType(collectionTypeClass, responseContentClass); - - Object objectFromJSON = mapper.readValue(json, javaType); - return objectFromJSON; - } else { - // single value object expected - Object objectFromJSON = mapper.readValue(json, responseContentClass); - return objectFromJSON; - } - } - - } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) { - // redirection - String newURL = connection.getHeaderField("Location"); - if (newURL == null) { - LOGGER.error("No Location header to redirect to when response code="+connection.getResponseCode()); - throw new IOException("No redirect Location header when response code="+connection.getResponseCode()); - } - int qIndex = newURL.indexOf("?"); - if (qIndex > 0) { - newURL = newURL.substring(0, qIndex); - } - LOGGER.info("Redirect seen. Redirecting " + fullURL + " to " + newURL); - return newURL; - } else { - LOGGER.warn("Unexpected response code: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); - throw new IOException("Server Response: " + connection.getResponseCode() + ": " + connection.getResponseMessage()); - } - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "HTTP Request/Response to PAP: " + e,e); - throw new PAPException("Request/Response threw :" + e); - } finally { - // cleanup the connection - if (connection != null) { - try { - // For some reason trying to get the inputStream from the connection - // throws an exception rather than returning null when the InputStream does not exist. - InputStream is = connection.getInputStream(); - if (is != null) { - is.close(); - } - } catch (IOException ex) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex); - } - connection.disconnect(); - } - } - } -} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/components/HumanPolicyComponent.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/components/HumanPolicyComponent.java deleted file mode 100644 index 5b4fdeb02..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/components/HumanPolicyComponent.java +++ /dev/null @@ -1,991 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.components; - - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import javax.xml.bind.JAXBElement; - -import org.apache.commons.io.FilenameUtils; -import org.json.JSONObject; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.controller.PolicyController; -import org.openecomp.policy.rest.jpa.FunctionDefinition; -import org.openecomp.policy.utils.XACMLPolicyWriterWithPapNotify; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.openecomp.policy.xacml.util.XACMLPolicyScanner; - -import com.att.research.xacml.api.AttributeValue; -import com.att.research.xacml.std.IdentifierImpl; -import com.att.research.xacml.std.StdAttribute; -import com.att.research.xacml.std.StdAttributeValue; -import com.att.research.xacml.util.XACMLPolicyScanner.CallbackResult; -import com.att.research.xacml.util.XACMLPolicyScanner.SimpleCallback; - -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeSelectorType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType; -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 oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType; - - - -public class HumanPolicyComponent{ - - private static final Logger LOGGER = FlexLogger.getLogger(HumanPolicyComponent.class); - - // Constants Used in XML Creation - public static final String CATEGORY_RECIPIENT_SUBJECT = "urn:oasis:names:tc:xacml:1.0:subject-category:recipient-subject"; - public static final String CATEGORY_RESOURCE = "urn:oasis:names:tc:xacml:3.0:attribute-category:resource"; - public static final String CATEGORY_ACTION = "urn:oasis:names:tc:xacml:3.0:attribute-category:action"; - public static final String CATEGORY_ACCESS_SUBJECT = "urn:oasis:names:tc:xacml:1.0:subject-category:access-subject"; - public static final String ACTION_ID = "urn:oasis:names:tc:xacml:1.0:action:action-id"; - public static final String SUBJECT_ID = "urn:oasis:names:tc:xacml:1.0:subject:subject-id"; - public static final String RESOURCE_ID = "urn:oasis:names:tc:xacml:1.0:resource:resource-id"; - public static final String FUNTION_INTEGER_ONE_AND_ONLY = "urn:oasis:names:tc:xacml:1.0:function:integer-one-and-only"; - public static final String FUNCTION_STRING_ONE_AND_ONLY = "urn:oasis:names:tc:xacml:1.0:function:string-one-and-only"; - public static final String FUNCTION_STRING_EQUAL = "urn:oasis:names:tc:xacml:1.0:function:string-equal"; - public static final String FUNCTION_STRING_REGEX_MATCH = "org.openecomp.function.regex-match"; - public static final String FUNCTION_STRING_EQUAL_IGNORE = "urn:oasis:names:tc:xacml:3.0:function:string-equal-ignore-case"; - public static final String INTEGER_DATATYPE = "http://www.w3.org/2001/XMLSchema#integer"; - public static final String BOOLEAN_DATATYPE = "http://www.w3.org/2001/XMLSchema#boolean"; - public static final String STRING_DATATYPE = "http://www.w3.org/2001/XMLSchema#string"; - public static final String URI_DATATYPE = "http://www.w3.org/2001/XMLSchema#anyURI"; - public static final String RULE_VARIABLE = "var:"; - public static final String EMPTY_STRING = ""; - - private static HtmlProcessor htmlProcessor; - - private static File policyFile; - - private HumanPolicyComponent(){ - //Default Constructor - } - - public static JSONObject DescribePolicy(final File policyFile) { - if (LOGGER.isTraceEnabled()) - LOGGER.trace("ENTER"); - - HumanPolicyComponent.policyFile = policyFile; - return humanPolicyLayout(); - - } - - private static JSONObject humanPolicyLayout() { - if (LOGGER.isTraceEnabled()) - LOGGER.trace("ENTER"); - - try { - String html = processPolicy(); - JSONObject result = new JSONObject(); - result.put("html", html); - return result; - - } catch (IllegalArgumentException e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "cannot build html area por policy", e); - } - return null; - } - - private static String processPolicy() throws IllegalArgumentException { - if (LOGGER.isTraceEnabled()) - LOGGER.trace("ENTER"); - - FileInputStream pIS = null; - try { - pIS = new FileInputStream(policyFile); - Object policy = XACMLPolicyScanner.readPolicy(pIS); - if (policy == null) - throw new IllegalArgumentException("Policy File " + policyFile.getName() + - " cannot be unmarshalled"); - - HumanPolicyComponent.htmlProcessor = - new HtmlProcessor(HumanPolicyComponent.policyFile, policy); - - Path policyPath = Paths.get(policyFile.getAbsolutePath()); - XACMLPolicyScanner xacmlScanner = new XACMLPolicyScanner(policyPath, htmlProcessor); - xacmlScanner.scan(); - String html = htmlProcessor.html(); - if (LOGGER.isDebugEnabled()) - LOGGER.debug(policyPath + System.lineSeparator() + html); - - return html; - - } catch (Exception e) { - String msg = "Exception reading policy: " + policyFile.getAbsolutePath() + - ": " + e.getMessage(); - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + msg, e); - throw new IllegalArgumentException(msg); - } finally { - if (pIS != null) { - try { - pIS.close(); - } catch (IOException e) { - LOGGER.warn(e.getMessage(), e); - } - } - } - } - -} - -class HtmlProcessor extends SimpleCallback { - - private static final Logger LOGGER = FlexLogger.getLogger(HtmlProcessor.class); - - private static Map function2human; - static { - function2human = new HashMap<>(); - function2human.put(HumanPolicyComponent.FUNCTION_STRING_EQUAL, "equal"); - function2human.put(HumanPolicyComponent.FUNCTION_STRING_EQUAL_IGNORE, "equal"); - function2human.put(HumanPolicyComponent.FUNCTION_STRING_ONE_AND_ONLY, "one-and-only"); - function2human.put(HumanPolicyComponent.FUNCTION_STRING_REGEX_MATCH, "matching regular expression"); - function2human.put(HumanPolicyComponent.FUNTION_INTEGER_ONE_AND_ONLY, "one-and-only"); - } - - private static Map combiningAlgo2human; - static { - combiningAlgo2human = new HashMap<>(); - combiningAlgo2human.put("deny-overrides", "to deny if any $placeholder$ below evaluates to deny"); - combiningAlgo2human.put("permit-overrides", "to permit if any $placeholder$ below evaluates to permit"); - - combiningAlgo2human.put("ordered-deny-overrides", "to deny if any $placeholder$ below evaluates to deny"); - combiningAlgo2human.put("ordered-permit-overrides", "to permit if any $placeholder$ below evaluates to permit"); - combiningAlgo2human.put("deny-unless-permit", "to permit if any $placeholder$ below evaluates to deny and not indeterminate"); - - combiningAlgo2human.put("permit-unless-deny", "to deny if any $placeholder$ below evaluates to is permit and not indeterminate"); - combiningAlgo2human.put("first-applicable", "to honour the result of the first successfully evaluated $placeholder$ in order"); - combiningAlgo2human.put("only-one-applicable", "to honour the result of the first successfully evaluated $placeholder$ in order"); - } - - private Map attributeIdentifiersMap = new HashMap(); - - private final StringWriter stringWriter = new StringWriter(); - private final PrintWriter htmlOut = new PrintWriter(stringWriter); - private final String policyName; - private final Object rootPolicyObject; - - public HtmlProcessor(File policyFile, Object policyObject) - throws IllegalArgumentException { - if (LOGGER.isTraceEnabled()) - LOGGER.trace("ENTER"); - - if (policyFile == null) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Null Policy File"); - throw new IllegalArgumentException("Null Policy File"); - } - - if (!policyFile.exists() || !policyFile.canRead()) { - String msg = "Can't access " + policyFile.getAbsolutePath(); - LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + msg); - throw new IllegalArgumentException(msg); - } - - if (policyObject == null || - (!(policyObject instanceof PolicySetType) && !(policyObject instanceof PolicyType))) { - String msg = "Invalid unmarshalled object: " + policyObject; - LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + msg); - throw new IllegalArgumentException(msg); - } - - this.policyName = FilenameUtils.removeExtension(policyFile.getName()); - this.rootPolicyObject = policyObject; - - String version = "-"; - if (policyObject instanceof PolicyType) { - PolicyType policy = (PolicyType) policyObject; - version = policy.getVersion(); - htmlOut.println("

    Policy: " + policyName + - " (version " + version + ")

    "); - - } else { - PolicySetType policySet = (PolicySetType) policyObject; - version = policySet.getVersion(); - htmlOut.println("

    Policy Set: " + policyName + - " (v" + version + ")

    "); - } - - htmlOut.println("

    Location: " + policyFile.getPath() + "

    "); - htmlOut.println("
    "); - - if (rootPolicyObject instanceof PolicySetType) { - if (policyName.startsWith("Config_")) { - htmlOut.println("

    This is a config policy set.

    "); - } else if (policyName.startsWith("Action_")) { - htmlOut.println("

    This is an action policy set.

    "); - } - htmlOut.println("
    "); - } else { - if (policyName.startsWith("Config_")) { - htmlOut.println("

    This is a config policy.

    "); - } else if (policyName.startsWith("Action_")) { - htmlOut.println("

    This is an action policy.

    "); - } - htmlOut.println("
      "); - } - } - - /** - * @return the attributeIdentifiersMap - */ - public Map getAttributeIdentifiersMap() { - return attributeIdentifiersMap; - } - - @Override - public void onFinishScan(Object root) { - if (LOGGER.isTraceEnabled()) - LOGGER.trace("ENTER"); - - if (rootPolicyObject instanceof PolicySetType) { - htmlOut.println("
    "); - } else { - htmlOut.println(""); - } - - htmlOut.println("
    "); - - htmlOut.println("

    Attribute Table:

    "); - - htmlOut.println(""); - htmlOut.println(""); - htmlOut.print(""); - htmlOut.print(""); - htmlOut.print(""); - htmlOut.println(""); - for(Map.Entry entry : this.attributeIdentifiersMap.entrySet()){ - AttributeIdentifiers value = entry.getValue(); - htmlOut.println(""); - htmlOut.print(""); - htmlOut.print(""); - htmlOut.print(""); - htmlOut.println(""); - } - htmlOut.println("
    CategoryTypeIdentifier
    " + value.category + "" + value.getType() + "" + value.id + "
    "); - - htmlOut.println("

    "); - - // Not necessary for the user, uncomment if desired at some point - // writeRawXACML() - - super.onFinishScan(root); - } - - @SuppressWarnings("unused") - private void writeRawXACML() { - if (LOGGER.isTraceEnabled()) - LOGGER.trace("ENTER"); - - htmlOut.println("
    "); - htmlOut.println("

    Raw XACML:

    "); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - if (rootPolicyObject instanceof PolicySetType) { - XACMLPolicyWriterWithPapNotify.writePolicyFile(bos, (PolicySetType) rootPolicyObject); - } else if (rootPolicyObject instanceof PolicyType) { - XACMLPolicyWriterWithPapNotify.writePolicyFile(bos, (PolicyType) rootPolicyObject); - } - - String xacml = bos.toString(); - xacml = xacml.replaceAll("<", "<"); - xacml = xacml.replaceAll(">", ">"); - htmlOut.println("
    ");
    -		htmlOut.println(xacml);
    -		htmlOut.println("
    "); - } - - @Override - public CallbackResult onPreVisitPolicySet(PolicySetType parent, PolicySetType policySet) { - if (LOGGER.isTraceEnabled()) - LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + " Version: " + policySet.getVersion()); - - if (parent != null && LOGGER.isTraceEnabled()) - LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + - "Parent PolicySet: " + parent.getPolicySetId() + " Version: " + parent.getVersion()); - - String description = policySet.getDescription(); - if (description != null && LOGGER.isTraceEnabled()) - LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + - " Description: " + policySet.getDescription()); - - if (parent == null) // root - policySet(policySet, "dl"); - else - policySet(policySet, "li"); - - if (policySet.getPolicySetOrPolicyOrPolicySetIdReference().size() > 0) - htmlOut.println("
      "); - - return super.onPreVisitPolicySet(parent, policySet); - } - - @Override - public CallbackResult onPostVisitPolicySet(PolicySetType parent, PolicySetType policySet) { - if (LOGGER.isTraceEnabled()) - LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + " Version: " + policySet.getVersion()); - - if (parent != null && LOGGER.isTraceEnabled()) - LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + - "Parent PolicySet: " + parent.getPolicySetId() + " Version: " + parent.getVersion()); - - String description = policySet.getDescription(); - if (description != null && LOGGER.isTraceEnabled()) - LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + - " Description: " + policySet.getDescription()); - - if (policySet.getPolicySetOrPolicyOrPolicySetIdReference().size() > 0) - htmlOut.println("
    "); - - htmlOut.println("

    "); - - return super.onPostVisitPolicySet(parent, policySet); - } - - public void policySet(PolicySetType policySet, String htmlListElement) { - if (LOGGER.isTraceEnabled()) - LOGGER.trace("PolicySet: " + policySet.getPolicySetId()); - - String combiningAlgorithm = "-"; - String id = "-"; - String version = "-"; - - - if (policySet.getPolicyCombiningAlgId() != null) - combiningAlgorithm = extractLastIdentifier(policySet.getPolicyCombiningAlgId(), ":"); - - if (policySet.getPolicySetId() != null) - id = extractLastIdentifier(policySet.getPolicySetId(), ":"); - - if (policySet.getVersion() != null) - version = policySet.getVersion(); - - - htmlOut.println("<" + htmlListElement + ">Policy Set ID: " + id + - " (v" + version + ") " + ""); - - if (policySet.getTarget() == null || - policySet.getTarget().getAnyOf() == null || - policySet.getTarget().getAnyOf().size() <= 0) { - htmlOut.println("

    This policy set applies to all requests.

    "); - } else { - htmlOut.print("

    "); - htmlOut.print("This policy set applies to requests with attributes "); - - List anyOf_s = policySet.getTarget().getAnyOf(); - target(anyOf_s); - htmlOut.println(".

    "); - } - - if (policySet.getPolicySetOrPolicyOrPolicySetIdReference() != null && - policySet.getPolicySetOrPolicyOrPolicySetIdReference().size() > 0) { - String algoDesc = combiningAlgo2human.get(combiningAlgorithm); - if (algoDesc != null) { - algoDesc = algoDesc.replace("$placeholder$", "policy") + " (" + "" + combiningAlgorithm + ")"; - } else { - algoDesc = combiningAlgorithm; - } - - htmlOut.println("

    The result is " + algoDesc + ":

    "); - } - } - - @Override - public CallbackResult onPreVisitPolicy(PolicySetType parent, PolicyType policy) { - if (LOGGER.isTraceEnabled()) - LOGGER.trace("PolicySet: " + policy.getPolicyId() + " Version: " + policy.getVersion()); - - if (parent != null && LOGGER.isTraceEnabled()) - LOGGER.trace("PolicySet: " + policy.getPolicyId() + - "Parent PolicySet: " + parent.getPolicySetId() + " Version: " + parent.getVersion()); - - String description = policy.getDescription(); - if (description != null && LOGGER.isTraceEnabled()) - LOGGER.trace("PolicySet: " + policy.getPolicyId() + - " Description: " + policy.getDescription()); - - policy(policy); - - if (policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().size() > 0) - htmlOut.println("
      "); - - return super.onPreVisitPolicy(parent, policy); - } - - @Override - public CallbackResult onPostVisitPolicy(PolicySetType parent, PolicyType policy) { - if (LOGGER.isTraceEnabled()) - LOGGER.trace("PolicySet: " + policy.getPolicyId() + " Version: " + policy.getVersion()); - - if (parent != null && LOGGER.isTraceEnabled()) - LOGGER.trace("PolicySet: " + policy.getPolicyId() + - "Parent PolicySet: " + parent.getPolicySetId() + " Version: " + parent.getVersion()); - - if (policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().size() > 0) - htmlOut.println("
    "); - - htmlOut.println("

    "); - return super.onPostVisitPolicy(parent, policy); - } - - public void policy(PolicyType policy) { - if (LOGGER.isTraceEnabled()) - LOGGER.trace("Policy: " + policy.getPolicyId()); - - String combiningAlgorithm = "-"; - String id = "-"; - String version = "-"; - - - if (policy.getRuleCombiningAlgId() != null) - combiningAlgorithm = extractLastIdentifier(policy.getRuleCombiningAlgId(), ":"); - - if (policy.getPolicyId() != null) - id = extractLastIdentifier(policy.getPolicyId(), ":"); - - if (policy.getVersion() != null) - version = policy.getVersion(); - - htmlOut.println("
  • Policy ID: " + id + - " (v" + version + ") " + "
  • "); - - if (policy.getTarget() == null || - policy.getTarget().getAnyOf() == null || - policy.getTarget().getAnyOf().size() <= 0) { - htmlOut.println("

    This policy applies to all requests.

    "); - } else { - htmlOut.print("

    "); - htmlOut.print("This policy applies to requests with attributes "); - - List anyOf_s = policy.getTarget().getAnyOf(); - target(anyOf_s); - htmlOut.println(".

    "); - } - - if (policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition() != null && - policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().size() > 0) { - String algoDesc = combiningAlgo2human.get(combiningAlgorithm); - if (algoDesc != null) { - algoDesc = algoDesc.replace("$placeholder$", "rule") + " (" + combiningAlgorithm + ")"; - } else { - algoDesc = combiningAlgorithm; - } - htmlOut.println("

    The result is " + algoDesc + ":

    "); - } - } - - - @Override - public CallbackResult onPreVisitRule(PolicyType parent, RuleType rule) { - if (LOGGER.isTraceEnabled()) - LOGGER.trace("Rule: " + rule.getRuleId()); - - if (parent != null && LOGGER.isTraceEnabled()) - LOGGER.trace("Parent Policy: " + parent.getPolicyId() + " Version: " + parent.getVersion()); - - String description = rule.getDescription(); - if (description != null && LOGGER.isTraceEnabled()) { - LOGGER.trace("Rule: " + rule.getRuleId() + - " Description: " + rule.getDescription()); - } - - rule(rule); - - return super.onPreVisitRule(parent, rule); - } - - @Override - public CallbackResult onPostVisitRule(PolicyType parent, RuleType rule) { - if (LOGGER.isTraceEnabled()) - LOGGER.trace("Rule: " + rule.getRuleId()); - - if (parent != null && LOGGER.isTraceEnabled()) - LOGGER.trace("Parent Policy: " + parent.getPolicyId() + " Version: " + parent.getVersion()); - - return super.onPostVisitRule(parent, rule); - } - - public void rule(RuleType rule) { - if (LOGGER.isTraceEnabled()) - LOGGER.trace("Rule: " + rule.getRuleId()); - - String id = "-"; - - if (rule.getRuleId() != null) - id = extractLastIdentifier(rule.getRuleId(), ":"); - - htmlOut.println("
  • Rule ID: " + id + "
  • "); - - htmlOut.println("
    "); - - htmlOut.print("

    "); - htmlOut.print(rule.getEffect().value()); - - if (rule.getTarget() == null || - rule.getTarget().getAnyOf() == null || - rule.getTarget().getAnyOf().size() <= 0) { - htmlOut.print(" for all requests"); - } else { - List anyOf_s = rule.getTarget().getAnyOf(); - htmlOut.print(" for requests with attributes "); - target(anyOf_s); - } - - if (rule.getCondition() != null) { - htmlOut.print(" when "); - htmlOut.println(this.stringifyCondition(rule.getCondition()) + " "); - } else { - htmlOut.print(" with no conditions "); - } - - if (rule.getAdviceExpressions() != null) { - advice(rule.getAdviceExpressions()); - if (rule.getObligationExpressions() != null) - htmlOut.println(" and "); - } - - if (rule.getObligationExpressions() != null) { - obligation(rule.getObligationExpressions()); - } - - htmlOut.println("

    "); - } - - private void advice(AdviceExpressionsType adviceExpressions) { - if (LOGGER.isTraceEnabled()) - LOGGER.trace("ENTER"); - - List ae = adviceExpressions.getAdviceExpression(); - for (AdviceExpressionType expression : ae) { - htmlOut.println(" with advice (" + expression.getAdviceId() + ") on " + - expression.getAppliesTo().value() + ":" ); - htmlOut.println("
      "); - List assignments = expression.getAttributeAssignmentExpression(); - if (assignments != null) { - processAttributeAssignments(assignments); - } - htmlOut.println("
    "); - } - } - - private void obligation(ObligationExpressionsType obligationExpressions) { - if (LOGGER.isTraceEnabled()) - LOGGER.trace("ENTER"); - - List oe = obligationExpressions.getObligationExpression(); - for (ObligationExpressionType expression : oe) { - htmlOut.println(" with obligations (" + expression.getObligationId() + ") to be fullfilled on " + - expression.getFulfillOn().value() + ":" ); - htmlOut.println("
      "); - List assignments = expression.getAttributeAssignmentExpression(); - if (assignments != null) { - processAttributeAssignments(assignments); - } - htmlOut.println("
    "); - } - } - - /** - * @param assignments - */ - private void processAttributeAssignments(List assignments) { - if (LOGGER.isTraceEnabled()) - LOGGER.trace("ENTER"); - - for (AttributeAssignmentExpressionType assignment : assignments) { - String succintIdentifier = extractLastIdentifier(assignment.getCategory(), ":") + - ":" + extractLastIdentifier(assignment.getAttributeId(), ":"); - AttributeIdentifiers attributeIdentifiers = null; - if (!this.attributeIdentifiersMap.containsKey(succintIdentifier)) { - // Note Attribute Assignments do not have an Attribute Type, assume string - // but note this case is unlikely since attributeMap should have been populated - // during parsing of target and conditions, and not in this case for Advice and - // Obligations. - attributeIdentifiers = new AttributeIdentifiers(assignment.getCategory(), - "NA", - assignment.getAttributeId()); - this.attributeIdentifiersMap.put(succintIdentifier, attributeIdentifiers); - } - - htmlOut.print("
  • " + succintIdentifier + " is "); - // AttributeValueType - JAXBElement jaxbExp = assignment.getExpression(); - Object assignmentObject = jaxbExp.getValue(); - if (assignmentObject instanceof AttributeValueType) { - AttributeValueType avt = (AttributeValueType) assignmentObject; - if (attributeIdentifiers != null) { - attributeIdentifiers.setType(avt.getDataType()); - } - int numContent = avt.getContent().size(); - int countContent = 0; - for (Object c: avt.getContent()) { - countContent++; - htmlOut.print("" + c + ""); - if (countContent < numContent) - htmlOut.print(" or "); - } - htmlOut.println("
  • "); - } else if (assignmentObject instanceof AttributeDesignatorType) { - htmlOut.println("NA"); - } else if (assignmentObject instanceof AttributeSelectorType) { - htmlOut.println("NA"); - } else if (assignmentObject instanceof ApplyType) { - htmlOut.println("NA"); - } else { - htmlOut.println("Unexpected"); - } - } - } - - /** - * - * @param anyOfList - */ - public void target(List anyOfList) { - if (LOGGER.isTraceEnabled()) - LOGGER.trace("ENTER"); - - if (anyOfList != null) { - Iterator iterAnyOf = anyOfList.iterator(); - String targetInHuman = ""; - while (iterAnyOf.hasNext()) { - AnyOfType anyOf = iterAnyOf.next(); - List allOfList = anyOf.getAllOf(); - if (allOfList != null) { - Iterator iterAllOf = allOfList.iterator(); - while (iterAllOf.hasNext()) { - AllOfType allOf = iterAllOf.next(); - List matchList = allOf.getMatch(); - if (matchList != null) { - Iterator iterMatch = matchList.iterator(); - if (matchList.size() > 1) - targetInHuman += "("; - while (iterMatch.hasNext()) { - MatchType match = iterMatch.next(); - // - // Finally down to the actual attribute - // - StdAttribute attribute = null; - AttributeValueType value = match.getAttributeValue(); - String attributeDataType = null; - if (match.getAttributeDesignator() != null && value != null) { - AttributeDesignatorType designator = match.getAttributeDesignator(); - attribute = new StdAttribute(new IdentifierImpl(designator.getCategory()), - new IdentifierImpl(designator.getAttributeId()), - new StdAttributeValue>(new IdentifierImpl(value.getDataType()), value.getContent()), - designator.getIssuer(), - false); - attributeDataType = designator.getDataType(); - } else if (match.getAttributeSelector() != null && value != null) { - AttributeSelectorType selector = match.getAttributeSelector(); - attribute = new StdAttribute(new IdentifierImpl(selector.getCategory()), - new IdentifierImpl(selector.getContextSelectorId()), - new StdAttributeValue>(new IdentifierImpl(value.getDataType()), value.getContent()), - null, - false); - attributeDataType = selector.getDataType(); - } else { - LOGGER.warn("NULL designator/selector or value for match."); - attributeDataType = "NA"; - } - - String functionName = getHumanFunction(match.getMatchId()); - if(attribute != null){ - String succintIdentifier = extractLastIdentifier(attribute.getCategory().stringValue(), ":") + - ":" + extractLastIdentifier(attribute.getAttributeId().stringValue(), ":"); - AttributeIdentifiers ai = new AttributeIdentifiers(attribute.getCategory().stringValue(), - attributeDataType, - attribute.getAttributeId().stringValue()); - this.attributeIdentifiersMap.put(succintIdentifier,ai); - - targetInHuman += "" + succintIdentifier + " " + functionName + " "; - - int numAttributes = attribute.getValues().size(); - int count = 0; - for (AttributeValue v: attribute.getValues()) { - count++; - if (v.getValue() instanceof Collection) { - Collection value_s = (Collection) v.getValue(); - int numValues = value_s.size(); - int countValues = 0; - for (Object o : value_s) { - countValues++; - targetInHuman += " " + o + ""; - if (countValues < numValues) { - targetInHuman += ", or"; - } - } - } else { - targetInHuman += " " + v.getValue() + ""; - if (count < numAttributes) { - targetInHuman += ", or "; - } - } - } - } - - if (iterMatch.hasNext()) { - targetInHuman += " and "; - } - } // end iterMatch - if (matchList.size() > 1) { - targetInHuman += ")"; - } - } - if (iterAllOf.hasNext()) { - targetInHuman += " or "; - } - } // end iterAllOf - } - if (iterAnyOf.hasNext()) { - targetInHuman = "(" + targetInHuman + ")" + " or "; - } else { - if (anyOfList.size() > 1) { - targetInHuman += ")"; - } - } - } // end iterAnyOf - htmlOut.println(targetInHuman); - } - } - - private String getHumanFunction(String matchId) { - if (HtmlProcessor.function2human.containsKey(matchId)) { - return HtmlProcessor.function2human.get(matchId); - } - - FunctionDefinition function = PolicyController.getFunctionIDMap().get(matchId); - String functionName = function.getShortname(); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(functionName + - ": #args[" + function.getArgLb() + "," + function.getArgUb() +"]"); - } - - return extractLastIdentifier(removePrimitives(functionName), ":"); - } - - public String html() { - this.htmlOut.flush(); - return this.stringWriter.toString(); - } - - private String extractLastIdentifier(String in, String separator) { - int lastIndex = in.lastIndexOf(separator); - if (lastIndex < 0) - return in; - else - return in.substring(lastIndex+1); - } - - private String removePrimitives(String in) { - in = in.replace("string-", ""); - in = in.replace("integer-", ""); - in = in.replace("double-", ""); - in = in.replace("boolean-", ""); - return in; - } - - private String stringifyCondition(ConditionType condition) { - if (condition.getExpression() == null) { - return ""; - } - - return stringifyExpression(condition.getExpression().getValue()); - } - - private String stringifyExpression(Object expression) { - if (expression instanceof ApplyType) { - ApplyType apply = (ApplyType) expression; - FunctionDefinition function = PolicyController.getFunctionIDMap().get(apply.getFunctionId()); - String functionName = function.getShortname(); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(functionName + - ": #args[" + function.getArgLb() + "," + function.getArgUb() +"]"); - } - - if (functionName.contains("one-and-only")) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("one-and-only found: " + functionName); - } - - List> exps = apply.getExpression(); - if (exps == null || exps.size() == 0) - return ""; - else { - String forResult = ""; - for (JAXBElement e : exps) { - Object v = e.getValue(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("one-and-only children: " + v); - } - if (v != null) { - // C: return stringifyExpression(v, result); - forResult += stringifyExpression(v); - } - } - return forResult; - } - } - - final int numExpr = (apply.getExpression() == null) ? -1 : apply.getExpression().size(); - if (numExpr <= 0) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(functionName + " 0 expressions: " + numExpr); - } - return ""; - } else if (numExpr == 1) { - // eg: not - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(functionName + " 1 expression: " + numExpr); - } - String applySubresult = ""; - for (JAXBElement e : apply.getExpression()) { - Object v = e.getValue(); - if (v != null) { - applySubresult += this.stringifyExpression(e.getValue()); - } - } - return " " + removePrimitives(functionName) + " (" + applySubresult + ")"; - } else { - // > 1 arguments - if (LOGGER.isDebugEnabled()) { - LOGGER.debug(functionName + " > 1 expressions: " + numExpr); - } - String applySubresult = ""; - int exprCount = 0; - for (JAXBElement e : apply.getExpression()) { - exprCount++; - Object ev = e.getValue(); - if (ev != null) { - if (ev instanceof ApplyType) { - if (((ApplyType) ev).getFunctionId().contains("one-and-only")) { - applySubresult += this.stringifyExpression(e.getValue()); - } else { - applySubresult += "(" + this.stringifyExpression(e.getValue()) + ")"; - } - } else { - applySubresult += this.stringifyExpression(e.getValue()); - } - - if (exprCount < numExpr) { - applySubresult += " " + removePrimitives(functionName) + " "; - } - } - } - return applySubresult; - } - } - if (expression instanceof AttributeDesignatorType) { - AttributeDesignatorType adt = (AttributeDesignatorType) expression; - - String succintIdentifier = extractLastIdentifier(adt.getCategory(), ":") + - ":" + extractLastIdentifier(adt.getAttributeId(), ":"); - AttributeIdentifiers ai = new AttributeIdentifiers(adt.getCategory(), - adt.getDataType(), - adt.getAttributeId()); - this.attributeIdentifiersMap.put(succintIdentifier,ai); - - return "" + succintIdentifier + ""; - } - if (expression instanceof AttributeSelectorType) { - AttributeSelectorType ast = (AttributeSelectorType) expression; - - String attrName = ast.getPath(); - if (attrName == null || (attrName.length() == 0)) { - return ""; - } - - String textSelector = "/text()"; - if (attrName.endsWith(textSelector)) { - attrName = attrName.substring(0, attrName.length() - textSelector.length()); - } - - attrName = extractLastIdentifier(attrName, "/"); - attrName = extractLastIdentifier(attrName, ":"); - return " " + attrName; - } - if (expression instanceof AttributeValueType) { - AttributeValueType avt = (AttributeValueType) expression; - List content = avt.getContent(); - String value_s = ""; - for (Object o: content) { - value_s += " " + o.toString(); - } - return " " + value_s; - } - if (expression instanceof VariableReferenceType) { - // - // Really unknown - the variable may or may not have been defined - // - return " VARIABLEREF-NOT-HANDLED"; - } else { - throw new IllegalArgumentException("Unexpected input expression"); - } - } -} - - -class AttributeIdentifiers { - public final String category; - private String type; - public final String id; - - public AttributeIdentifiers(String category, String type, String id) { - this.category = category; - this.setType(type); - this.id = id; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } -} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/conf/HibernateSession.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/conf/HibernateSession.java deleted file mode 100644 index 22ecb0e00..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/conf/HibernateSession.java +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.conf; - -/* - * - * - * */ -import java.util.Properties; - -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.cfg.Configuration; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.controller.PolicyController; -import org.openecomp.policy.rest.jpa.SystemLogDB; - -@SuppressWarnings("deprecation") -public class HibernateSession{ - - private static final Logger LOGGER = FlexLogger.getLogger(HibernateSession.class); - - private static SessionFactory logSessionFactory; - - static { - try { - Properties prop= new Properties(); - prop.setProperty("hibernate.connection.url", PolicyController.getLogdbUrl()); - prop.setProperty("hibernate.connection.username", PolicyController.getLogdbUserName()); - prop.setProperty("hibernate.connection.password", PolicyController.getLogdbPassword()); - prop.setProperty("dialect", PolicyController.getLogdbDialect()); - prop.setProperty("hibernate.connection.driver_class", PolicyController.getLogdbDriver()); - prop.setProperty("show_sql", "false"); - logSessionFactory = new Configuration().addPackage("org.openecomp.policy.*").addProperties(prop) - .addAnnotatedClass(SystemLogDB.class).buildSessionFactory(); - } catch (Exception ex) { - LOGGER.error("Exception Occured while creating Log database Hibernate session"+ex); - } - } - public static Session getSession(){ - return logSessionFactory.openSession(); - } - -} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/ActionPolicyController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/ActionPolicyController.java deleted file mode 100644 index c88412b8b..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/ActionPolicyController.java +++ /dev/null @@ -1,268 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.controller; - - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import javax.xml.bind.JAXBElement; - -import org.openecomp.policy.rest.adapter.PolicyRestAdapter; -import org.openecomp.policy.rest.jpa.PolicyEntity; -import org.openecomp.portalsdk.core.controller.RestrictedBaseController; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; - - -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; - -@Controller -@RequestMapping({"/"}) -public class ActionPolicyController extends RestrictedBaseController{ - private static final Logger LOGGER = FlexLogger.getLogger(ActionPolicyController.class); - - public ActionPolicyController(){ - //Default Constructor - } - - private ArrayList attributeList; - protected LinkedList ruleAlgoirthmTracker; - public static final String PERFORMER_ATTRIBUTEID = "performer"; - protected Map performer = new HashMap<>(); - private ArrayList ruleAlgorithmList; - - public void prePopulateActionPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - attributeList = new ArrayList<>(); - ruleAlgorithmList = new ArrayList<>(); - performer.put("PDP", "PDPAction"); - performer.put("PEP", "PEPAction"); - - if (policyAdapter.getPolicyData() instanceof PolicyType) { - Object policyData = policyAdapter.getPolicyData(); - PolicyType policy = (PolicyType) policyData; - policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("_") + 1); - policyAdapter.setPolicyName(policyNameValue); - String description = ""; - try{ - description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); - }catch(Exception e){ - description = policy.getDescription(); - } - policyAdapter.setPolicyDescription(description); - // Get the target data under policy for Action. - TargetType target = policy.getTarget(); - if (target != null) { - // under target we have AnyOFType - List anyOfList = target.getAnyOf(); - if (anyOfList != null) { - Iterator iterAnyOf = anyOfList.iterator(); - while (iterAnyOf.hasNext()) { - AnyOfType anyOf = iterAnyOf.next(); - // Under AntOfType we have AllOfType - List allOfList = anyOf.getAllOf(); - if (allOfList != null) { - Iterator iterAllOf = allOfList.iterator(); - while (iterAllOf.hasNext()) { - AllOfType allOf = iterAllOf.next(); - // Under AllOfType we have Mathch. - List matchList = allOf.getMatch(); - if (matchList != null) { - Iterator iterMatch = matchList.iterator(); - while (iterMatch.hasNext()) { - MatchType match = iterMatch.next(); - // - // Under the match we have attributevalue and - // attributeDesignator. So,finally down to the actual attribute. - // - AttributeValueType attributeValue = match.getAttributeValue(); - String value = (String) attributeValue.getContent().get(0); - AttributeDesignatorType designator = match.getAttributeDesignator(); - String attributeId = designator.getAttributeId(); - // Component attributes are saved under Target here we are fetching them back. - // One row is default so we are not adding dynamic component at index 0. - Map attribute = new HashMap<>(); - attribute.put("key", attributeId); - attribute.put("value", value); - attributeList.add(attribute); - } - } - policyAdapter.setAttributes(attributeList); - } - } - } - } - - List ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); - // Under rule we have Condition and obligation. - for (Object o : ruleList) { - if (o instanceof RuleType) { - ConditionType condition = ((RuleType) o).getCondition(); - ObligationExpressionsType obligations = ((RuleType) o).getObligationExpressions(); - if (condition != null) { - int index = 0; - ApplyType actionApply = (ApplyType) condition.getExpression().getValue(); - ruleAlgoirthmTracker = new LinkedList<>(); - // Populating Rule Algorithms starting from compound. - prePopulateCompoundRuleAlgorithm(index, actionApply); - } - policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList); - // get the Obligation data under the rule for Form elements. - if (obligations != null) { - // Under the obligationExpressions we have obligationExpression. - List obligationList = obligations.getObligationExpression(); - if (obligationList != null) { - Iterator iterObligation = obligationList.iterator(); - while (iterObligation.hasNext()) { - ObligationExpressionType obligation = iterObligation.next(); - policyAdapter.setActionAttributeValue(obligation.getObligationId()); - // Under the obligationExpression we have attributeAssignmentExpression. - List attributeAssignmentExpressionList = obligation.getAttributeAssignmentExpression(); - if (attributeAssignmentExpressionList != null) { - Iterator iterAttributeAssignmentExpression = attributeAssignmentExpressionList.iterator(); - while (iterAttributeAssignmentExpression.hasNext()) { - AttributeAssignmentExpressionType attributeAssignmentExpression = iterAttributeAssignmentExpression.next(); - String attributeID = attributeAssignmentExpression.getAttributeId(); - AttributeValueType attributeValue = (AttributeValueType) attributeAssignmentExpression.getExpression().getValue(); - if (attributeID.equals(PERFORMER_ATTRIBUTEID)) { - for (String key : performer.keySet()) { - String keyValue = performer.get(key); - if (keyValue.equals(attributeValue.getContent().get(0))) { - policyAdapter.setActionPerformer(key); - } - } - } - } - } - } - } - } - } - } - } - } - } - - private int prePopulateCompoundRuleAlgorithm(int index, ApplyType actionApply) { - boolean isCompoundRule = true; - List> jaxbActionTypes = actionApply.getExpression(); - for (JAXBElement jaxbElement : jaxbActionTypes) { - // If There is Attribute Value under Action Type that means we came to the final child - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Prepopulating rule algoirthm: " + index); - } - // Check to see if Attribute Value exists, if yes then it is not a compound rule - if (jaxbElement.getValue() instanceof AttributeValueType) { - prePopulateRuleAlgorithms(index, actionApply, jaxbActionTypes); - ruleAlgoirthmTracker.addLast(index); - isCompoundRule = false; - index++; - } - } - if (isCompoundRule) { - // As it's compound rule, Get the Apply types - for (JAXBElement jaxbElement : jaxbActionTypes) { - ApplyType innerActionApply = (ApplyType) jaxbElement.getValue(); - index = prePopulateCompoundRuleAlgorithm(index, innerActionApply); - } - // Populate combo box - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Prepopulating Compound rule algorithm: " + index); - } - Map rule = new HashMap(); - for (String key : PolicyController.getDropDownMap().keySet()) { - String keyValue = PolicyController.getDropDownMap().get(key); - if (keyValue.equals(actionApply.getFunctionId())) { - rule.put("dynamicRuleAlgorithmCombo", key); - } - } - rule.put("id", "A" + (index +1)); - // Populate Key and values for Compound Rule - rule.put("dynamicRuleAlgorithmField1", "A" + (ruleAlgoirthmTracker.getLast() + 1 )); - ruleAlgoirthmTracker.removeLast(); - rule.put("dynamicRuleAlgorithmField2", "A" + (ruleAlgoirthmTracker.getLast() + 1)); - ruleAlgoirthmTracker.removeLast(); - ruleAlgoirthmTracker.addLast(index); - ruleAlgorithmList.add(rule); - index++; - } - return index; - } - - private void prePopulateRuleAlgorithms(int index, ApplyType actionApply, List> jaxbActionTypes) { - Map ruleMap = new HashMap(); - ruleMap.put("id", "A" + (index +1)); - // Populate combo box - Map dropDownMap = PolicyController.getDropDownMap(); - for (String key : dropDownMap.keySet()) { - String keyValue = dropDownMap.get(key); - if (keyValue.equals(actionApply.getFunctionId())) { - ruleMap.put("dynamicRuleAlgorithmCombo", key); - } - } - // Populate the key and value fields - // Rule Attribute added as key - if ((jaxbActionTypes.get(0).getValue()) instanceof ApplyType) { - // Get from Attribute Designator - ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(0).getValue(); - List> jaxbInnerActionTypes = innerActionApply.getExpression(); - AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerActionTypes.get(0).getValue(); - ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId()); - - // Get from Attribute Value - AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbActionTypes.get(1).getValue(); - String attributeValue = (String) actionConditionAttributeValue.getContent().get(0); - ruleMap.put("dynamicRuleAlgorithmField2", attributeValue); - } - // Rule Attribute added as value - else if (((jaxbActionTypes.get(0).getValue()) instanceof AttributeValueType)) { - AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbActionTypes.get(0).getValue(); - String attributeValue = (String) actionConditionAttributeValue.getContent().get(0); - ruleMap.put("dynamicRuleAlgorithmField2", attributeValue); - - ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(1).getValue(); - List> jaxbInnerActionTypes = innerActionApply.getExpression(); - AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerActionTypes.get(0).getValue(); - ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId()); - } - ruleAlgorithmList.add(ruleMap); - } - -} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AdminTabController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AdminTabController.java deleted file mode 100644 index 650b5872f..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AdminTabController.java +++ /dev/null @@ -1,119 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.controller; - - -import java.io.PrintWriter; -import java.util.HashMap; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.json.JSONObject; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.rest.dao.CommonClassDao; -import org.openecomp.policy.rest.jpa.GlobalRoleSettings; -import org.openecomp.portalsdk.core.controller.RestrictedBaseController; -import org.openecomp.portalsdk.core.web.support.JsonMessage; -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.servlet.ModelAndView; - -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -@Controller -@RequestMapping({"/"}) -public class AdminTabController extends RestrictedBaseController{ - - private static final Logger LOGGER = FlexLogger.getLogger(AdminTabController.class); - - private static CommonClassDao commonClassDao; - - public static CommonClassDao getCommonClassDao() { - return commonClassDao; - } - - public static void setCommonClassDao(CommonClassDao commonClassDao) { - AdminTabController.commonClassDao = commonClassDao; - } - - @Autowired - private AdminTabController(CommonClassDao commonClassDao){ - AdminTabController.commonClassDao = commonClassDao; - } - - public AdminTabController() { - //default constructor - } - - @RequestMapping(value={"/get_LockDownData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getAdminTabEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("lockdowndata", mapper.writeValueAsString(commonClassDao.getData(GlobalRoleSettings.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error("Exception Occured"+e); - } - } - - @RequestMapping(value={"/adminTabController/save_LockDownValue.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveAdminTabLockdownValue(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - GlobalRoleSettings globalRole = mapper.readValue(root.get("lockdowndata").toString(), GlobalRoleSettings.class); - globalRole.setRole("super-admin"); - commonClassDao.update(globalRole); - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(commonClassDao.getData(GlobalRoleSettings.class)); - JSONObject j = new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString + "}"); - - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error("Exception Occured"+e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } -} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AutoPushController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AutoPushController.java deleted file mode 100644 index a4387d19a..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AutoPushController.java +++ /dev/null @@ -1,377 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.controller; - - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.PrintWriter; -import java.net.URI; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.json.JSONObject; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.model.PDPGroupContainer; -import org.openecomp.policy.model.PDPPolicyContainer; -import org.openecomp.policy.model.Roles; -import org.openecomp.policy.rest.adapter.AutoPushTabAdapter; -import org.openecomp.policy.rest.dao.CommonClassDao; -import org.openecomp.policy.rest.jpa.PolicyEntity; -import org.openecomp.policy.rest.jpa.PolicyVersion; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.openecomp.policy.xacml.api.pap.EcompPDPGroup; -import org.openecomp.policy.xacml.std.pap.StdPDPGroup; -import org.openecomp.policy.xacml.std.pap.StdPDPPolicy; -import org.openecomp.portalsdk.core.controller.RestrictedBaseController; -import org.openecomp.portalsdk.core.web.support.JsonMessage; -import org.openecomp.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.servlet.ModelAndView; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.api.pap.PDPPolicy; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - - -@Controller -@RequestMapping({"/"}) -public class AutoPushController extends RestrictedBaseController{ - - private static final Logger logger = FlexLogger.getLogger(AutoPushController.class); - - @Autowired - CommonClassDao commonClassDao; - - private PDPGroupContainer container; - protected List groups = Collections.synchronizedList(new ArrayList()); - - private PDPPolicyContainer policyContainer; - - private PolicyController policyController; - public PolicyController getPolicyController() { - return policyController; - } - - public void setPolicyController(PolicyController policyController) { - this.policyController = policyController; - } - - private List data; - - public synchronized void refreshGroups() { - synchronized(this.groups) { - this.groups.clear(); - try { - PolicyController controller = getPolicyControllerInstance(); - this.groups.addAll(controller.getPapEngine().getEcompPDPGroups()); - } catch (PAPException e) { - String message = "Unable to retrieve Groups from server: " + e; - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message); - } - - } - } - - private PolicyController getPolicyControllerInstance(){ - return policyController != null ? getPolicyController() : new PolicyController(); - } - - @RequestMapping(value={"/get_AutoPushPoliciesContainerData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response){ - try{ - Set scopes = null; - List roles = null; - data = new ArrayList(); - String userId = UserUtils.getUserSession(request).getOrgUserId(); - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - PolicyController controller = policyController != null ? getPolicyController() : new PolicyController(); - List userRoles = controller.getRoles(userId); - roles = new ArrayList<>(); - scopes = new HashSet<>(); - for(Object role: userRoles){ - Roles userRole = (Roles) role; - roles.add(userRole.getRole()); - if(userRole.getScope() != null){ - if(userRole.getScope().contains(",")){ - String[] multipleScopes = userRole.getScope().split(","); - for(int i =0; i < multipleScopes.length; i++){ - scopes.add(multipleScopes[i]); - } - }else{ - if(!userRole.getScope().equals("")){ - scopes.add(userRole.getScope()); - } - } - } - } - if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest")) { - data = commonClassDao.getData(PolicyVersion.class); - }else{ - if(!scopes.isEmpty()){ - for(String scope : scopes){ - String query = "From PolicyVersion where policy_name like '"+scope+"%' and id > 0"; - List filterdatas = commonClassDao.getDataByQuery(query); - if(filterdatas != null){ - for(int i =0; i < filterdatas.size(); i++){ - data.add(filterdatas.get(i)); - } - } - } - }else{ - PolicyVersion emptyPolicyName = new PolicyVersion(); - emptyPolicyName.setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you"); - data.add(emptyPolicyName); - } - } - model.put("policydatas", mapper.writeValueAsString(data)); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - logger.error("Exception Occured"+e); - } - } - - @RequestMapping(value={"/auto_Push/PushPolicyToPDP.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView PushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception { - try { - ArrayList selectedPDPS = new ArrayList<>(); - ArrayList selectedPoliciesInUI = new ArrayList<>(); - PolicyController controller = getPolicyControllerInstance(); - this.groups.addAll(controller.getPapEngine().getEcompPDPGroups()); - ObjectMapper mapper = new ObjectMapper(); - this.container = new PDPGroupContainer(controller.getPapEngine()); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - AutoPushTabAdapter adapter = mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class); - for (Object pdpGroupId : adapter.getPdpDatas()) { - LinkedHashMap selectedPDP = (LinkedHashMap)pdpGroupId; - for(EcompPDPGroup pdpGroup : this.groups){ - if(pdpGroup.getId().equals(selectedPDP.get("id"))){ - selectedPDPS.add(pdpGroup); - } - } - } - - for (Object policyId : adapter.getPolicyDatas()) { - LinkedHashMap selected = (LinkedHashMap)policyId; - String policyName = selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml"; - selectedPoliciesInUI.add(policyName); - } - - for (Object pdpDestinationGroupId : selectedPDPS) { - Set currentPoliciesInGroup = new HashSet<>(); - Set selectedPolicies = new HashSet<>(); - for (String policyId : selectedPoliciesInUI) { - logger.debug("Handlepolicies..." + pdpDestinationGroupId + policyId); - - // - // Get the current selection - String selectedItem = policyId; - // - assert (selectedItem != null); - // create the id of the target file - // Our standard for file naming is: - // ...xml - // since the file name usually has a ".xml", we need to strip - // that - // before adding the other parts - String name = selectedItem.replace(File.separator, "."); - String id = name; - if (id.endsWith(".xml")) { - id = id.replace(".xml", ""); - id = id.substring(0, id.lastIndexOf(".")); - } - - // Default policy to be Root policy; user can change to deferred - // later - - StdPDPPolicy selectedPolicy = null; - String dbCheckName = name; - if(dbCheckName.contains("Config_")){ - dbCheckName = dbCheckName.replace(".Config_", ":Config_"); - }else if(dbCheckName.contains("Action_")){ - dbCheckName = dbCheckName.replace(".Action_", ":Action_"); - }else if(dbCheckName.contains("Decision_")){ - dbCheckName = dbCheckName.replace(".Decision_", ":Decision_"); - } - String[] split = dbCheckName.split(":"); - String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'"; - List queryData = controller.getDataByQuery(query); - PolicyEntity policyEntity = (PolicyEntity) queryData.get(0); - File temp = new File(name); - BufferedWriter bw = new BufferedWriter(new FileWriter(temp)); - bw.write(policyEntity.getPolicyData()); - bw.close(); - URI selectedURI = temp.toURI(); - try { - // - // Create the policy - selectedPolicy = new StdPDPPolicy(name, true, id, selectedURI); - } catch (IOException e) { - logger.error("Unable to create policy '" + name + "': "+ e.getMessage()); - } - StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId; - if (selectedPolicy != null) { - // Add Current policies from container - for (EcompPDPGroup group : container.getGroups()) { - if (group.getId().equals(selectedGroup.getId())) { - currentPoliciesInGroup.addAll(group.getPolicies()); - } - } - // copy policy to PAP - try { - controller.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId); - } catch (PAPException e) { - logger.error("Exception Occured"+e); - return null; - } - selectedPolicies.add(selectedPolicy); - } - temp.delete(); - } - StdPDPGroup pdpGroup = (StdPDPGroup) pdpDestinationGroupId; - StdPDPGroup updatedGroupObject = new StdPDPGroup(pdpGroup.getId(), pdpGroup.isDefaultGroup(), pdpGroup.getName(), pdpGroup.getDescription(), pdpGroup.getDirectory()); - updatedGroupObject.setEcompPdps(pdpGroup.getEcompPdps()); - updatedGroupObject.setPipConfigs(pdpGroup.getPipConfigs()); - updatedGroupObject.setStatus(pdpGroup.getStatus()); - - // replace the original set of Policies with the set from the - // container (possibly modified by the user) - // do not allow multiple copies of same policy - Iterator policyIterator = currentPoliciesInGroup.iterator(); - logger.debug("policyIterator....." + selectedPolicies); - while (policyIterator.hasNext()) { - PDPPolicy existingPolicy = policyIterator.next(); - for (PDPPolicy selPolicy : selectedPolicies) { - if (selPolicy.getName().equals(existingPolicy.getName())) { - if (selPolicy.getVersion().equals(existingPolicy.getVersion())) { - if (selPolicy.getId().equals(existingPolicy.getId())) { - policyIterator.remove(); - logger.debug("Removing policy: " + selPolicy); - break; - } - } else { - policyIterator.remove(); - logger.debug("Removing Old Policy version: "+ selPolicy); - break; - } - } - } - } - - currentPoliciesInGroup.addAll(selectedPolicies); - updatedGroupObject.setPolicies(currentPoliciesInGroup); - this.container.updateGroup(updatedGroupObject); - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - refreshGroups(); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); - JSONObject j = new JSONObject(msg); - out.write(j.toString()); - return null; - } - } - catch (Exception e){ - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @SuppressWarnings("unchecked") - @RequestMapping(value={"/auto_Push/remove_GroupPolicies.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception { - try { - PolicyController controller = getPolicyControllerInstance(); - this.container = new PDPGroupContainer(controller.getPapEngine()); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - StdPDPGroup group = (StdPDPGroup)mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class); - JsonNode removePolicyData = root.get("data"); - policyContainer = new PDPPolicyContainer(group); - if(removePolicyData.size() > 0){ - for(int i = 0 ; i < removePolicyData.size(); i++){ - String data = removePolicyData.get(i).toString(); - this.policyContainer.removeItem(data); - } - Set changedPolicies = new HashSet<>(); - changedPolicies.addAll((Collection) this.policyContainer.getItemIds()); - StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(), group.getDescription(),null); - updatedGroupObject.setPolicies(changedPolicies); - updatedGroupObject.setEcompPdps(group.getEcompPdps()); - updatedGroupObject.setPipConfigs(group.getPipConfigs()); - updatedGroupObject.setStatus(group.getStatus()); - this.container.updateGroup(updatedGroupObject); - } - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - refreshGroups(); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); - JSONObject j = new JSONObject(msg); - - out.write(j.toString()); - - return null; - } - catch (Exception e){ - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - -} \ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSParamController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSParamController.java deleted file mode 100644 index 18ad9fc58..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSParamController.java +++ /dev/null @@ -1,551 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.controller; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.PrintWriter; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.xml.bind.JAXBElement; - -import org.json.JSONObject; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.rest.adapter.PolicyRestAdapter; -import org.openecomp.policy.rest.dao.CommonClassDao; -import org.openecomp.policy.rest.jpa.BRMSParamTemplate; -import org.openecomp.policy.rest.jpa.PolicyEntity; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.openecomp.portalsdk.core.controller.RestrictedBaseController; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; - -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; - -@Controller -@RequestMapping("/") -public class CreateBRMSParamController extends RestrictedBaseController { - private static final Logger policyLogger = FlexLogger.getLogger(CreateBRMSParamController.class); - - private static CommonClassDao commonClassDao; - - public static CommonClassDao getCommonClassDao() { - return commonClassDao; - } - - public static void setCommonClassDao(CommonClassDao commonClassDao) { - CreateBRMSParamController.commonClassDao = commonClassDao; - } - - @Autowired - private CreateBRMSParamController(CommonClassDao commonClassDao){ - CreateBRMSParamController.commonClassDao = commonClassDao; - } - - public CreateBRMSParamController(){} - protected PolicyRestAdapter policyAdapter = null; - - private HashMap dynamicLayoutMap; - - private static String brmsTemplateVlaue = "<$%BRMSParamTemplate="; - private static String string = "String"; - - - @RequestMapping(value={"/policyController/getBRMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public void getBRMSParamPolicyRuleData(HttpServletRequest request, HttpServletResponse response){ - try{ - dynamicLayoutMap = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - String rule = findRule(root.get(PolicyController.getPolicydata()).toString().replaceAll("^\"|\"$", "")); - generateUI(rule); - response.setCharacterEncoding(PolicyController.getCharacterencoding()); - response.setContentType(PolicyController.getContenttype()); - request.setCharacterEncoding(PolicyController.getCharacterencoding()); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(dynamicLayoutMap); - JSONObject j = new JSONObject("{policyData: " + responseString + "}"); - out.write(j.toString()); - }catch(Exception e){ - policyLogger.error("Exception Occured while getting BRMS Rule data" , e); - } - } - - protected String findRule(String ruleTemplate) { - List datas = commonClassDao.getDataById(BRMSParamTemplate.class, "ruleName", ruleTemplate); - if(datas != null && !datas.isEmpty()){ - BRMSParamTemplate bRMSParamTemplate = (BRMSParamTemplate) datas.get(0); - return bRMSParamTemplate.getRule(); - } - return null; - } - - protected void generateUI(String rule) { - if(rule!=null){ - try { - StringBuilder params = new StringBuilder(""); - Boolean flag = false; - Boolean comment = false; - String lines[] = rule.split("\n"); - for(String line : lines){ - if (line.isEmpty() || line.startsWith("//")) { - continue; - } - if (line.startsWith("/*")) { - comment = true; - continue; - } - if (line.contains("//")) { - line = line.split("\\/\\/")[0]; - } - if (line.contains("/*")) { - comment = true; - if (line.contains("*/")) { - try { - comment = false; - line = line.split("\\/\\*")[0] - + line.split("\\*\\/")[1].replace("*/", ""); - } catch (Exception e) { - policyLogger.info("Just for Logging"+e); - line = line.split("\\/\\*")[0]; - } - } else { - line = line.split("\\/\\*")[0]; - } - } - if (line.contains("*/")) { - comment = false; - try { - line = line.split("\\*\\/")[1].replace("*/", ""); - } catch (Exception e) { - policyLogger.info("Just for Logging"+e); - line = ""; - } - } - if (comment) { - continue; - } - if (flag) { - params.append(line); - } - if (line.contains("declare Params")) { - params.append(line); - flag = true; - } - if (line.contains("end") && flag) { - break; - } - } - params = new StringBuilder(params.toString().replace("declare Params", "").replace("end", "").replaceAll("\\s+", "")); - String[] components = params.toString().split(":"); - String caption = ""; - for (int i = 0; i < components.length; i++) { - String type = ""; - if (i == 0) { - caption = components[i]; - } - if("".equals(caption)){ - break; - } - String nextComponent = ""; - try { - nextComponent = components[i + 1]; - } catch (Exception e) { - policyLogger.info("Just for Logging"+e); - nextComponent = components[i]; - } - if (nextComponent.startsWith(string)) { - type = "String"; - createField(caption, type); - caption = nextComponent.replace(string, ""); - } else if (nextComponent.startsWith("int")) { - type = "int"; - createField(caption, type); - caption = nextComponent.replace("int", ""); - } - } - } catch (Exception e) { - policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); - } - } - } - - private void createField(String caption, String type) { - dynamicLayoutMap.put(caption, type); - } - - /* - * When the User Click Edit or View Policy the following method will get invoked for setting the data to PolicyRestAdapter. - * Which is used to bind the data in GUI - */ - public void prePopulateBRMSParamPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - dynamicLayoutMap = new HashMap<>(); - if (policyAdapter.getPolicyData() instanceof PolicyType) { - PolicyType policy = (PolicyType) policyAdapter.getPolicyData(); - policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - // policy name value is the policy name without any prefix and - // Extensions. - String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Param_") + 11); - if (policyLogger.isDebugEnabled()) { - policyLogger.debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName()); - } - policyAdapter.setPolicyName(policyNameValue); - String description = ""; - try{ - description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); - }catch(Exception e){ - policyLogger.info("Just for Logging"+e); - description = policy.getDescription(); - } - policyAdapter.setPolicyDescription(description); - setDataAdapterFromAdviceExpressions(policy, policyAdapter); - paramUIGenerate(policyAdapter, entity); - // Get the target data under policy. - policyAdapter.setDynamicLayoutMap(dynamicLayoutMap); - if(policyAdapter.getDynamicLayoutMap().size() > 0){ - LinkedHashMap drlRule = new LinkedHashMap<>(); - for(Object keyValue: policyAdapter.getDynamicLayoutMap().keySet()){ - drlRule.put(keyValue.toString(), policyAdapter.getDynamicLayoutMap().get(keyValue)); - } - policyAdapter.setRuleData(drlRule); - } - TargetType target = policy.getTarget(); - if (target != null) { - setDataToAdapterFromTarget(target, policyAdapter); - } - } - } - - private void setDataAdapterFromAdviceExpressions(PolicyType policy, PolicyRestAdapter policyAdapter){ - ArrayList attributeList = new ArrayList<>(); - // Set Attributes. - AdviceExpressionsType expressionTypes = ((RuleType)policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0)).getAdviceExpressions(); - for( AdviceExpressionType adviceExpression: expressionTypes.getAdviceExpression()){ - for(AttributeAssignmentExpressionType attributeAssignment: adviceExpression.getAttributeAssignmentExpression()){ - if(attributeAssignment.getAttributeId().startsWith("key:")){ - Map attribute = new HashMap<>(); - String key = attributeAssignment.getAttributeId().replace("key:", ""); - attribute.put("key", key); - @SuppressWarnings("unchecked") - JAXBElement attributevalue = (JAXBElement) attributeAssignment.getExpression(); - String value = (String) attributevalue.getValue().getContent().get(0); - attribute.put("value", value); - attributeList.add(attribute); - }else if(attributeAssignment.getAttributeId().startsWith("dependencies:")){ - ArrayList dependencies = new ArrayList<>(Arrays.asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(","))); - if(dependencies.contains("")){ - dependencies.remove(""); - } - policyAdapter.setBrmsDependency(dependencies); - }else if(attributeAssignment.getAttributeId().startsWith("controller:")){ - policyAdapter.setBrmsController(attributeAssignment.getAttributeId().replace("controller:", "")); - } - } - policyAdapter.setAttributes(attributeList); - } - } - - private void setDataToAdapterFromTarget(TargetType target, PolicyRestAdapter policyAdapter){ - // Under target we have AnyOFType - List anyOfList = target.getAnyOf(); - if (anyOfList != null) { - Iterator iterAnyOf = anyOfList.iterator(); - while (iterAnyOf.hasNext()) { - AnyOfType anyOf = iterAnyOf.next(); - // Under AnyOFType we have AllOFType - List allOfList = anyOf.getAllOf(); - if (allOfList != null) { - Iterator iterAllOf = allOfList.iterator(); - while (iterAllOf.hasNext()) { - AllOfType allOf = iterAllOf.next(); - // Under AllOFType we have Match - List matchList = allOf.getMatch(); - if (matchList != null) { - setDataToAdapterFromMatchList(matchList, policyAdapter); - } - } - } - } - } - } - - private void setDataToAdapterFromMatchList(List matchList, PolicyRestAdapter policyAdapter){ - Iterator iterMatch = matchList.iterator(); - while (iterMatch.hasNext()) { - MatchType match = iterMatch.next(); - // - // Under the match we have attribute value and - // attributeDesignator. So,finally down to the actual attribute. - // - AttributeValueType attributeValue = match.getAttributeValue(); - String value = (String) attributeValue.getContent().get(0); - AttributeDesignatorType designator = match.getAttributeDesignator(); - String attributeId = designator.getAttributeId(); - - if ("RiskType".equals(attributeId)){ - policyAdapter.setRiskType(value); - } - if ("RiskLevel".equals(attributeId)){ - policyAdapter.setRiskLevel(value); - } - if ("guard".equals(attributeId)){ - policyAdapter.setGuard(value); - } - if ("TTLDate".equals(attributeId) && !value.contains("NA")){ - String newDate = convertDate(value, true); - policyAdapter.setTtlDate(newDate); - } - } - } - - private String convertDate(String dateTTL, boolean portalType) { - String formateDate = null; - String[] date; - String[] parts; - - if (portalType){ - parts = dateTTL.split("-"); - formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z"; - } else { - date = dateTTL.split("T"); - parts = date[0].split("-"); - formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; - } - return formateDate; - } - // This method generates the UI from rule configuration - public void paramUIGenerate(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - String data = entity.getConfigurationData().getConfigBody(); - if(data != null){ - File file = new File(PolicyController.getConfigHome() +File.separator+ entity.getConfigurationData().getConfigurationName()); - if(file.exists()){ - try (BufferedReader br = new BufferedReader(new FileReader(file))) { - StringBuilder sb = new StringBuilder(); - String line = br.readLine(); - while (line != null) { - sb.append(line); - sb.append("\n"); - line = br.readLine(); - } - }catch(Exception e){ - policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+ e.getMessage() + e); - } - } - try { - StringBuilder params = new StringBuilder(""); - Boolean flag = false; - Boolean comment = false; - for (String line : Files.readAllLines(Paths.get(file.toString()))) { - if (line.isEmpty() || line.startsWith("//")) { - continue; - } - if(line.contains(brmsTemplateVlaue)){ - String value = line.substring(line.indexOf("<$%"),line.indexOf("%$>")); - value = value.replace(brmsTemplateVlaue, ""); - policyAdapter.setRuleName(value); - } - if (line.startsWith("/*")) { - comment = true; - continue; - } - if ((line.contains("//"))&&(!(line.contains("http://") || line.contains("https://")))){ - line = line.split("\\/\\/")[0]; - } - if (line.contains("/*")) { - comment = true; - if (line.contains("*/")) { - try { - comment = false; - line = line.split("\\/\\*")[0] - + line.split("\\*\\/")[1].replace( - "*/", ""); - } catch (Exception e) { - policyLogger.info("Just for Logging"+e); - line = line.split("\\/\\*")[0]; - } - } else { - line = line.split("\\/\\*")[0]; - } - } - if (line.contains("*/")) { - comment = false; - try { - line = line.split("\\*\\/")[1] - .replace("*/", ""); - } catch (Exception e) { - policyLogger.info("Just for Logging"+e); - line = ""; - } - } - if (comment) { - continue; - } - if (flag) { - params.append(line); - } - if (line.contains("rule") && line.contains(".Params\"")) { - params.append(line); - flag = true; - } - if (line.contains("end") && flag) { - break; - } - } - params = new StringBuilder(params.substring(params.indexOf(".Params\"")+ 8)); - params = new StringBuilder(params.toString().replaceAll("\\s+", "").replace("salience1000whenthenParamsparams=newParams();","") - .replace("insert(params);end", "") - .replace("params.set", "")); - String[] components = params.toString().split("\\);"); - if(components!= null && components.length > 0){ - for (int i = 0; i < components.length; i++) { - String value = null; - components[i] = components[i]+")"; - String caption = components[i].substring(0, - components[i].indexOf('(')); - caption = caption.substring(0, 1).toLowerCase() + caption.substring(1); - if (components[i].contains("(\"")) { - value = components[i] - .substring(components[i].indexOf("(\""), - components[i].indexOf("\")")) - .replace("(\"", "").replace("\")", ""); - } else { - value = components[i] - .substring(components[i].indexOf('('), - components[i].indexOf(')')) - .replace("(", "").replace(")", ""); - } - dynamicLayoutMap.put(caption, value); - - } - } - } catch (Exception e) { - policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage() + e); - } - } - - } - - // set View Rule - @SuppressWarnings("unchecked") - @RequestMapping(value={"/policyController/ViewBRMSParamPolicyRule.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public void setViewRule(HttpServletRequest request, HttpServletResponse response){ - try { - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - PolicyRestAdapter policyData = mapper.readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class); - policyData.setDomainDir(root.get(PolicyController.getPolicydata()).get("model").get("name").toString().replace("\"", "")); - if(root.get(PolicyController.getPolicydata()).get("model").get("type").toString().replace("\"", "").equals(PolicyController.getFile())){ - policyData.setEditPolicy(true); - } - - String body = ""; - - body = "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " + - brmsTemplateVlaue + policyData.getRuleName() + "%$> \n */ \n"; - body = body + findRule((String) policyData.getRuleName()) + "\n"; - StringBuilder generatedRule = new StringBuilder(); - generatedRule.append("rule \""+ policyData.getDomainDir().replace("\\", ".") +".Config_BRMS_Param_" + policyData.getPolicyName()+".Params\" \n\tsalience 1000 \n\twhen\n\tthen\n\t\tParams params = new Params();"); - - if(policyData.getRuleData().size() > 0){ - for(Object keyValue: policyData.getRuleData().keySet()){ - String key = keyValue.toString().substring(0, 1).toUpperCase() + keyValue.toString().substring(1); - if (string.equals(keyValue)) { - generatedRule.append("\n\t\tparams.set" - + key + "(\"" - + policyData.getRuleData().get(keyValue).toString() + "\");"); - } else { - generatedRule.append("\n\t\tparams.set" - + key + "(" - + policyData.getRuleData().get(keyValue).toString() + ");"); - } - } - } - generatedRule.append("\n\t\tinsert(params);\nend"); - policyLogger.info("New rule generated with :" + generatedRule.toString()); - body = body + generatedRule.toString(); - // Expand the body. - Map copyMap=new HashMap<>(); - copyMap.putAll((Map) policyData.getRuleData()); - copyMap.put("policyName", policyData.getDomainDir().replace("\\", ".") +".Config_BRMS_Param_" + policyData.getPolicyName()); - copyMap.put("policyScope", policyData.getDomainDir().replace("\\", ".")); - copyMap.put("policyVersion", "1"); - //Finding all the keys in the Map data-structure. - Set keySet= copyMap.keySet(); - Iterator iterator = keySet.iterator(); - Pattern p; - Matcher m; - while(iterator.hasNext()) { - //Converting the first character of the key into a lower case. - String input= iterator.next(); - String output = Character.toLowerCase(input.charAt(0)) + - (input.length() > 1 ? input.substring(1) : ""); - //Searching for a pattern in the String using the key. - p=Pattern.compile("\\$\\{"+output+"\\}"); - m=p.matcher(body); - //Replacing the value with the inputs provided by the user in the editor. - body=m.replaceAll(copyMap.get(input)); - } - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(body); - JSONObject j = new JSONObject("{policyData: " + responseString + "}"); - out.write(j.toString()); - } catch (Exception e) { - policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } -} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSRawController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSRawController.java deleted file mode 100644 index c5b97ad45..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSRawController.java +++ /dev/null @@ -1,172 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.controller; - - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import javax.xml.bind.JAXBElement; - -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; - -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.rest.adapter.PolicyRestAdapter; -import org.openecomp.policy.rest.jpa.PolicyEntity; - -public class CreateBRMSRawController{ - - private static final Logger logger = FlexLogger.getLogger(CreateBRMSRawController.class); - - protected PolicyRestAdapter policyAdapter = null; - private ArrayList attributeList; - - - @SuppressWarnings("unchecked") - public void prePopulateBRMSRawPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - attributeList = new ArrayList(); - if (policyAdapter.getPolicyData() instanceof PolicyType) { - PolicyType policy = (PolicyType) policyAdapter.getPolicyData(); - policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - // policy name value is the policy name without any prefix and - // Extensions. - String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Raw_") + 9); - if (logger.isDebugEnabled()) { - logger.debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName()); - } - policyAdapter.setPolicyName(policyNameValue); - String description = ""; - try{ - description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); - }catch(Exception e){ - logger.info("Not able to see the createdby in description. So, add generic description", e); - description = policy.getDescription(); - } - policyAdapter.setPolicyDescription(description); - // Set Attributes. - AdviceExpressionsType expressionTypes = ((RuleType)policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0)).getAdviceExpressions(); - for( AdviceExpressionType adviceExpression: expressionTypes.getAdviceExpression()){ - for(AttributeAssignmentExpressionType attributeAssignment: adviceExpression.getAttributeAssignmentExpression()){ - if(attributeAssignment.getAttributeId().startsWith("key:")){ - Map attribute = new HashMap<>(); - String key = attributeAssignment.getAttributeId().replace("key:", ""); - attribute.put("key", key); - JAXBElement attributevalue = (JAXBElement) attributeAssignment.getExpression(); - String value = (String) attributevalue.getValue().getContent().get(0); - attribute.put("value", value); - attributeList.add(attribute); - }else if(attributeAssignment.getAttributeId().startsWith("dependencies:")){ - ArrayList dependencies = new ArrayList(Arrays.asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(","))); - if(dependencies.contains("")){ - dependencies.remove(""); - } - policyAdapter.setBrmsDependency(dependencies); - }else if(attributeAssignment.getAttributeId().startsWith("controller:")){ - policyAdapter.setBrmsController(attributeAssignment.getAttributeId().replace("controller:", "")); - } - } - policyAdapter.setAttributes(attributeList); - } - // Get the target data under policy. - policyAdapter.setConfigBodyData(entity.getConfigurationData().getConfigBody()); - TargetType target = policy.getTarget(); - if (target != null) { - // Under target we have AnyOFType - List anyOfList = target.getAnyOf(); - if (anyOfList != null) { - Iterator iterAnyOf = anyOfList.iterator(); - while (iterAnyOf.hasNext()) { - AnyOfType anyOf = iterAnyOf.next(); - // Under AnyOFType we have AllOFType - List allOfList = anyOf.getAllOf(); - if (allOfList != null) { - Iterator iterAllOf = allOfList.iterator(); - while (iterAllOf.hasNext()) { - AllOfType allOf = iterAllOf.next(); - // Under AllOFType we have Match - List matchList = allOf.getMatch(); - if (matchList != null) { - Iterator iterMatch = matchList.iterator(); - while (iterMatch.hasNext()) { - MatchType match = iterMatch.next(); - // - // Under the match we have attribute value and - // attributeDesignator. So,finally down to the actual attribute. - // - AttributeValueType attributeValue = match.getAttributeValue(); - String value = (String) attributeValue.getContent().get(0); - AttributeDesignatorType designator = match.getAttributeDesignator(); - String attributeId = designator.getAttributeId(); - - if (attributeId.equals("RiskType")){ - policyAdapter.setRiskType(value); - } - if (attributeId.equals("RiskLevel")){ - policyAdapter.setRiskLevel(value); - } - if (attributeId.equals("guard")){ - policyAdapter.setGuard(value); - } - if (attributeId.equals("TTLDate") && !value.contains("NA")){ - String newDate = convertDate(value, true); - policyAdapter.setTtlDate(newDate); - } - } - } - } - } - } - } - } - } - } - - private String convertDate(String dateTTL, boolean portalType) { - String formateDate = null; - String[] date; - String[] parts; - - if (portalType){ - parts = dateTTL.split("-"); - formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z"; - } else { - date = dateTTL.split("T"); - parts = date[0].split("-"); - formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; - } - return formateDate; - } -} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateClosedLoopFaultController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateClosedLoopFaultController.java deleted file mode 100644 index 08c0c38e7..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateClosedLoopFaultController.java +++ /dev/null @@ -1,709 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.controller; - - -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.rest.adapter.ClosedLoopFaultBody; -import org.openecomp.policy.rest.adapter.ClosedLoopFaultTriggerUISignatures; -import org.openecomp.policy.rest.adapter.ClosedLoopSignatures; -import org.openecomp.policy.rest.adapter.PolicyRestAdapter; -import org.openecomp.policy.rest.dao.CommonClassDao; -import org.openecomp.policy.rest.jpa.EcompName; -import org.openecomp.policy.rest.jpa.PolicyEntity; -import org.openecomp.policy.rest.jpa.VarbindDictionary; -import org.openecomp.portalsdk.core.controller.RestrictedBaseController; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; - -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectWriter; - -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; - -@Controller -@RequestMapping("/") -public class CreateClosedLoopFaultController extends RestrictedBaseController{ - - private static final Logger policyLogger = FlexLogger.getLogger(CreateClosedLoopFaultController.class); - - protected PolicyRestAdapter policyAdapter = null; - - - private static CommonClassDao commonclassdao; - - @Autowired - private CreateClosedLoopFaultController(CommonClassDao commonclassdao){ - CreateClosedLoopFaultController.commonclassdao = commonclassdao; - } - - public CreateClosedLoopFaultController(){} - - public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root){ - try{ - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - TrapDatas trapDatas = mapper.readValue(root.get("trapData").toString(), TrapDatas.class); - TrapDatas faultDatas = mapper.readValue(root.get("faultData").toString(), TrapDatas.class); - ClosedLoopGridJSONData policyJsonData = mapper.readValue(root.get("policyData").get("policy").toString(), ClosedLoopGridJSONData.class); - ClosedLoopFaultBody jsonBody = mapper.readValue(root.get("policyData").get("policy").get("jsonBodyData").toString(), ClosedLoopFaultBody.class); - - ArrayList trapSignatureDatas = new ArrayList<>(); - if(trapDatas.getTrap1() != null){ - trapSignatureDatas.add(trapDatas); - } - ArrayList faultSignatureDatas = new ArrayList<>(); - if(faultDatas.getTrap1() != null){ - faultSignatureDatas.add(faultDatas); - } - - String resultBody = ""; - if(!policyJsonData.getConnecttriggerSignatures().isEmpty()){ - resultBody = resultBody + "("; - for(int i = policyJsonData.getConnecttriggerSignatures().size()-1; i>=0 ; i--){ - String connectBody = connectTriggerSignature(i, policyJsonData.getConnecttriggerSignatures(), trapSignatureDatas.get(0)); - resultBody = resultBody + connectBody; - } - resultBody = resultBody + ")"; - }else{ - if(!trapSignatureDatas.isEmpty()){ - resultBody = callTrap("nill", trapSignatureDatas.get(0)); - } - } - ClosedLoopSignatures triggerSignatures = new ClosedLoopSignatures(); - triggerSignatures.setSignatures(resultBody); - if(policyData.getClearTimeOut() != null){ - triggerSignatures.setTimeWindow(Integer.parseInt(policyData.getClearTimeOut())); - triggerSignatures.setTrapMaxAge(Integer.parseInt(policyData.getTrapMaxAge())); - ClosedLoopFaultTriggerUISignatures uiTriggerSignatures = new ClosedLoopFaultTriggerUISignatures(); - if(!trapSignatureDatas.isEmpty()){ - uiTriggerSignatures.setSignatures(getUITriggerSignature("Trap", trapSignatureDatas.get(0))); - if(!policyJsonData.getConnecttriggerSignatures().isEmpty()){ - uiTriggerSignatures.setConnectSignatures(getUIConnectTraps(policyJsonData.getConnecttriggerSignatures())); - } - } - jsonBody.setTriggerSignaturesUsedForUI(uiTriggerSignatures); - jsonBody.setTriggerTimeWindowUsedForUI(Integer.parseInt(policyData.getClearTimeOut())); - jsonBody.setTrapMaxAgeUsedForUI(Integer.parseInt(policyData.getTrapMaxAge())); - } - - jsonBody.setTriggerSignatures(triggerSignatures); - String faultBody = ""; - if(!policyJsonData.getConnectVerificationSignatures().isEmpty()){ - faultBody = faultBody + "("; - for(int i = policyJsonData.getConnectVerificationSignatures().size()-1; i>=0 ; i--){ - String connectBody = connectTriggerSignature(i, policyJsonData.getConnectVerificationSignatures(), faultSignatureDatas.get(0)); - faultBody = faultBody + connectBody; - } - faultBody = faultBody + ")"; - }else{ - if(!faultSignatureDatas.isEmpty()){ - faultBody = callTrap("nill", faultSignatureDatas.get(0)); - } - } - ClosedLoopSignatures faultSignatures = new ClosedLoopSignatures(); - faultSignatures.setSignatures(faultBody); - if(policyData.getVerificationclearTimeOut() != null){ - faultSignatures.setTimeWindow(Integer.parseInt(policyData.getVerificationclearTimeOut())); - ClosedLoopFaultTriggerUISignatures uifaultSignatures = new ClosedLoopFaultTriggerUISignatures(); - if(!faultSignatureDatas.isEmpty()){ - uifaultSignatures.setSignatures(getUITriggerSignature("Fault", faultSignatureDatas.get(0))); - if(!policyJsonData.getConnectVerificationSignatures().isEmpty()){ - uifaultSignatures.setConnectSignatures(getUIConnectTraps(policyJsonData.getConnectVerificationSignatures())); - } - } - - jsonBody.setVerificationSignaturesUsedForUI(uifaultSignatures); - jsonBody.setVerfificationTimeWindowUsedForUI(Integer.parseInt(policyData.getVerificationclearTimeOut())); - } - jsonBody.setVerificationSignatures(faultSignatures); - ObjectWriter om = new ObjectMapper().writer(); - String json = om.writeValueAsString(jsonBody); - policyData.setJsonBody(json); - - }catch(Exception e){ - policyLogger.error("Exception Occured while setting data to Adapter" , e); - } - return policyData; - } - - - @SuppressWarnings("unchecked") - private String connectTriggerSignature(int index, ArrayList triggerSignatures, Object object) { - String resultBody = ""; - Map connectTraps = (Map) triggerSignatures.get(index); - try{ - String notBox = ""; - if(connectTraps.keySet().contains("notBox")){ - notBox = connectTraps.get("notBox"); - } - resultBody = resultBody + "(" + notBox; - }catch(NullPointerException e){ - policyLogger.info("General error" , e); - resultBody = resultBody + "("; - } - String connectTrap1 = connectTraps.get("connectTrap1"); - if(connectTrap1.startsWith("Trap") || connectTrap1.startsWith("Fault")){ - String trapBody = callTrap(connectTrap1, object); - if(trapBody!=null){ - resultBody = resultBody + trapBody; - } - }else if(connectTrap1.startsWith("C")){ - for(int i=0; i<= triggerSignatures.size(); i++){ - Map triggerSignature = (Map) triggerSignatures.get(i); - if(triggerSignature.get("id").equals(connectTrap1)){ - resultBody = resultBody + "("; - String connectBody = connectTriggerSignature(i, triggerSignatures, object); - resultBody = resultBody + connectBody + ")"; - }else{ - i++; - } - } - } - try{ - String trapCount1 = connectTraps.get("trapCount1"); - resultBody = resultBody + ", Time = " + trapCount1 + ")"; - }catch(NullPointerException e){ - policyLogger.info("General error" , e); - } - try{ - String operatorBox = connectTraps.get("operatorBox"); - resultBody = resultBody + operatorBox +"("; - }catch (NullPointerException e){ - policyLogger.info("General error" , e); - } - try{ - String connectTrap2 = connectTraps.get("connectTrap2"); - if(connectTrap2.startsWith("Trap") || connectTrap2.startsWith("Fault")){ - String trapBody = callTrap(connectTrap2, object); - if(trapBody!=null){ - resultBody = resultBody + trapBody; - } - }else if(connectTrap2.startsWith("C")){ - for(int i=0; i<= triggerSignatures.size(); i++){ - Map triggerSignature = (Map) triggerSignatures.get(i); - if(triggerSignature.get("id").equals(connectTrap2)){ - resultBody = resultBody + "("; - String connectBody = connectTriggerSignature(i, triggerSignatures, object); - resultBody = resultBody + connectBody + ")"; - }else{ - i++; - } - } - } - }catch(NullPointerException e){ - policyLogger.info("General error" , e); - } - try{ - String trapCount2 = connectTraps.get("trapCount2"); - resultBody = resultBody + ", Time = " + trapCount2 + ")"; - }catch(NullPointerException e){ - policyLogger.info("General error" , e); - } - return resultBody; - } - - - private String callTrap(String trap, Object object) { - String signatureBody = ""; - TrapDatas trapDatas = (TrapDatas) object; - ArrayList attributeList = new ArrayList<>(); - // Read the Trap - if(!trap.equals("nill")){ - try{ - if(trap.startsWith("Trap")){ - if(trap.equals("Trap1")){ - attributeList = trapDatas.getTrap1(); - }else if(trap.equals("Trap2")){ - attributeList = trapDatas.getTrap2(); - }else if(trap.equals("Trap3")){ - attributeList = trapDatas.getTrap3(); - }else if(trap.equals("Trap4")){ - attributeList = trapDatas.getTrap4(); - }else if(trap.equals("Trap5")){ - attributeList = trapDatas.getTrap5(); - }else if(trap.equals("Trap6")){ - attributeList = trapDatas.getTrap6(); - } - }else{ - if(trap.startsWith("Fault")){ - if(trap.equals("Fault1")){ - attributeList = trapDatas.getTrap1(); - }else if(trap.equals("Fault2")){ - attributeList = trapDatas.getTrap2(); - }else if(trap.equals("Fault3")){ - attributeList = trapDatas.getTrap3(); - }else if(trap.equals("Fault4")){ - attributeList = trapDatas.getTrap4(); - }else if(trap.equals("Fault5")){ - attributeList = trapDatas.getTrap5(); - }else if(trap.equals("Fault6")){ - attributeList = trapDatas.getTrap6(); - } - } - } - } catch(Exception e){ - return "(" + trap + ")"; - } - }else{ - if(trapDatas.getTrap1()!=null){ - attributeList = trapDatas.getTrap1(); - }else{ - return ""; - } - } - signatureBody = signatureBody + "(" + readAttributes(attributeList, attributeList.size()-1) + ")"; - return signatureBody; - } - - @SuppressWarnings("unchecked") - private String readAttributes(ArrayList object, int index) { - String attributes = ""; - Map trapSignatures = (Map) object.get(index); - // Read the Elements. - Object notBox = ""; - if(trapSignatures.keySet().contains("notBox")){ - notBox = trapSignatures.get("notBox"); - } - if(notBox!=null){ - attributes = attributes + notBox.toString(); - } - Object trapName1 = trapSignatures.get("trigger1"); - if(trapName1!=null){ - String attrib = trapName1.toString(); - if(attrib.startsWith("A")){ - try{ - int iy = Integer.parseInt(attrib.substring(1))-1; - attributes = attributes + "(" + readAttributes(object, iy) + ")"; - }catch(NumberFormatException e){ - try { - attrib = getVarbindOID(attrib); - attributes = attributes + "("+ URLEncoder.encode(attrib, "UTF-8")+ ")"; - } catch (UnsupportedEncodingException e1) { - //logger.error("Caused Exception while Encoding Varbind Dictionary Values"+e1); - } - } - }else{ - try { - attrib = getVarbindOID(attrib); - attributes = attributes + "("+ URLEncoder.encode(attrib, "UTF-8")+ ")"; - } catch (UnsupportedEncodingException e) { - //logger.error("Caused Exception while Encoding Varbind Dictionary Values"+e); - } - } - }else{ - return ""; - } - Object comboBox = trapSignatures.get("operatorBox"); - if(comboBox!=null){ - attributes = attributes + comboBox.toString(); - }else{ - return attributes; - } - Object trapName2 = trapSignatures.get("trigger2"); - if(trapName2!=null){ - String attrib = trapName2.toString(); - if(attrib.startsWith("A")){ - try{ - int iy = Integer.parseInt(attrib.substring(1))-1; - attributes = attributes + "(" + readAttributes(object, iy) + ")"; - }catch(NumberFormatException e){ - try { - attrib = getVarbindOID(attrib); - attributes = attributes + "("+ URLEncoder.encode(attrib, "UTF-8") + ")"; - } catch (UnsupportedEncodingException e1) { - //logger.error("Caused Exception while Encoding Varbind Dictionary Values"+e1); - } - } - }else{ - try { - attrib = getVarbindOID(attrib); - attributes = attributes + "("+ URLEncoder.encode(attrib, "UTF-8") + ")"; - } catch (UnsupportedEncodingException e) { - //logger.error("Caused Exception while Encoding Varbind Dictionary Values"+e); - } - } - } - return attributes; - } - - private String getVarbindOID(String attrib) { - VarbindDictionary varbindId = null; - try{ - varbindId = (VarbindDictionary) commonclassdao.getEntityItem(VarbindDictionary.class, "varbindName", attrib); - return varbindId.getVarbindOID(); - }catch(Exception e){ - return attrib; - } - } - - - //connect traps data set to JSON Body as String - @SuppressWarnings({ "unchecked", "rawtypes" }) - private String getUIConnectTraps(ArrayList connectTrapSignatures) { - String resultBody = ""; - String connectMainBody = ""; - for(int j = 0; j < connectTrapSignatures.size(); j++){ - Map connectTraps = (Map)connectTrapSignatures.get(j); - String connectBody = ""; - Object object = connectTraps; - if(object instanceof LinkedHashMap){ - String notBox = ""; - String connectTrap1 = ""; - String trapCount1 = ""; - String operatorBox = ""; - String connectTrap2 = ""; - String trapCount2 = ""; - if(((LinkedHashMap) object).keySet().contains("notBox")){ - notBox = ((LinkedHashMap) object).get("notBox").toString(); - } - if(((LinkedHashMap) object).get("connectTrap1") != null){ - connectTrap1 = ((LinkedHashMap) object).get("connectTrap1").toString(); - } - if(((LinkedHashMap) object).get("trapCount1") != null){ - trapCount1 = ((LinkedHashMap) object).get("trapCount1").toString(); - } - if(((LinkedHashMap) object).get("operatorBox") != null){ - operatorBox = ((LinkedHashMap) object).get("operatorBox").toString(); - } - if(((LinkedHashMap) object).get("connectTrap2") != null){ - connectTrap2 = ((LinkedHashMap) object).get("connectTrap2").toString(); - } - if(((LinkedHashMap) object).get("trapCount2") != null){ - trapCount2 = ((LinkedHashMap) object).get("trapCount2").toString(); - } - connectBody = notBox + "@!" + connectTrap1 + "@!" + trapCount1 + "@!" + operatorBox + "@!" + connectTrap2 + "@!" + trapCount2 + "#!?!"; - } - resultBody = resultBody + connectBody; - } - connectMainBody = connectMainBody + resultBody; - return connectMainBody; - } - - - - // get Trigger signature from JSON body - @SuppressWarnings({ "rawtypes", "unchecked" }) - private String getUITriggerSignature(String trap, Object object2) { - String triggerBody = ""; - TrapDatas trapDatas = (TrapDatas) object2; - ArrayList attributeList = new ArrayList<>(); - // Read the Trap - if(trap.startsWith("Trap")){ - if(trapDatas.getTrap1()!= null){ - attributeList.add(trapDatas.getTrap1()); - } - if(trapDatas.getTrap2()!= null){ - attributeList.add(trapDatas.getTrap2()); - } - if(trapDatas.getTrap3()!= null){ - attributeList.add(trapDatas.getTrap3()); - } - if(trapDatas.getTrap4()!= null){ - attributeList.add(trapDatas.getTrap4()); - } - if(trapDatas.getTrap5()!= null){ - attributeList.add(trapDatas.getTrap5()); - } - if(trapDatas.getTrap6()!= null){ - attributeList.add(trapDatas.getTrap6()); - } - }else{ - if(trap.startsWith("Fault")){ - if(trapDatas.getTrap1()!= null){ - attributeList.add(trapDatas.getTrap1()); - } - if(trapDatas.getTrap2()!= null){ - attributeList.add(trapDatas.getTrap2()); - } - if(trapDatas.getTrap3()!= null){ - attributeList.add(trapDatas.getTrap3()); - } - if(trapDatas.getTrap4()!= null){ - attributeList.add(trapDatas.getTrap4()); - } - if(trapDatas.getTrap5()!= null){ - attributeList.add(trapDatas.getTrap5()); - } - if(trapDatas.getTrap6()!= null){ - attributeList.add(trapDatas.getTrap6()); - } - } - } - - for(int j = 0; j < attributeList.size(); j++){ - String signatureBody = ""; - ArrayList connectTraps = (ArrayList) attributeList.get(j); - for(int i =0 ; i < connectTraps.size(); i++){ - String connectBody = ""; - Object object = connectTraps.get(i); - if(object instanceof LinkedHashMap){ - String notBox = ""; - String trigger1 = ""; - String operatorBox = ""; - String trigger2 = ""; - if(((LinkedHashMap) object).keySet().contains("notBox")){ - notBox = ((LinkedHashMap) object).get("notBox").toString(); - } - if(((LinkedHashMap) object).get("trigger1") != null){ - trigger1 = ((LinkedHashMap) object).get("trigger1").toString(); - } - if(((LinkedHashMap) object).get("operatorBox") != null){ - operatorBox = ((LinkedHashMap) object).get("operatorBox").toString(); - } - if(((LinkedHashMap) object).get("trigger2") != null){ - trigger2 = ((LinkedHashMap) object).get("trigger2").toString(); - } - connectBody = notBox + "@!" + trigger1 + "@!" + operatorBox + "@!" + trigger2 + "#!"; - } - signatureBody = signatureBody + connectBody; - } - triggerBody = triggerBody + signatureBody + "?!"; - } - - return triggerBody; - } - - public void prePopulateClosedLoopFaultPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - if (policyAdapter.getPolicyData() instanceof PolicyType) { - Object policyData = policyAdapter.getPolicyData(); - PolicyType policy = (PolicyType) policyData; - policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("Fault_") +6); - policyAdapter.setPolicyName(policyNameValue); - String description = ""; - try{ - description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); - }catch(Exception e){ - description = policy.getDescription(); - } - policyAdapter.setPolicyDescription(description); - // Get the target data under policy. - TargetType target = policy.getTarget(); - if (target != null) { - // Under target we have AnyOFType - List anyOfList = target.getAnyOf(); - if (anyOfList != null) { - Iterator iterAnyOf = anyOfList.iterator(); - while (iterAnyOf.hasNext()) { - AnyOfType anyOf = iterAnyOf.next(); - // Under AnyOFType we have AllOFType - List allOfList = anyOf.getAllOf(); - if (allOfList != null) { - Iterator iterAllOf = allOfList.iterator(); - while (iterAllOf.hasNext()) { - AllOfType allOf = iterAllOf.next(); - // Under AllOFType we have Match - List matchList = allOf.getMatch(); - if (matchList != null) { - Iterator iterMatch = matchList.iterator(); - while (iterMatch.hasNext()) { - MatchType match = iterMatch.next(); - // - // Under the match we have attribute value and - // attributeDesignator. So,finally down to the actual attribute. - // - AttributeValueType attributeValue = match.getAttributeValue(); - String value = (String) attributeValue.getContent().get(0); - AttributeDesignatorType designator = match.getAttributeDesignator(); - String attributeId = designator.getAttributeId(); - - // First match in the target is EcompName, so set that value. - if (attributeId.equals("ECOMPName")) { - policyAdapter.setEcompName(value); - EcompName ecompName = new EcompName(); - ecompName.setEcompName(value); - policyAdapter.setEcompNameField(ecompName); - } - if (attributeId.equals("RiskType")){ - policyAdapter.setRiskType(value); - } - if (attributeId.equals("RiskLevel")){ - policyAdapter.setRiskLevel(value); - } - if (attributeId.equals("guard")){ - policyAdapter.setGuard(value); - } - if (attributeId.equals("TTLDate") && !value.contains("NA")){ - String newDate = convertDate(value, true); - policyAdapter.setTtlDate(newDate); - } - } - } - } - } - } - } - } - readClosedLoopJSONFile(policyAdapter, entity); - } - - } - - private String convertDate(String dateTTL, boolean portalType) { - String formateDate = null; - String[] date; - String[] parts; - - if (portalType){ - parts = dateTTL.split("-"); - formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z"; - } else { - date = dateTTL.split("T"); - parts = date[0].split("-"); - formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; - } - return formateDate; - } - - private String readClosedLoopJSONFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - ObjectMapper mapper = new ObjectMapper(); - try { - ClosedLoopFaultBody closedLoopBody = mapper.readValue(entity.getConfigurationData().getConfigBody(), ClosedLoopFaultBody.class); - if(closedLoopBody.getClosedLoopPolicyStatus().equalsIgnoreCase("ACTIVE")){ - closedLoopBody.setClosedLoopPolicyStatus("Active"); - }else{ - closedLoopBody.setClosedLoopPolicyStatus("InActive"); - } - policyAdapter.setJsonBodyData(closedLoopBody); - if(closedLoopBody.getTrapMaxAgeUsedForUI() != null){ - policyAdapter.setTrapMaxAge(closedLoopBody.getTrapMaxAgeUsedForUI().toString()); - } - if(closedLoopBody.getTriggerTimeWindowUsedForUI() != null){ - policyAdapter.setClearTimeOut(closedLoopBody.getTriggerTimeWindowUsedForUI().toString()); - } - if(closedLoopBody.getVerfificationTimeWindowUsedForUI() != null){ - policyAdapter.setVerificationclearTimeOut(closedLoopBody.getVerfificationTimeWindowUsedForUI().toString()); - } - - } catch (Exception e) { - policyLogger.error("Exception Occured"+e); - } - - return null; - } - -} - -class TrapDatas{ - private ArrayList trap1; - private ArrayList trap2; - private ArrayList trap3; - private ArrayList trap4; - private ArrayList trap5; - private ArrayList trap6; - public ArrayList getTrap1() { - return trap1; - } - public void setTrap1(ArrayList trap1) { - this.trap1 = trap1; - } - public ArrayList getTrap2() { - return trap2; - } - public void setTrap2(ArrayList trap2) { - this.trap2 = trap2; - } - public ArrayList getTrap3() { - return trap3; - } - public void setTrap3(ArrayList trap3) { - this.trap3 = trap3; - } - public ArrayList getTrap4() { - return trap4; - } - public void setTrap4(ArrayList trap4) { - this.trap4 = trap4; - } - public ArrayList getTrap5() { - return trap5; - } - public void setTrap5(ArrayList trap5) { - this.trap5 = trap5; - } - public ArrayList getTrap6() { - return trap6; - } - public void setTrap6(ArrayList trap6) { - this.trap6 = trap6; - } -} - -class ClosedLoopGridJSONData{ - - private String clearTimeOut; - private String trapMaxAge; - private String verificationclearTimeOut; - private ArrayList connecttriggerSignatures; - private ArrayList connectVerificationSignatures; - - public String getClearTimeOut() { - return clearTimeOut; - } - public void setClearTimeOut(String clearTimeOut) { - this.clearTimeOut = clearTimeOut; - } - public String getTrapMaxAge() { - return trapMaxAge; - } - public void setTrapMaxAge(String trapMaxAge) { - this.trapMaxAge = trapMaxAge; - } - public String getVerificationclearTimeOut() { - return verificationclearTimeOut; - } - public void setVerificationclearTimeOut(String verificationclearTimeOut) { - this.verificationclearTimeOut = verificationclearTimeOut; - } - - - public ArrayList getConnecttriggerSignatures() { - return connecttriggerSignatures; - } - public void setConnecttriggerSignatures(ArrayList connecttriggerSignatures) { - this.connecttriggerSignatures = connecttriggerSignatures; - } - public ArrayList getConnectVerificationSignatures() { - return connectVerificationSignatures; - } - public void setConnectVerificationSignatures(ArrayList connectVerificationSignatures) { - this.connectVerificationSignatures = connectVerificationSignatures; - } -} \ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateClosedLoopPMController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateClosedLoopPMController.java deleted file mode 100644 index 39850d990..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateClosedLoopPMController.java +++ /dev/null @@ -1,208 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.controller; - - -import java.io.IOException; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; - -import javax.json.JsonArray; -import javax.json.JsonObject; - -import org.openecomp.policy.admin.PolicyManagerServlet; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.rest.adapter.ClosedLoopPMBody; -import org.openecomp.policy.rest.adapter.PolicyRestAdapter; -import org.openecomp.policy.rest.jpa.PolicyEntity; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; - -public class CreateClosedLoopPMController{ - - private static final Logger LOGGER = FlexLogger.getLogger(CreateClosedLoopPMController.class); - - protected PolicyRestAdapter policyAdapter = null; - - public void prePopulateClosedLoopPMPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - if (policyAdapter.getPolicyData() instanceof PolicyType) { - Object policyData = policyAdapter.getPolicyData(); - PolicyType policy = (PolicyType) policyData; - policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("PM_") +3); - policyAdapter.setPolicyName(policyNameValue); - String description = ""; - try{ - description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); - }catch(Exception e){ - LOGGER.info("General error" , e); - description = policy.getDescription(); - } - policyAdapter.setPolicyDescription(description); - // Get the target data under policy. - TargetType target = policy.getTarget(); - if (target != null) { - // Under target we have AnyOFType - List anyOfList = target.getAnyOf(); - if (anyOfList != null) { - Iterator iterAnyOf = anyOfList.iterator(); - while (iterAnyOf.hasNext()) { - AnyOfType anyOf = iterAnyOf.next(); - // Under AnyOFType we have AllOFType - List allOfList = anyOf.getAllOf(); - if (allOfList != null) { - Iterator iterAllOf = allOfList.iterator(); - while (iterAllOf.hasNext()) { - AllOfType allOf = iterAllOf.next(); - // Under AllOFType we have Match - List matchList = allOf.getMatch(); - if (matchList != null) { - Iterator iterMatch = matchList.iterator(); - while (matchList.size()>1 && iterMatch.hasNext()) { - MatchType match = iterMatch.next(); - // - // Under the match we have attribute value and - // attributeDesignator. So,finally down to the actual attribute. - // - AttributeValueType attributeValue = match.getAttributeValue(); - String value = (String) attributeValue.getContent().get(0); - AttributeDesignatorType designator = match.getAttributeDesignator(); - String attributeId = designator.getAttributeId(); - - // First match in the target is EcompName, so set that value. - if (attributeId.equals("ECOMPName")) { - policyAdapter.setEcompName(value); - } - if (attributeId.equals("RiskType")){ - policyAdapter.setRiskType(value); - } - if (attributeId.equals("RiskLevel")){ - policyAdapter.setRiskLevel(value); - } - if (attributeId.equals("guard")){ - policyAdapter.setGuard(value); - } - if (attributeId.equals("TTLDate") && !value.contains("NA")){ - String newDate = convertDate(value, true); - policyAdapter.setTtlDate(newDate); - } - if (attributeId.equals("ServiceType")){ - LinkedHashMap serviceTypePolicyName1 = new LinkedHashMap<>(); - String key = "serviceTypePolicyName"; - serviceTypePolicyName1.put(key, value); - policyAdapter.setServiceTypePolicyName(serviceTypePolicyName1); - LinkedHashMap vertica = new LinkedHashMap<>(); - vertica.put("verticaMetrics", getVertica(value)); - policyAdapter.setVerticaMetrics(vertica); - LinkedHashMap desc = new LinkedHashMap<>(); - desc.put("policyDescription", getDescription(value)); - policyAdapter.setDescription(desc); - LinkedHashMap attributes = new LinkedHashMap<>(); - attributes.put("attributes", getAttributes(value)); - policyAdapter.setAttributeFields(attributes); - } - } - } - } - } - } - } - } - readClosedLoopJSONFile(policyAdapter, entity); - } - } - - private String convertDate(String dateTTL, boolean portalType) { - String formateDate = null; - String[] date; - String[] parts; - - if (portalType){ - parts = dateTTL.split("-"); - formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z"; - } else { - date = dateTTL.split("T"); - parts = date[0].split("-"); - formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; - } - return formateDate; - } - - protected void readClosedLoopJSONFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - ObjectMapper mapper = new ObjectMapper(); - try { - ClosedLoopPMBody closedLoopBody = mapper.readValue(entity.getConfigurationData().getConfigBody(), ClosedLoopPMBody.class); - policyAdapter.setJsonBodyData(closedLoopBody); - } catch (IOException e) { - LOGGER.error("Exception Occured"+e); - } - } - - //get vertica metrics data from the table - private String getVertica(String policyName){ - String verticas = null; - JsonArray data = PolicyManagerServlet.getPolicyNames(); - for(int i=0 ; i< data.size(); i++){ - if(policyName.equals(data.getJsonObject(i).getJsonString("serviceTypePolicyName").getString())){ - verticas = data.getJsonObject(i).getJsonString("verticaMetrics").getString(); - return verticas; - } - } - return verticas; - } - - //get policy description from the table - private String getDescription(String policyName){ - String description = null; - JsonArray data = PolicyManagerServlet.getPolicyNames(); - for(int i=0 ; i< data.size(); i++){ - if(policyName.equals(data.getJsonObject(i).getJsonString("serviceTypePolicyName").getString())){ - description = data.getJsonObject(i).getJsonString("policyDescription").getString(); - return description; - } - } - return description; - } - - //get Attributes - private JsonObject getAttributes(String policyName){ - JsonObject attributes = null; - JsonArray data = PolicyManagerServlet.getPolicyNames(); - for(int i=0 ; i< data.size(); i++){ - if(policyName.equals(data.getJsonObject(i).getJsonString("serviceTypePolicyName").getString())){ - attributes = data.getJsonObject(i).getJsonObject("attributes"); - return attributes; - } - } - return attributes; - } - -} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java deleted file mode 100644 index 777fb89e3..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java +++ /dev/null @@ -1,1622 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.controller; - - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.TreeMap; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.compress.utils.IOUtils; -import org.apache.commons.fileupload.FileItem; -import org.apache.commons.fileupload.disk.DiskFileItemFactory; -import org.apache.commons.fileupload.servlet.ServletFileUpload; -import org.apache.commons.io.FileUtils; -import org.apache.commons.lang.StringUtils; -import org.json.JSONArray; -import org.json.JSONObject; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.rest.XACMLRestProperties; -import org.openecomp.policy.rest.adapter.PolicyRestAdapter; -import org.openecomp.policy.rest.dao.CommonClassDao; -import org.openecomp.policy.rest.jpa.GroupPolicyScopeList; -import org.openecomp.policy.rest.jpa.MicroServiceModels; -import org.openecomp.policy.rest.jpa.PolicyEntity; -import org.openecomp.policy.rest.util.MSAttributeObject; -import org.openecomp.policy.rest.util.MSModelUtils; -import org.openecomp.policy.rest.util.MSModelUtils.MODEL_TYPE; -import org.openecomp.portalsdk.core.controller.RestrictedBaseController; -import org.openecomp.portalsdk.core.web.support.JsonMessage; -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.servlet.ModelAndView; -import org.yaml.snakeyaml.Yaml; - -import com.att.research.xacml.util.XACMLProperties; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectWriter; -import com.fasterxml.jackson.databind.node.JsonNodeFactory; -import com.fasterxml.jackson.databind.node.ObjectNode; -import com.google.gson.Gson; - -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; - -@Controller -@RequestMapping("/") -public class CreateDcaeMicroServiceController extends RestrictedBaseController { - private static final Logger LOGGER = FlexLogger.getLogger(CreateDcaeMicroServiceController.class); - - private static CommonClassDao commonClassDao; - - public static CommonClassDao getCommonClassDao() { - return commonClassDao; - } - - public static void setCommonClassDao(CommonClassDao commonClassDao) { - CreateDcaeMicroServiceController.commonClassDao = commonClassDao; - } - - private MicroServiceModels newModel; - private String newFile; - private String directory; - private List modelList = new ArrayList<>(); - private List dirDependencyList = new ArrayList<>(); - private HashMap classMap = new HashMap<>(); - //Tosca Model related Datastructure. - String referenceAttributes; - String attributeString; - String listConstraints; - String subAttributeString; - HashMap retmap = new HashMap<>(); - Set uniqueKeys= new HashSet<>(); - Set uniqueDataKeys= new HashSet<>(); - StringBuilder dataListBuffer=new StringBuilder(); - List dataConstraints= new ArrayList <>(); - - public static final String DATATYPE = "data_types.policy.data."; - public static final String PROPERTIES=".properties."; - public static final String TYPE=".type"; - public static final String STRING="string"; - public static final String INTEGER="integer"; - public static final String LIST="list"; - public static final String DEFAULT=".default"; - public static final String REQUIRED=".required"; - public static final String MANYFALSE=":MANY-false"; - - - @Autowired - private CreateDcaeMicroServiceController(CommonClassDao commonClassDao){ - CreateDcaeMicroServiceController.commonClassDao = commonClassDao; - } - - public CreateDcaeMicroServiceController(){} - - protected PolicyRestAdapter policyAdapter = null; - private int priorityCount; - private Map attributesListRefMap = new HashMap<>(); - private Map> arrayTextList = new HashMap<>(); - - public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) { - - String jsonContent = null; - try{ - jsonContent = decodeContent(root.get("policyJSON")).toString(); - constructJson(policyData, jsonContent); - }catch(Exception e){ - LOGGER.error("Error while decoding microservice content", e); - } - - return policyData; - } - - private GroupPolicyScopeList getPolicyObject(String policyScope) { - GroupPolicyScopeList groupList= (GroupPolicyScopeList) commonClassDao.getEntityItem(GroupPolicyScopeList.class, "name", policyScope); - return groupList; - } - - private PolicyRestAdapter constructJson(PolicyRestAdapter policyAdapter, String jsonContent) { - ObjectWriter om = new ObjectMapper().writer(); - String json=""; - DCAEMicroServiceObject microServiceObject = new DCAEMicroServiceObject(); - MicroServiceModels returnModel = new MicroServiceModels(); - microServiceObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_MS)); - if(policyAdapter.getServiceType() !=null){ - microServiceObject.setService(policyAdapter.getServiceType()); - microServiceObject.setVersion(policyAdapter.getVersion()); - returnModel = getAttributeObject(microServiceObject.getService(), microServiceObject.getVersion()); - } - if (returnModel.getAnnotation()==null || returnModel.getAnnotation().isEmpty()){ - if(policyAdapter.getUuid()!=null){ - microServiceObject.setUuid(policyAdapter.getUuid()); - } - if(policyAdapter.getLocation()!=null){ - microServiceObject.setLocation(policyAdapter.getLocation()); - } - if(policyAdapter.getConfigName()!=null){ - microServiceObject.setConfigName(policyAdapter.getConfigName()); - } - GroupPolicyScopeList policyScopeValue = getPolicyObject(policyAdapter.getPolicyScope()); - if(policyScopeValue!=null){ - microServiceObject.setPolicyScope(policyScopeValue.getGroupList()); - } - } - - if(policyAdapter.getPolicyName()!=null){ - microServiceObject.setPolicyName(policyAdapter.getPolicyName()); - } - if(policyAdapter.getPolicyDescription()!=null){ - microServiceObject.setDescription(policyAdapter.getPolicyDescription()); - } - if (policyAdapter.getPriority()!=null){ - microServiceObject.setPriority(policyAdapter.getPriority()); - }else { - microServiceObject.setPriority("9999"); - } - - if (policyAdapter.getRiskLevel()!=null){ - microServiceObject.setRiskLevel(policyAdapter.getRiskLevel()); - } - if (policyAdapter.getRiskType()!=null){ - microServiceObject.setRiskType(policyAdapter.getRiskType()); - } - if (policyAdapter.getGuard()!=null){ - microServiceObject.setGuard(policyAdapter.getGuard()); - } - microServiceObject.setContent(jsonContent); - - try { - json = om.writeValueAsString(microServiceObject); - } catch (JsonProcessingException e) { - LOGGER.error("Error writing out the object", e); - } - LOGGER.info(json); - String cleanJson = cleanUPJson(json); - cleanJson = removeNullAttributes(cleanJson); - policyAdapter.setJsonBody(cleanJson); - return policyAdapter; - } - - private String removeNullAttributes(String cleanJson) { - ObjectMapper mapper = new ObjectMapper(); - - try { - JsonNode rootNode = mapper.readTree(cleanJson); - JsonNode returnNode = mapper.readTree(cleanJson); - Iterator> fieldsIterator = rootNode.fields(); - boolean remove = false; - while (fieldsIterator.hasNext()) { - Map.Entry field = fieldsIterator.next(); - final String key = field.getKey(); - final JsonNode value = field.getValue(); - if (value==null || value.isNull()){ - ((ObjectNode) returnNode).remove(key); - remove = true; - } - } - if (remove){ - cleanJson = returnNode.toString(); - } - } catch (IOException e) { - LOGGER.error("Error writing out the JsonNode",e); - } - return cleanJson; - } - - // Second index of dot should be returned. - public int stringBetweenDots(String str){ - String stringToSearch=str; - String[]ss=stringToSearch.split("\\."); - if(ss!=null){ - int len= ss.length; - if(len>2){ - uniqueKeys.add(ss[2]); - } - } - - return uniqueKeys.size(); - } - - public void stringBetweenDotsForDataFields(String str){ - String stringToSearch=str; - String[]ss=stringToSearch.split("\\."); - if(ss!=null){ - int len= ss.length; - - if(len>2){ - uniqueDataKeys.add(ss[0]+"%"+ss[2]); - } - } - } - - - public Map load(String fileName) throws IOException { - File newConfiguration = new File(fileName); - InputStream is = null; - try { - is = new FileInputStream(newConfiguration); - } catch (FileNotFoundException e) { - LOGGER.error(e); - } - - Yaml yaml = new Yaml(); - @SuppressWarnings("unchecked") - Map yamlMap = (Map) yaml.load(is); - StringBuilder sb = new StringBuilder(); - Map settings = new HashMap<>(); - if (yamlMap == null) { - return settings; - } - List path = new ArrayList <>(); - serializeMap(settings, sb, path, yamlMap); - return settings; - } - - public Map load(byte[] source) throws IOException { - Yaml yaml = new Yaml(); - @SuppressWarnings("unchecked") - Map yamlMap = (Map) yaml.load(Arrays.toString(source)); - StringBuilder sb = new StringBuilder(); - Map settings = new HashMap <>(); - if (yamlMap == null) { - return settings; - } - List path = new ArrayList <>(); - serializeMap(settings, sb, path, yamlMap); - return settings; - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - private void serializeMap(Map settings, StringBuilder sb, List path, Map yamlMap) { - for (Map.Entry entry : yamlMap.entrySet()) { - if (entry.getValue() instanceof Map) { - path.add((String) entry.getKey()); - serializeMap(settings, sb, path, (Map) entry.getValue()); - path.remove(path.size() - 1); - } else if (entry.getValue() instanceof List) { - path.add((String) entry.getKey()); - serializeList(settings, sb, path, (List) entry.getValue()); - path.remove(path.size() - 1); - } else { - serializeValue(settings, sb, path, (String) entry.getKey(), entry.getValue()); - } - } - } - - @SuppressWarnings("unchecked") - private void serializeList(Map settings, StringBuilder sb, List path, List yamlList) { - int counter = 0; - for (Object listEle : yamlList) { - if (listEle instanceof Map) { - path.add(Integer.toString(counter)); - serializeMap(settings, sb, path, (Map) listEle); - path.remove(path.size() - 1); - } else if (listEle instanceof List) { - path.add(Integer.toString(counter)); - serializeList(settings, sb, path, (List) listEle); - path.remove(path.size() - 1); - } else { - serializeValue(settings, sb, path, Integer.toString(counter), listEle); - } - counter++; - } - } - - private void serializeValue(Map settings, StringBuilder sb, List path, String name, Object value) { - if (value == null) { - return; - } - sb.setLength(0); - for (String pathEle : path) { - sb.append(pathEle).append('.'); - } - sb.append(name); - settings.put(sb.toString(), value.toString()); - } - - void parseDataAndPolicyNodes(Map map){ - for(String key:map.keySet()){ - if(key.contains("policy.nodes.Root")) - { - continue; - } - else if(key.contains("policy.nodes")){ - String wordToFind = "policy.nodes."; - int indexForPolicyNode=key.indexOf(wordToFind); - String subNodeString= key.substring(indexForPolicyNode+13, key.length()); - - stringBetweenDots(subNodeString); - } - else if(key.contains("policy.data")){ - String wordToFind="policy.data."; - int indexForPolicyNode=key.indexOf(wordToFind); - String subNodeString= key.substring(indexForPolicyNode+12, key.length()); - - stringBetweenDotsForDataFields(subNodeString); - } - } - } - - HashMap parseDataNodes(Map map){ - HashMap dataMapForJson=new HashMap <>(); - for(String uniqueDataKey: uniqueDataKeys){ - if(uniqueDataKey.contains("%")){ - String[] uniqueDataKeySplit= uniqueDataKey.split("%"); - String findType=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+TYPE; - String typeValue=map.get(findType); - LOGGER.info(typeValue); - if(typeValue.equalsIgnoreCase(STRING)|| - typeValue.equalsIgnoreCase(INTEGER) - ) - { - String findDefault=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+DEFAULT; - String defaultValue= map.get(findDefault); - LOGGER.info("defaultValue is:"+ defaultValue); - - String findRequired=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+REQUIRED; - String requiredValue= map.get(findRequired); - LOGGER.info("requiredValue is:"+ requiredValue); - - StringBuilder attributeIndividualStringBuilder= new StringBuilder(); - attributeIndividualStringBuilder.append(typeValue+":defaultValue-"); - attributeIndividualStringBuilder.append(defaultValue+":required-"); - attributeIndividualStringBuilder.append(requiredValue+MANYFALSE); - dataMapForJson.put(uniqueDataKey, attributeIndividualStringBuilder.toString()); - } - else if(typeValue.equalsIgnoreCase(LIST)){ - String findList= DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+".entry_schema.type"; - String listValue=map.get(findList); - if(listValue!=null){ - LOGGER.info("Type of list is:"+ listValue); - //Its userdefined - if(listValue.contains(".")){ - String trimValue=listValue.substring(listValue.lastIndexOf('.')+1); - StringBuilder referenceIndividualStringBuilder= new StringBuilder(); - referenceIndividualStringBuilder.append(trimValue+":MANY-true"); - dataMapForJson.put(uniqueDataKey, referenceIndividualStringBuilder.toString()); - }//Its string - else{ - StringBuilder stringListItems= new StringBuilder(); - stringListItems.append(uniqueDataKeySplit[1].toUpperCase()+":MANY-false"); - dataMapForJson.put(uniqueDataKey, stringListItems.toString()); - dataListBuffer.append(uniqueDataKeySplit[1].toUpperCase()+"=["); - for(int i=0;i<10;i++){ - String findConstraints= DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+".entry_schema.constraints.0.valid_values."+i; - String constraintsValue=map.get(findConstraints); - LOGGER.info(constraintsValue); - if(constraintsValue==null){ - break; - } - else{ - dataConstraints.add(constraintsValue); - dataListBuffer.append(constraintsValue+","); - } - } - dataListBuffer.append("]#"); - - LOGGER.info(dataListBuffer); - } - } - } - else{ - String findUserDefined="data_types.policy.data."+uniqueDataKeySplit[0]+"."+"properties"+"."+uniqueDataKeySplit[1]+".type"; - String userDefinedValue=map.get(findUserDefined); - String trimValue=userDefinedValue.substring(userDefinedValue.lastIndexOf('.')+1); - StringBuilder referenceIndividualStringBuilder= new StringBuilder(); - referenceIndividualStringBuilder.append(trimValue+":MANY-false"); - dataMapForJson.put(uniqueDataKey, referenceIndividualStringBuilder.toString()); - - } - } - } - return dataMapForJson; - } - - void constructJsonForDataFields(HashMap dataMapForJson){ - HashMap> dataMapKey= new HashMap <>(); - HashMap hmSub; - for(Map.Entry entry: dataMapForJson.entrySet()){ - String uniqueDataKey= entry.getKey(); - String[] uniqueDataKeySplit=uniqueDataKey.split("%"); - String value= dataMapForJson.get(uniqueDataKey); - if(dataMapKey.containsKey(uniqueDataKeySplit[0])){ - hmSub = dataMapKey.get(uniqueDataKeySplit[0]); - hmSub.put(uniqueDataKeySplit[1], value); - } - else{ - hmSub=new HashMap <>(); - hmSub.put(uniqueDataKeySplit[1], value); - } - - dataMapKey.put(uniqueDataKeySplit[0], hmSub); - } - - JSONObject mainObject= new JSONObject(); - JSONObject json; - for(Map.Entry> entry: dataMapKey.entrySet()){ - String s=entry.getKey(); - json= new JSONObject(); - HashMap jsonHm=dataMapKey.get(s); - for(Map.Entry entryMap:jsonHm.entrySet()){ - String key=entryMap.getKey(); - json.put(key, jsonHm.get(key)); - } - mainObject.put(s,json); - } - Iterator keysItr = mainObject.keys(); - while(keysItr.hasNext()) { - String key = keysItr.next(); - String value = mainObject.get(key).toString(); - retmap.put(key, value); - } - - LOGGER.info("#############################################################################"); - LOGGER.info(mainObject); - LOGGER.info("###############################################################################"); - } - - - HashMap> parsePolicyNodes(Map map){ - HashMap> mapKey= new HashMap <>(); - for(String uniqueKey: uniqueKeys){ - HashMap hm; - - for(Map.Entry entry:map.entrySet()){ - String key=entry.getKey(); - if(key.contains(uniqueKey) && key.contains("policy.nodes")){ - if(mapKey.containsKey(uniqueKey)){ - hm = mapKey.get(uniqueKey); - String keyStr= key.substring(key.lastIndexOf('.')+1); - String valueStr= map.get(key); - if(("type").equals(keyStr)){ - if(!key.contains("entry_schema")) - { - hm.put(keyStr,valueStr); - } - }else{ - hm.put(keyStr,valueStr); - } - - } else { - hm = new HashMap <>(); - String keyStr= key.substring(key.lastIndexOf('.')+1); - String valueStr= map.get(key); - if(("type").equals(keyStr)){ - if(!key.contains("entry_schema")) - { - hm.put(keyStr,valueStr); - } - }else{ - hm.put(keyStr,valueStr); - } - mapKey.put(uniqueKey, hm); - } - } - } - } - return mapKey; - } - - void createAttributes(HashMap> mapKey){ - StringBuilder attributeStringBuilder= new StringBuilder(); - StringBuilder referenceStringBuilder= new StringBuilder(); - StringBuilder listBuffer= new StringBuilder(); - List constraints= new ArrayList<>(); - for(Map.Entry> entry: mapKey.entrySet()){ - String keySetString= entry.getKey(); - HashMap keyValues=mapKey.get(keySetString); - if(keyValues.get("type").equalsIgnoreCase(STRING)|| - keyValues.get("type").equalsIgnoreCase(INTEGER) - ){ - StringBuilder attributeIndividualStringBuilder= new StringBuilder(); - attributeIndividualStringBuilder.append(keySetString+"="); - attributeIndividualStringBuilder.append(keyValues.get("type")+":defaultValue-"); - attributeIndividualStringBuilder.append(keyValues.get("default")+":required-"); - attributeIndividualStringBuilder.append(keyValues.get("required")+":MANY-false"); - attributeStringBuilder.append(attributeIndividualStringBuilder+","); - - } - else if(keyValues.get("type").equalsIgnoreCase(LIST)){ - //List Datatype - Set keys= keyValues.keySet(); - Iterator itr=keys.iterator(); - while(itr.hasNext()){ - String key= itr.next(); - if((!("type").equals(key) ||("required").equals(key))) - { - String value= keyValues.get(key); - //The "." in the value determines if its a string or a user defined type. - if (!value.contains(".")){ - //This is string - constraints.add(keyValues.get(key)); - }else{ - //This is userdefined string - String trimValue=value.substring(value.lastIndexOf('.')+1); - StringBuilder referenceIndividualStringBuilder= new StringBuilder(); - referenceIndividualStringBuilder.append(keySetString+"="+trimValue+":MANY-true"); - referenceStringBuilder.append(referenceIndividualStringBuilder+","); - } - } - } - - }else{ - //User defined Datatype. - String value=keyValues.get("type"); - String trimValue=value.substring(value.lastIndexOf('.')+1); - StringBuilder referenceIndividualStringBuilder= new StringBuilder(); - referenceIndividualStringBuilder.append(keySetString+"="+trimValue+":MANY-false"); - referenceStringBuilder.append(referenceIndividualStringBuilder+","); - - } - if(constraints!=null &&constraints.isEmpty()==false){ - //List handling. - listBuffer.append(keySetString.toUpperCase()+"=["); - for(String str:constraints){ - listBuffer.append(str+","); - } - listBuffer.append("]#"); - LOGGER.info(listBuffer); - - - StringBuilder referenceIndividualStringBuilder= new StringBuilder(); - referenceIndividualStringBuilder.append(keySetString+"="+keySetString.toUpperCase()+":MANY-false"); - referenceStringBuilder.append(referenceIndividualStringBuilder+","); - constraints.clear(); - } - } - - dataListBuffer.append(listBuffer); - - - LOGGER.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"); - LOGGER.info("Whole attribute String is:"+attributeStringBuilder); - LOGGER.info("Whole reference String is:"+referenceStringBuilder); - LOGGER.info("List String is:"+listBuffer); - LOGGER.info("Data list buffer is:"+dataListBuffer); - LOGGER.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"); - - this.listConstraints=dataListBuffer.toString(); - this.referenceAttributes=referenceStringBuilder.toString(); - this.attributeString=attributeStringBuilder.toString(); - } - - - - public void parseTosca (String fileName){ - Map map= new HashMap<>(); - - try { - map=load(fileName); - - parseDataAndPolicyNodes(map); - - HashMap dataMapForJson=parseDataNodes(map); - - constructJsonForDataFields(dataMapForJson); - - HashMap> mapKey= parsePolicyNodes(map); - - createAttributes(mapKey); - - } catch (IOException e) { - LOGGER.error(e); - } - - } - - private String cleanUPJson(String json) { - String cleanJson = StringUtils.replaceEach(json, new String[]{"\\\\", "\\\\\\", "\\\\\\\\"}, new String[]{"\\", "\\", "\\"}); - cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\\"}, new String[]{"\\"}); - cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\", "[[", "]]"}, new String[]{"\\", "[", "]"}); - - cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\"", "\\\"", "\"[{", "}]\""}, new String[]{"\"", "\"", "[{", "}]"}); - cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[{", "}]\""}, new String[]{"[{", "}]"}); - cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[", "]\""}, new String[]{"[", "]"}); - cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"{", "}\""}, new String[]{"{", "}"}); - cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\"\"", "\"\""}, new String[]{"\"", "\""}); - cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\""}, new String[]{""}); - cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\""}, new String[]{"\""}); - cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\\\\\\"}, new String[]{"\""}); - cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\\\""}, new String[]{"\""}); - cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[", "]\""}, new String[]{"[", "]"}); - return cleanJson; - } - - private JSONObject decodeContent(JsonNode jsonNode){ - Iterator jsonElements = jsonNode.elements(); - Iterator jsonKeys = jsonNode.fieldNames(); - Map element = new TreeMap<>(); - while(jsonElements.hasNext() && jsonKeys.hasNext()){ - element.put(jsonKeys.next(), jsonElements.next().toString()); - } - JSONObject jsonResult = new JSONObject(); - JSONArray jsonArray = null; - String oldValue = null; - String nodeKey = null; - String arryKey = null; - Boolean isArray = false; - JsonNodeFactory nodeFactory = JsonNodeFactory.instance; - ObjectNode node = nodeFactory.objectNode(); - String prevKey = null; - String presKey = null; - for(String key: element.keySet()){ - if(key.contains(".")){ - presKey = key.substring(0,key.indexOf(".")); - }else if(key.contains("@")){ - presKey = key.substring(0,key.indexOf("@")); - }else{ - presKey = key; - } - // first check if we are different from old. - LOGGER.info(key+"\n"); - if(jsonArray!=null && jsonArray.length()>0 && key.contains("@") && !key.contains(".") && oldValue!=null){ - if(!oldValue.equals(key.substring(0,key.indexOf("@")))){ - jsonResult.put(oldValue, jsonArray); - jsonArray = new JSONArray(); - } - }else if(jsonArray!=null && jsonArray.length()>0 && !presKey.equals(prevKey) && oldValue!=null){ - jsonResult.put(oldValue, jsonArray); - isArray = false; - jsonArray = new JSONArray(); - } - - prevKey = presKey; - // - if(key.contains(".")){ - if(nodeKey==null){ - nodeKey = key.substring(0,key.indexOf(".")); - } - if(nodeKey.equals(key.substring(0,key.indexOf(".")))){ - node.put(key.substring(key.indexOf(".")+1), element.get(key)); - }else{ - if(node.size()!=0){ - if(nodeKey.contains("@")){ - if(arryKey==null){ - arryKey = nodeKey.substring(0,nodeKey.indexOf("@")); - } - if(nodeKey.endsWith("@0")){ - isArray = true; - jsonArray = new JSONArray(); - } - if(jsonArray != null && arryKey.equals(nodeKey.substring(0,nodeKey.indexOf("@")))){ - jsonArray.put(decodeContent(node)); - } - if((key.contains("@") && !arryKey.equals(key.substring(0,nodeKey.indexOf("@")))) || !key.contains("@")){ - jsonResult.put(arryKey, jsonArray); - jsonArray = new JSONArray(); - } - arryKey = nodeKey.substring(0,nodeKey.indexOf("@")); - }else{ - isArray = false; - jsonResult.put(nodeKey, decodeContent(node)); - } - node = nodeFactory.objectNode(); - } - nodeKey = key.substring(0,key.indexOf(".")); - if(nodeKey.contains("@")){ - arryKey = nodeKey.substring(0,nodeKey.indexOf("@")); - } - node.put(key.substring(key.indexOf(".")+1), element.get(key)); - } - }else if(node.size()!=0){ - if(nodeKey.contains("@")){ - if(arryKey==null){ - arryKey = nodeKey.substring(0,nodeKey.indexOf("@")); - } - if(nodeKey.endsWith("@0")){ - isArray = true; - jsonArray = new JSONArray(); - } - if(jsonArray != null && arryKey.equals(nodeKey.substring(0,nodeKey.indexOf("@")))){ - jsonArray.put(decodeContent(node)); - } - jsonResult.put(arryKey, jsonArray); - jsonArray = new JSONArray(); - arryKey = nodeKey.substring(0,nodeKey.indexOf("@")); - }else{ - isArray = false; - jsonResult.put(nodeKey, decodeContent(node)); - } - node = nodeFactory.objectNode(); - if(key.contains("@")){ - isArray = true; - if(key.endsWith("@0")|| jsonArray==null){ - jsonArray = new JSONArray(); - } - }else if(!key.contains("@")){ - isArray = false; - } - if(isArray){ - if(oldValue==null){ - oldValue = key.substring(0,key.indexOf("@")); - } - if(oldValue!=prevKey){ - oldValue = key.substring(0,key.indexOf("@")); - } - if(oldValue.equals(key.substring(0,key.indexOf("@")))){ - jsonArray.put(element.get(key)); - }else{ - jsonResult.put(oldValue, jsonArray); - jsonArray = new JSONArray(); - } - oldValue = key.substring(0,key.indexOf("@")); - }else{ - jsonResult.put(key, element.get(key)); - } - }else{ - if(key.contains("@")){ - isArray = true; - if(key.endsWith("@0")|| jsonArray==null){ - jsonArray = new JSONArray(); - } - }else if(!key.contains("@")){ - isArray = false; - } - if(isArray){ - if(oldValue==null){ - oldValue = key.substring(0,key.indexOf("@")); - } - if(oldValue!=prevKey){ - oldValue = key.substring(0,key.indexOf("@")); - } - if(oldValue.equals(key.substring(0,key.indexOf("@")))){ - jsonArray.put(element.get(key)); - }else{ - jsonResult.put(oldValue, jsonArray); - jsonArray = new JSONArray(); - } - oldValue = key.substring(0,key.indexOf("@")); - }else{ - jsonResult.put(key, element.get(key)); - } - } - } - if(node.size()>0){ - if(nodeKey.contains("@")){ - if(jsonArray==null){ - jsonArray = new JSONArray(); - } - if(arryKey==null){ - arryKey = nodeKey.substring(0,nodeKey.indexOf("@")); - } - jsonArray.put(decodeContent(node)); - jsonResult.put(arryKey, jsonArray); - isArray = false;; - }else{ - jsonResult.put(nodeKey, decodeContent(node)); - } - } - if(isArray && jsonArray.length() > 0){ - jsonResult.put(oldValue, jsonArray); - } - return jsonResult; - } - - @RequestMapping(value={"/policyController/getDCAEMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView getDCAEMSTemplateData(HttpServletRequest request, HttpServletResponse response) throws Exception{ - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - - String value = root.get("policyData").toString().replaceAll("^\"|\"$", ""); - String servicename = value.toString().split("-v")[0]; - String version = null; - if (value.toString().contains("-v")){ - version = value.toString().split("-v")[1]; - } - MicroServiceModels returnModel = getAttributeObject(servicename, version); - - String jsonModel = createMicroSeriveJson(returnModel); - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - List list = new ArrayList<>(); - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(returnModel); - JSONObject j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + "}"); - list.add(j); - out.write(list.toString()); - return null; - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - private String createMicroSeriveJson(MicroServiceModels returnModel) { - Map attributeMap = new HashMap<>(); - Map refAttributeMap = new HashMap<>(); - String attribute = returnModel.getAttributes(); - if(attribute != null){ - attribute = attribute.trim(); - } - String refAttribute = returnModel.getRef_attributes(); - if(refAttribute != null){ - refAttribute = refAttribute.trim(); - } - String enumAttribute = returnModel.getEnumValues(); - if(enumAttribute != null){ - enumAttribute = enumAttribute.trim(); - } - if (!StringUtils.isEmpty(attribute)){ - attributeMap = convert(attribute, ","); - } - if (!StringUtils.isEmpty(refAttribute)){ - refAttributeMap = convert(refAttribute, ","); - } - - Gson gson = new Gson(); - - String subAttributes = returnModel.getSub_attributes(); - if(subAttributes != null){ - subAttributes = subAttributes.trim(); - }else{ - subAttributes = ""; - } - Map gsonObject = (Map) gson.fromJson(subAttributes, Object.class); - - JSONObject object = new JSONObject(); - JSONArray array = new JSONArray(); - - for (Entry keySet : attributeMap.entrySet()){ - array = new JSONArray(); - String value = keySet.getValue(); - if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){ - array.put(value); - object.put(keySet.getKey().trim(), array); - }else { - object.put(keySet.getKey().trim(), value.trim()); - } - } - - for (Entry keySet : refAttributeMap.entrySet()){ - array = new JSONArray(); - String value = keySet.getValue().split(":")[0]; - if (gsonObject.containsKey(value)){ - if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){ - array.put(recursiveReference(value, gsonObject, enumAttribute)); - object.put(keySet.getKey().trim(), array); - }else { - object.put(keySet.getKey().trim(), recursiveReference(value, gsonObject, enumAttribute)); - } - }else { - if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){ - array.put(value.trim()); - object.put(keySet.getKey().trim(), array); - }else { - object.put(keySet.getKey().trim(), value.trim()); - } - } - } - - return object.toString(); - } - - @SuppressWarnings("unchecked") - private JSONObject recursiveReference(String name, Map subAttributeMap, String enumAttribute) { - JSONObject object = new JSONObject(); - Map map = new HashMap<>(); - Object returnClass = subAttributeMap.get(name); - map = (Map) returnClass; - JSONArray array = new JSONArray(); - - for( Entry m:map.entrySet()){ - String[] splitValue = m.getValue().split(":"); - array = new JSONArray(); - if (subAttributeMap.containsKey(splitValue[0])){ - if (m.getValue().split("MANY-")[1].equalsIgnoreCase("true")){ - array.put(recursiveReference(splitValue[0], subAttributeMap, enumAttribute)); - object.put(m.getKey().trim(), array); - }else { - object.put(m.getKey().trim(), recursiveReference(splitValue[0], subAttributeMap, enumAttribute)); - } - } else{ - if (m.getValue().split("MANY-")[1].equalsIgnoreCase("true")){ - array.put(splitValue[0].trim()); - object.put(m.getKey().trim(), array); - }else { - object.put(m.getKey().trim(), splitValue[0].trim()); - } - } - } - - return object; - } - - - @RequestMapping(value={"/policyController/getModelServiceVersioneData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response) throws Exception{ - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - - String value = root.get("policyData").toString().replaceAll("^\"|\"$", ""); - String servicename = value.toString().split("-v")[0]; - Set returnList = getVersionList(servicename); - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - List list = new ArrayList<>(); - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(returnList); - JSONObject j = new JSONObject("{dcaeModelVersionData: " + responseString +"}"); - list.add(j); - out.write(list.toString()); - return null; - } - - private Set getVersionList(String name) { - MicroServiceModels workingModel = new MicroServiceModels(); - Set list = new HashSet<>(); - List microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name); - for (int i = 0; i < microServiceModelsData.size(); i++) { - workingModel = (MicroServiceModels) microServiceModelsData.get(i); - if (workingModel.getVersion()!=null){ - list.add(workingModel.getVersion()); - }else{ - list.add("Default"); - } - } - return list; - } - - private MicroServiceModels getAttributeObject(String name, String version) { - MicroServiceModels workingModel = new MicroServiceModels(); - List microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name); - for (int i = 0; i < microServiceModelsData.size(); i++) { - workingModel = (MicroServiceModels) microServiceModelsData.get(i); - if(version != null){ - if (workingModel.getVersion()!=null){ - if (workingModel.getVersion().equals(version)){ - return workingModel; - } - }else{ - return workingModel; - } - }else{ - return workingModel; - } - - } - return workingModel; - } - - @RequestMapping(value={"/get_DCAEPriorityValues"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getDCAEPriorityValuesData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - List priorityList = new ArrayList<>(); - priorityCount = 10; - for (int i = 1; i < priorityCount; i++) { - priorityList.add(String.valueOf(i)); - } - model.put("priorityDatas", mapper.writeValueAsString(priorityList)); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(e); - } - } - - public void prePopulateDCAEMSPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - if (policyAdapter.getPolicyData() instanceof PolicyType) { - Object policyData = policyAdapter.getPolicyData(); - PolicyType policy = (PolicyType) policyData; - policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("MS_") +3); - policyAdapter.setPolicyName(policyNameValue); - String description = ""; - try{ - description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); - }catch(Exception e){ - description = policy.getDescription(); - } - policyAdapter.setPolicyDescription(description); - // Get the target data under policy. - TargetType target = policy.getTarget(); - if (target != null) { - // Under target we have AnyOFType - List anyOfList = target.getAnyOf(); - if (anyOfList != null) { - Iterator iterAnyOf = anyOfList.iterator(); - while (iterAnyOf.hasNext()) { - AnyOfType anyOf = iterAnyOf.next(); - // Under AnyOFType we have AllOFType - List allOfList = anyOf.getAllOf(); - if (allOfList != null) { - Iterator iterAllOf = allOfList.iterator(); - while (iterAllOf.hasNext()) { - AllOfType allOf = iterAllOf.next(); - // Under AllOFType we have Match - List matchList = allOf.getMatch(); - if (matchList != null) { - Iterator iterMatch = matchList.iterator(); - while (matchList.size()>1 && iterMatch.hasNext()) { - MatchType match = iterMatch.next(); - // - // Under the match we have attribute value and - // attributeDesignator. So,finally down to the actual attribute. - // - AttributeValueType attributeValue = match.getAttributeValue(); - String value = (String) attributeValue.getContent().get(0); - AttributeDesignatorType designator = match.getAttributeDesignator(); - String attributeId = designator.getAttributeId(); - // First match in the target is EcompName, so set that value. - if (attributeId.equals("ECOMPName")) { - policyAdapter.setEcompName(value); - } - if (attributeId.equals("ConfigName")){ - policyAdapter.setConfigName(value); - } - if (attributeId.equals("uuid")){ - policyAdapter.setUuid(value); - } - if (attributeId.equals("location")){ - policyAdapter.setLocation(value); - } - if (attributeId.equals("RiskType")){ - policyAdapter.setRiskType(value); - } - if (attributeId.equals("RiskLevel")){ - policyAdapter.setRiskLevel(value); - } - if (attributeId.equals("guard")){ - policyAdapter.setGuard(value); - } - if (attributeId.equals("TTLDate") && !value.contains("NA")){ - String newDate = convertDate(value, true); - policyAdapter.setTtlDate(newDate); - } - } - readFile(policyAdapter, entity); - } - } - } - } - } - } - } - } - - private String convertDate(String dateTTL, boolean portalType) { - String formateDate = null; - String[] date = dateTTL.split("T"); - String[] parts = date[0].split("-"); - - formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; - return formateDate; - } - - public static Map convert(String str, String split) { - Map map = new HashMap<>(); - for(final String entry : str.split(split)) { - String[] parts = entry.split("="); - map.put(parts[0], parts[1]); - } - return map; - } - - - @SuppressWarnings("unchecked") - private void readFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - String policyScopeName = null; - ObjectMapper mapper = new ObjectMapper(); - try { - DCAEMicroServiceObject msBody = (DCAEMicroServiceObject) mapper.readValue(entity.getConfigurationData().getConfigBody(), DCAEMicroServiceObject.class); - policyScopeName = getPolicyScope(msBody.getPolicyScope()); - policyAdapter.setPolicyScope(policyScopeName); - - policyAdapter.setPriority(msBody.getPriority()); - - if (msBody.getVersion()!= null){ - policyAdapter.setServiceType(msBody.getService()); - policyAdapter.setVersion(msBody.getVersion()); - }else{ - policyAdapter.setServiceType(msBody.getService()); - } - if(msBody.getContent() != null){ - LinkedHashMap data = new LinkedHashMap<>(); - LinkedHashMap map = (LinkedHashMap) msBody.getContent(); - readRecursivlyJSONContent(map, data); - policyAdapter.setRuleData(data); - } - - } catch (Exception e) { - LOGGER.error(e); - } - - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - private void readRecursivlyJSONContent(LinkedHashMap map, LinkedHashMap data){ - for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) { - Object key = iterator.next(); - Object value = map.get(key); - if(value instanceof LinkedHashMap){ - LinkedHashMap secondObjec = new LinkedHashMap<>(); - readRecursivlyJSONContent((LinkedHashMap) value, secondObjec); - for(String objKey: secondObjec.keySet()){ - data.put(key+"." +objKey, secondObjec.get(objKey)); - } - }else if(value instanceof ArrayList){ - ArrayList jsonArrayVal = (ArrayList)value; - for(int i = 0; i < jsonArrayVal.size(); i++){ - Object arrayvalue = jsonArrayVal.get(i); - if(arrayvalue instanceof LinkedHashMap){ - LinkedHashMap newData = new LinkedHashMap<>(); - readRecursivlyJSONContent((LinkedHashMap) arrayvalue, newData); - for(String objKey: newData.keySet()){ - data.put(key+"@"+i+"." +objKey, newData.get(objKey)); - } - }else if(arrayvalue instanceof ArrayList){ - ArrayList jsonArrayVal1 = (ArrayList)value; - for(int j = 0; j < jsonArrayVal1.size(); j++){ - Object arrayvalue1 = jsonArrayVal1.get(i); - data.put(key+"@"+j, arrayvalue1.toString()); - } - }else{ - data.put(key+"@"+i, arrayvalue.toString()); - } - } - }else{ - data.put(key.toString(), value.toString()); - } - } - } - - private String getPolicyScope(String value) { - List groupList= commonClassDao.getDataById(GroupPolicyScopeList.class, "groupList", value); - if(groupList != null && !groupList.isEmpty()){ - GroupPolicyScopeList pScope = (GroupPolicyScopeList) groupList.get(0); - return pScope.getGroupName(); - } - return null; - } - - //Convert the map values and set into JSON body - public Map convertMap(Map attributesMap, Map attributesRefMap) { - Map attribute = new HashMap<>(); - String temp = null; - String key; - String value; - for (Entry entry : attributesMap.entrySet()) { - key = entry.getKey(); - value = entry.getValue(); - attribute.put(key, value); - } - for (Entry entryRef : attributesRefMap.entrySet()) { - key = entryRef.getKey(); - value = entryRef.getValue().toString(); - attribute.put(key, value); - } - for (Entry entryList : attributesListRefMap.entrySet()) { - key = entryList.getKey(); - value = entryList.getValue().toString(); - attribute.put(key, value); - } - for (Entry> arrayList : arrayTextList.entrySet()){ - key = arrayList.getKey(); - temp = null; - for (Object textList : arrayList.getValue()){ - if (temp == null){ - temp = "[" + textList; - }else{ - temp = temp + "," + textList; - } - } - attribute.put(key, temp+ "]"); - } - - return attribute; - } - - @RequestMapping(value={"/ms_dictionary/set_MSModelData"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public void SetMSModelData(HttpServletRequest request, HttpServletResponse response) throws Exception{ - List items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); - boolean zip = false; - boolean yml= false; - for (FileItem item : items) { - if(item.getName().endsWith(".zip") || item.getName().endsWith(".xmi")||item.getName().endsWith(".yml")){ - this.newModel = new MicroServiceModels(); - try{ - File file = new File(item.getName()); - OutputStream outputStream = new FileOutputStream(file); - IOUtils.copy(item.getInputStream(), outputStream); - outputStream.close(); - this.newFile = file.toString(); - this.newModel.setModelName(this.newFile.toString().split("-v")[0]); - - if (this.newFile.toString().contains("-v")){ - if (item.getName().endsWith(".zip")){ - this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".zip", "")); - zip = true; - }else if(item.getName().endsWith(".yml")){ - this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".yml", "")); - yml = true; - } - else { - this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".xmi", "")); - } - } - - }catch(Exception e){ - LOGGER.error("Upload error : " + e); - } - } - - } - List fileList = new ArrayList<>();; - this.directory = "model"; - if (zip){ - extractFolder(this.newFile); - fileList = listModelFiles(this.directory); - }else if (yml==true){ - parseTosca(this.newFile); - }else { - File file = new File(this.newFile); - fileList.add(file); - } - String modelType= ""; - if(yml==false){ - modelType="xmi"; - //Process Main Model file first - classMap = new HashMap<>(); - for (File file : fileList) { - if(!file.isDirectory() && file.getName().endsWith(".xmi")){ - retreiveDependency(file.toString(), true); - } - } - - modelList = createList(); - - cleanUp(this.newFile); - cleanUp(directory); - }else{ - modelType="yml"; - modelList.add(this.newModel.getModelName()); - String className=this.newModel.getModelName(); - MSAttributeObject msAttributes= new MSAttributeObject(); - msAttributes.setClassName(className); - - HashMap returnAttributeList =new HashMap<>(); - returnAttributeList.put(className, this.attributeString); - msAttributes.setAttribute(returnAttributeList); - - msAttributes.setSubClass(this.retmap); - - HashMap returnReferenceList =new HashMap<>(); - //String[] referenceArray=this.referenceAttributes.split("="); - returnReferenceList.put(className, this.referenceAttributes); - msAttributes.setRefAttribute(returnReferenceList); - - if(this.listConstraints!=""){ - HashMap enumList =new HashMap<>(); - String[] listArray=this.listConstraints.split("#"); - for(String str:listArray){ - String[] strArr= str.split("="); - if(strArr.length>1){ - enumList.put(strArr[0], strArr[1]); - } - } - msAttributes.setEnumType(enumList); - } - - classMap=new HashMap<>(); - classMap.put(className, msAttributes); - - } - - PrintWriter out = response.getWriter(); - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - ObjectMapper mapper = new ObjectMapper(); - JSONObject j = new JSONObject(); - j.put("classListDatas", modelList); - j.put("modelDatas", mapper.writeValueAsString(classMap)); - j.put("modelType", modelType); - out.write(j.toString()); - } - - /* - * Unzip file and store in the model directory for processing - */ - @SuppressWarnings("rawtypes") - private void extractFolder(String zipFile ) { - int BUFFER = 2048; - File file = new File(zipFile); - - ZipFile zip = null; - try { - zip = new ZipFile(file); - String newPath = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4); - this.directory = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4); - checkZipDirectory(this.directory); - new File(newPath).mkdir(); - Enumeration zipFileEntries = zip.entries(); - - // Process each entry - while (zipFileEntries.hasMoreElements()){ - // grab a zip file entry - ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); - String currentEntry = entry.getName(); - File destFile = new File("model" + File.separator + currentEntry); - File destinationParent = destFile.getParentFile(); - - destinationParent.mkdirs(); - - if (!entry.isDirectory()){ - BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry)); - int currentByte; - byte data[] = new byte[BUFFER]; - FileOutputStream fos = new FileOutputStream(destFile); - BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER); - while ((currentByte = is.read(data, 0, BUFFER)) != -1) { - dest.write(data, 0, currentByte); - } - dest.flush(); - dest.close(); - is.close(); - } - - if (currentEntry.endsWith(".zip")){ - extractFolder(destFile.getAbsolutePath()); - } - } - } catch (IOException e) { - LOGGER.error("Failed to unzip model file " + zipFile); - }finally{ - try { - if(zip != null) - zip.close(); - } catch (IOException e) { - LOGGER.error("Exception Occured While closing zipfile " + e); - } - } - } - - private void retreiveDependency(String workingFile, Boolean modelClass) { - - MSModelUtils utils = new MSModelUtils(PolicyController.getMsEcompName(), PolicyController.getMsPolicyName()); - HashMap tempMap = new HashMap<>(); - - tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI); - - classMap.putAll(tempMap); - LOGGER.info(tempMap); - - return; - - } - - private List listModelFiles(String directoryName) { - File directory = new File(directoryName); - List resultList = new ArrayList<>(); - File[] fList = directory.listFiles(); - for (File file : fList) { - if (file.isFile()) { - resultList.add(file); - } else if (file.isDirectory()) { - dirDependencyList.add(file.getName()); - resultList.addAll(listModelFiles(file.getAbsolutePath())); - } - } - return resultList; - } - - private void cleanUp(String path) { - if (path!=null){ - try { - FileUtils.forceDelete(new File(path)); - } catch (IOException e) { - LOGGER.error("Failed to delete folder " + path); - } - } - } - - private void checkZipDirectory(String zipDirectory) { - Path path = Paths.get(zipDirectory); - - if (Files.exists(path)) { - cleanUp(zipDirectory); - } - } - - private List createList() { - List list = new ArrayList<>(); - for (Entry cMap : classMap.entrySet()){ - if (cMap.getValue().isPolicyTempalate()){ - list.add(cMap.getKey()); - } - - } - - if (list.isEmpty()){ - if (classMap.containsKey(this.newModel.getModelName())){ - list.add(this.newModel.getModelName()); - }else { - list.add("EMPTY"); - } - } - return list; - } - - public Map getAttributesListRefMap() { - return attributesListRefMap; - } - - public Map> getArrayTextList() { - return arrayTextList; - } - -} - -class DCAEMicroServiceObject { - - private String service; - private String location; - private String uuid; - private String policyName; - private String description; - private String configName; - private String templateVersion; - private String version; - private String priority; - private String policyScope; - private String riskType; - private String riskLevel; - private String guard = null; - - public String getGuard() { - return guard; - } - public void setGuard(String guard) { - this.guard = guard; - } - public String getRiskType() { - return riskType; - } - public void setRiskType(String riskType) { - this.riskType = riskType; - } - public String getRiskLevel() { - return riskLevel; - } - public void setRiskLevel(String riskLevel) { - this.riskLevel = riskLevel; - } - public String getPolicyScope() { - return policyScope; - } - public void setPolicyScope(String policyScope) { - this.policyScope = policyScope; - } - - public String getPriority() { - return priority; - } - public void setPriority(String priority) { - this.priority = priority; - } - public String getVersion() { - return version; - } - public void setVersion(String version) { - this.version = version; - } - private Object content; - - - public String getPolicyName() { - return policyName; - } - public void setPolicyName(String policyName) { - this.policyName = policyName; - } - public String getDescription() { - return description; - } - public void setDescription(String description) { - this.description = description; - } - public String getConfigName() { - return configName; - } - public void setConfigName(String configName) { - this.configName = configName; - } - public Object getContent() { - return content; - } - public void setContent(Object content) { - this.content = content; - } - - public String getService() { - return service; - } - public void setService(String service) { - this.service = service; - } - public String getLocation() { - return location; - } - public void setLocation(String location) { - this.location = location; - } - - public String getUuid() { - return uuid; - } - public void setUuid(String uuid) { - this.uuid = uuid; - } - public String getTemplateVersion() { - return templateVersion; - } - public void setTemplateVersion(String templateVersion) { - this.templateVersion = templateVersion; - } - -} \ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateFirewallController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateFirewallController.java deleted file mode 100644 index 2232da608..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateFirewallController.java +++ /dev/null @@ -1,929 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.controller; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.hibernate.SessionFactory; -import org.json.JSONObject; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.rest.adapter.AddressGroupJson; -import org.openecomp.policy.rest.adapter.AddressJson; -import org.openecomp.policy.rest.adapter.AddressMembers; -import org.openecomp.policy.rest.adapter.DeployNowJson; -import org.openecomp.policy.rest.adapter.IdMap; -import org.openecomp.policy.rest.adapter.PolicyRestAdapter; -import org.openecomp.policy.rest.adapter.PrefixIPList; -import org.openecomp.policy.rest.adapter.ServiceGroupJson; -import org.openecomp.policy.rest.adapter.ServiceListJson; -import org.openecomp.policy.rest.adapter.ServiceMembers; -import org.openecomp.policy.rest.adapter.ServicesJson; -import org.openecomp.policy.rest.adapter.TagDefines; -import org.openecomp.policy.rest.adapter.Tags; -import org.openecomp.policy.rest.adapter.Term; -import org.openecomp.policy.rest.adapter.TermCollector; -import org.openecomp.policy.rest.adapter.VendorSpecificData; -import org.openecomp.policy.rest.dao.CommonClassDao; -import org.openecomp.policy.rest.jpa.AddressGroup; -import org.openecomp.policy.rest.jpa.FWTagPicker; -import org.openecomp.policy.rest.jpa.GroupServiceList; -import org.openecomp.policy.rest.jpa.PolicyEntity; -import org.openecomp.policy.rest.jpa.PrefixList; -import org.openecomp.policy.rest.jpa.SecurityZone; -import org.openecomp.policy.rest.jpa.ServiceList; -import org.openecomp.policy.rest.jpa.TermList; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.openecomp.portalsdk.core.controller.RestrictedBaseController; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; - -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectWriter; - -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; - -@Controller -@RequestMapping("/") -public class CreateFirewallController extends RestrictedBaseController { - private static Logger policyLogger = FlexLogger.getLogger(CreateFirewallController.class); - - @Autowired - SessionFactory sessionFactory; - - private static CommonClassDao commonClassDao; - - private List tagCollectorList; - private String jsonBody; - List expandablePrefixIPList = new ArrayList<>(); - List expandableServicesList= new ArrayList<>(); - @Autowired - private CreateFirewallController(CommonClassDao commonClassDao){ - CreateFirewallController.commonClassDao = commonClassDao; - } - - public CreateFirewallController(){} - private List termCollectorList; - private ArrayList attributeList; - - - public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData){ - - termCollectorList = new ArrayList<>(); - tagCollectorList = new ArrayList<>(); - if(!policyData.getAttributes().isEmpty()){ - for(Object attribute : policyData.getAttributes()){ - if(attribute instanceof LinkedHashMap){ - String key = ((LinkedHashMap) attribute).get("key").toString(); - termCollectorList.add(key); - - String tag = ((LinkedHashMap) attribute).get("value").toString(); - tagCollectorList.add(tag); - } - } - } - jsonBody = constructJson(policyData); - if (jsonBody != null && !jsonBody.equalsIgnoreCase("")) { - policyData.setJsonBody(jsonBody); - } else { - policyData.setJsonBody("{}"); - } - policyData.setJsonBody(jsonBody); - - return policyData; - } - - private List mapping(String expandableList) { - List valueDesc= new ArrayList<>(); - List prefixListData = commonClassDao.getData(PrefixList.class); - for (int i = 0; i< prefixListData.size(); i++) { - PrefixList prefixList = (PrefixList) prefixListData.get(i); - if (prefixList.getPrefixListName().equals(expandableList)) { - String value = prefixList.getPrefixListValue(); - valueDesc.add(value); - String desc= prefixList.getDescription(); - valueDesc.add(desc); - break; - } - } - return valueDesc; - } - - private ServiceList mappingServiceList(String expandableList) { - ServiceList serviceList=null; - List serviceListData = commonClassDao.getData(ServiceList.class); - for (int i = 0; i< serviceListData.size(); i++) { - serviceList = (ServiceList) serviceListData.get(i); - if (serviceList.getServiceName().equals(expandableList)) { - break; - } - } - return serviceList; - } - - private GroupServiceList mappingServiceGroup(String expandableList) { - - GroupServiceList serviceGroup=null; - List serviceGroupData = commonClassDao.getData(GroupServiceList.class); - for (int i = 0; i< serviceGroupData.size(); i++) { - serviceGroup = (GroupServiceList) serviceGroupData.get(i); - if (serviceGroup.getGroupName().equals(expandableList)) { - break; - } - } - return serviceGroup; - } - - private AddressGroup mappingAddressGroup(String expandableList) { - - AddressGroup addressGroup=null; - List addressGroupData = commonClassDao.getData(AddressGroup.class); - for (int i = 0; i< addressGroupData.size(); i++) { - addressGroup = (AddressGroup) addressGroupData.get(i); - if (addressGroup.getGroupName().equals(expandableList)) { - break; - } - } - return addressGroup; - } - - public void prePopulateFWPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - attributeList = new ArrayList<>(); - if (policyAdapter.getPolicyData() instanceof PolicyType) { - Object policyData = policyAdapter.getPolicyData(); - PolicyType policy = (PolicyType) policyData; - // policy name value is the policy name without any prefix and Extensions. - policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("FW_") +3); - if (policyLogger.isDebugEnabled()) { - policyLogger.debug("Prepopulating form data for Config Policy selected:"+ policyAdapter.getPolicyName()); - } - policyAdapter.setPolicyName(policyNameValue); - String description = ""; - try{ - description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); - }catch(Exception e){ - policyLogger.info("General error", e); - description = policy.getDescription(); - } - policyAdapter.setPolicyDescription(description); - - ObjectMapper mapper = new ObjectMapper(); - - TermCollector tc1=null; - try { - //Json conversion. - String data=null; - SecurityZone jpaSecurityZone; - data = entity.getConfigurationData().getConfigBody(); - tc1 = (TermCollector)mapper.readValue(data, TermCollector.class); - List securityZoneData = commonClassDao.getData(SecurityZone.class); - for (int i = 0; i < securityZoneData.size() ; i++) { - jpaSecurityZone = (SecurityZone) securityZoneData.get(i); - if (jpaSecurityZone.getZoneValue().equals(tc1.getSecurityZoneId())){ - policyAdapter.setSecurityZone(jpaSecurityZone.getZoneName()); - break; - } - } - } - catch(Exception e) { - policyLogger.error("Exception Caused while Retriving the JSON body data" +e); - } - - Map termTagMap=null; - if(tc1 != null){ - for(int i=0;i(); - String ruleName= tc1.getFirewallRuleList().get(i).getRuleName(); - String tagPickerName=tc1.getRuleToTag().get(i).getTagPickerName(); - termTagMap.put("key", ruleName); - termTagMap.put("value", tagPickerName); - attributeList.add(termTagMap); - } - } - policyAdapter.setAttributes(attributeList); - // Get the target data under policy. - TargetType target = policy.getTarget(); - if (target != null) { - // Under target we have AnyOFType - List anyOfList = target.getAnyOf(); - if (anyOfList != null) { - Iterator iterAnyOf = anyOfList.iterator(); - while (iterAnyOf.hasNext()) { - AnyOfType anyOf = iterAnyOf.next(); - // Under AnyOFType we have AllOFType - List allOfList = anyOf.getAllOf(); - if (allOfList != null) { - Iterator iterAllOf = allOfList.iterator(); - while (iterAllOf.hasNext()) { - AllOfType allOf = iterAllOf.next(); - // Under AllOFType we have Match - List matchList = allOf.getMatch(); - if (matchList != null) { - - Iterator iterMatch = matchList.iterator(); - while (iterMatch.hasNext()) { - MatchType match = iterMatch.next(); - // - // Under the match we have attribute value and - // attributeDesignator. So,finally down to the actual attribute. - // - AttributeValueType attributeValue = match.getAttributeValue(); - String value = (String) attributeValue.getContent().get(0); - AttributeDesignatorType designator = match.getAttributeDesignator(); - String attributeId = designator.getAttributeId(); - if (attributeId.equals("ConfigName")) { - policyAdapter.setConfigName(value); - } - if (attributeId.equals("RiskType")){ - policyAdapter.setRiskType(value); - } - if (attributeId.equals("RiskLevel")){ - policyAdapter.setRiskLevel(value); - } - if (attributeId.equals("guard")){ - policyAdapter.setGuard(value); - } - if (attributeId.equals("TTLDate") && !value.contains("NA")){ - String newDate = convertDate(value, true); - policyAdapter.setTtlDate(newDate); - } - } - } - } - } - } - } - } - } - } - - private String convertDate(String dateTTL, boolean portalType) { - String formateDate = null; - String[] date; - String[] parts; - - if (portalType){ - parts = dateTTL.split("-"); - formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z"; - } else { - date = dateTTL.split("T"); - parts = date[0].split("-"); - formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; - } - return formateDate; - } - - @RequestMapping(value={"/policyController/ViewFWPolicyRule.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public void setFWViewRule(HttpServletRequest request, HttpServletResponse response){ - try { - termCollectorList = new ArrayList<>(); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - PolicyRestAdapter policyData = (PolicyRestAdapter)mapper.readValue(root.get("policyData").toString(), PolicyRestAdapter.class); - if(!policyData.getAttributes().isEmpty()){ - for(Object attribute : policyData.getAttributes()){ - if(attribute instanceof LinkedHashMap){ - String key = ((LinkedHashMap) attribute).get("key").toString(); - termCollectorList.add(key); - } - } - } - TermList jpaTermList; - String ruleSrcList=null; - String ruleDestList=null; - String ruleSrcPort=null; - String ruleDestPort=null; - String ruleAction=null; - List valueDesc= new ArrayList<>(); - StringBuffer displayString = new StringBuffer(); - for (String id : termCollectorList) { - List tmList = commonClassDao.getDataById(TermList.class, "termName", id); - jpaTermList = (TermList) tmList.get(0); - if (jpaTermList != null){ - ruleSrcList= ((TermList) jpaTermList).getSrcIPList(); - if ((ruleSrcList!= null) && (!ruleSrcList.isEmpty()) && !ruleSrcList.equals("null")){ - displayString.append("Source IP List: " + ((TermList) jpaTermList).getSrcIPList()); - displayString.append(" ; \t\n"); - for(String srcList:ruleSrcList.split(",")){ - if(srcList.startsWith("Group_")){ - AddressGroup ag= new AddressGroup(); - ag= mappingAddressGroup(srcList); - displayString.append("\n\t"+"Group has :"+ag.getPrefixList()+"\n"); - for(String groupItems:ag.getPrefixList().split(",")){ - valueDesc=mapping(groupItems); - displayString.append("\n\t"+"Name: "+groupItems); - if(!valueDesc.isEmpty()){ - displayString.append("\n\t"+"Description: "+valueDesc.get(1)); - displayString.append("\n\t"+"Value: "+valueDesc.get(0)); - } - displayString.append("\n"); - } - }else{ - if(!srcList.equals("ANY")){ - valueDesc=mapping(srcList); - displayString.append("\n\t"+"Name: "+srcList); - displayString.append("\n\t"+"Description: "+valueDesc.get(1)); - displayString.append("\n\t"+"Value: "+valueDesc.get(0)); - displayString.append("\n"); - } - } - } - displayString.append("\n"); - } - ruleDestList= ((TermList) jpaTermList).getDestIPList(); - if ( ruleDestList!= null && (!ruleDestList.isEmpty())&& !ruleDestList.equals("null")){ - displayString.append("Destination IP List: " + ((TermList) jpaTermList).getDestIPList()); - displayString.append(" ; \t\n"); - for(String destList:ruleDestList.split(",")){ - if(destList.startsWith("Group_")){ - AddressGroup ag= new AddressGroup(); - ag= mappingAddressGroup(destList); - displayString.append("\n\t"+"Group has :"+ag.getPrefixList()+"\n"); - for(String groupItems:ag.getPrefixList().split(",")){ - valueDesc=mapping(groupItems); - displayString.append("\n\t"+"Name: "+groupItems); - displayString.append("\n\t"+"Description: "+valueDesc.get(1)); - displayString.append("\n\t"+"Value: "+valueDesc.get(0)); - displayString.append("\n\t"); - } - }else{ - if(!destList.equals("ANY")){ - valueDesc=mapping(destList); - displayString.append("\n\t"+"Name: "+destList); - displayString.append("\n\t"+"Description: "+valueDesc.get(1)); - displayString.append("\n\t"+"Value: "+valueDesc.get(0)); - displayString.append("\n\t"); - } - } - } - displayString.append("\n"); - } - - ruleSrcPort=((TermList) jpaTermList).getSrcPortList(); - if ( ruleSrcPort!= null && (!ruleSrcPort.isEmpty())&& !ruleSrcPort.equals("null")) { - displayString.append("\n"+"Source Port List:" - + ruleSrcPort); - displayString.append(" ; \t\n"); - } - - ruleDestPort= ((TermList) jpaTermList).getDestPortList(); - if (ruleDestPort != null && (!ruleDestPort.isEmpty())&& !ruleDestPort.equals("null")) { - displayString.append("\n"+"Destination Port List:" - + ruleDestPort); - displayString.append(" ; \t\n"); - for(String destServices:ruleDestPort.split(",")){ - if(destServices.startsWith("Group_")){ - GroupServiceList sg= new GroupServiceList(); - sg= mappingServiceGroup(destServices); - displayString.append("\n\t"+"Service Group has :"+sg.getServiceList()+"\n"); - for(String groupItems:sg.getServiceList().split(",")){ - ServiceList sl= new ServiceList(); - sl= mappingServiceList(groupItems); - displayString.append("\n\t"+"Name: "+ - sl.getServiceName()); - displayString.append("\n\t"+"Description: "+ - sl.getServiceDescription()); - displayString.append("\n\t"+"Transport-Protocol: "+ - sl.getServiceTransProtocol()); - displayString.append("\n\t"+"Ports: "+ - sl.getServicePorts()); - displayString.append("\n"); - } - } - else{ - if(!destServices.equals("ANY")){ - ServiceList sl= new ServiceList(); - sl= mappingServiceList(destServices); - displayString.append("\n\t"+"Name: "+ - sl.getServiceName()); - displayString.append("\n\t"+"Description: "+ - sl.getServiceDescription()); - displayString.append("\n\t"+"Transport-Protocol: "+ - sl.getServiceTransProtocol()); - displayString.append("\n\t"+"Ports: "+ - sl.getServicePorts()); - displayString.append("\n"); - } - } - } - displayString.append("\n"); - } - - ruleAction=(jpaTermList).getAction(); - if ( ruleAction!= null && (!ruleAction.isEmpty())) { - displayString.append("\n"+"Action List:" - + ruleAction); - displayString.append(" ; \t\n"); - } - } - } - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(displayString); - JSONObject j = new JSONObject("{policyData: " + responseString + "}"); - out.write(j.toString()); - } catch (Exception e) { - policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } - - private String constructJson(PolicyRestAdapter policyData) { - int ruleCount=1; - //Maps to assosciate the values read from the TermList dictionary - Map srcIP_map =null; - Map destIP_map=null; - Map srcPort_map =null; - Map destPort_map =null; - Map action_map=null; - Map fromZone_map=null; - Map toZone_map=null; - - String ruleDesc=null; - String ruleFromZone=null; - String ruleToZone=null; - String ruleSrcPrefixList=null; - String ruleDestPrefixList=null; - String ruleSrcPort=null; - String ruleDestPort=null; - String ruleAction=null; - - String json = null; - - - List expandableList = new ArrayList<>(); - TermList jpaTermList; - TermCollector tc = new TermCollector(); - SecurityZone jpaSecurityZone; - List termList = new ArrayList<>(); - - Tags tags=null; - ListtagsList= new ArrayList<>(); - - TagDefines tagDefine= new TagDefines(); - List tagList=null; - ServiceListJson targetSl=null; - int i=0; - try{ - String networkRole=""; - for(String tag:tagCollectorList){ - tags= new Tags(); - List tagListData = commonClassDao.getData(FWTagPicker.class); - for(int tagCounter=0; tagCounter(); - for(String val:tagValues.split("#")) { - int index=val.indexOf(":"); - String keyToStore=val.substring(0,index); - String valueToStore=val.substring(index+1,val.length()); - - tagDefine= new TagDefines(); - tagDefine.setKey(keyToStore); - tagDefine.setValue(valueToStore); - //Add to the collection. - tagList.add(tagDefine); - - } - networkRole=jpaTagPickerList.getNetworkRole(); - break; - } - } - tags.setTags(tagList); - tags.setTagPickerName(tag); - tags.setRuleName(termCollectorList.get(i)); - tags.setNetworkRole(networkRole); - tagsList.add(tags); - i++; - } - tc.setRuleToTag(tagsList); - - for (int tl = 0 ; tl< termCollectorList.size(); tl++) { - expandableList.add(termCollectorList.get(tl)); - Term targetTerm = new Term(); - //targetSl= new ServiceListJson(); - targetTerm.setRuleName(termCollectorList.get(tl)); - List termListData = commonClassDao.getData(TermList.class); - for (int j =0; j < termListData.size(); j++) { - jpaTermList = (TermList) termListData.get(j); - if (jpaTermList.getTermName().equals(termCollectorList.get(tl))){ - ruleDesc=jpaTermList.getTermDescription(); - if ((ruleDesc!=null)&& (!ruleDesc.isEmpty())){ - targetTerm.setDescription(ruleDesc); - } - ruleFromZone=jpaTermList.getFromZone(); - - if ((ruleFromZone != null) && (!ruleFromZone.isEmpty())){ - fromZone_map = new HashMap<>(); - fromZone_map.put(tl, ruleFromZone); - } - ruleToZone=jpaTermList.getToZone(); - - if ((ruleToZone != null) && (!ruleToZone.isEmpty())){ - toZone_map = new HashMap<>(); - toZone_map.put(tl, ruleToZone); - } - ruleSrcPrefixList=jpaTermList.getSrcIPList(); - - if ((ruleSrcPrefixList != null) && (!ruleSrcPrefixList.isEmpty())){ - srcIP_map = new HashMap<>(); - srcIP_map.put(tl, ruleSrcPrefixList); - } - - ruleDestPrefixList= jpaTermList.getDestIPList(); - if ((ruleDestPrefixList != null) && (!ruleDestPrefixList.isEmpty())){ - destIP_map = new HashMap<>(); - destIP_map.put(tl, ruleDestPrefixList); - } - - ruleSrcPort=jpaTermList.getSrcPortList(); - - if (ruleSrcPort != null && (!ruleSrcPort.isEmpty())){ - srcPort_map = new HashMap<>(); - srcPort_map.put(tl, ruleSrcPort); - } - - ruleDestPort= jpaTermList.getDestPortList(); - - if (ruleDestPort!= null && (!jpaTermList.getDestPortList().isEmpty())){ - destPort_map = new HashMap<>(); - destPort_map.put(tl, ruleDestPort); - } - - ruleAction=jpaTermList.getAction(); - - if (( ruleAction!= null) && (!ruleAction.isEmpty())){ - action_map = new HashMap<>(); - action_map.put(tl, ruleAction); - } - } - } - targetTerm.setEnabled(true); - targetTerm.setLog(true); - targetTerm.setNegateSource(false); - targetTerm.setNegateDestination(false); - - if(action_map!=null){ - targetTerm.setAction(action_map.get(tl)); - } - - //FromZone arrays - if(fromZone_map!=null){ - List fromZone= new ArrayList<>(); - for(String fromZoneStr:fromZone_map.get(tl).split(",") ){ - fromZone.add(fromZoneStr); - } - targetTerm.setFromZones(fromZone); - } - - //ToZone arrays - if(toZone_map!=null){ - List toZone= new ArrayList<>(); - for(String toZoneStr:toZone_map.get(tl).split(",") ){ - toZone.add(toZoneStr); - } - targetTerm.setToZones(toZone); - } - - //Destination Services. - if(destPort_map!=null){ - Set destServicesJsonList= new HashSet<>(); - for(String destServices:destPort_map.get(tl).split(",") ){ - ServicesJson destServicesJson= new ServicesJson(); - destServicesJson.setType("REFERENCE"); - if(destServices.equals("ANY")){ - destServicesJson.setName("any"); - destServicesJsonList.add(destServicesJson); - break; - }else{ - if(destServices.startsWith("Group_")){ - destServicesJson.setName(destServices.substring(6,destServices.length())); - } else{ - destServicesJson.setName(destServices); - } - destServicesJsonList.add(destServicesJson); - } - } - targetTerm.setDestServices(destServicesJsonList); - } - //ExpandableServicesList - if((srcPort_map!=null) && (destPort_map!=null)){ - String servicesCollateString = (srcPort_map.get(tl) + "," + destPort_map.get(tl)); - expandableServicesList.add(servicesCollateString); - }else if (srcPort_map!=null){ - expandableServicesList.add(srcPort_map.get(tl)); - }else if (destPort_map!=null){ - expandableServicesList.add(destPort_map.get(tl)); - } - - if(srcIP_map!=null){ - //Source List - List sourceListArrayJson= new ArrayList<>(); - for(String srcList:srcIP_map.get(tl).split(",") ){ - AddressJson srcListJson= new AddressJson(); - if(srcList.equals("ANY")){ - srcListJson.setType("any"); - sourceListArrayJson.add(srcListJson); - break; - }else{ - srcListJson.setType("REFERENCE"); - if(srcList.startsWith("Group_")){ - srcListJson.setName(srcList.substring(6,srcList.length())); - }else{ - srcListJson.setName(srcList); - } - sourceListArrayJson.add(srcListJson); - } - } - targetTerm.setSourceList(sourceListArrayJson); - } - if(destIP_map!=null){ - //Destination List - List destListArrayJson= new ArrayList<>(); - for(String destList:destIP_map.get(tl).split(",")){ - AddressJson destListJson= new AddressJson(); - if(destList.equals("ANY")){ - destListJson.setType("any"); - destListArrayJson.add(destListJson); - break; - }else{ - destListJson.setType("REFERENCE"); - if(destList.startsWith("Group_")){ - destListJson.setName(destList.substring(6,destList.length())); - }else{ - destListJson.setName(destList); - } - destListArrayJson.add(destListJson); - } - } - targetTerm.setDestinationList(destListArrayJson); - } - //ExpandablePrefixIPList - if ((srcIP_map!=null) && (destIP_map!=null)) - { - String collateString = (srcIP_map.get(tl) + "," + destIP_map - .get(tl)); - expandablePrefixIPList.add(collateString); - } - else if(srcIP_map!=null){ - expandablePrefixIPList.add(srcIP_map.get(tl)); - } - else if(destIP_map!=null){ - expandablePrefixIPList.add(destIP_map.get(tl)); - } - termList.add(targetTerm); - targetTerm.setPosition("" + (ruleCount++)); - } - - List securityZoneData = commonClassDao.getData(SecurityZone.class); - for (int j =0 ; j< securityZoneData.size() ; j++){ - jpaSecurityZone = (SecurityZone) securityZoneData.get(j); - if (jpaSecurityZone.getZoneName().equals(policyData.getSecurityZone())){ - tc.setSecurityZoneId(jpaSecurityZone.getZoneValue()); - IdMap idMapInstance= new IdMap(); - idMapInstance.setAstraId(jpaSecurityZone.getZoneValue()); - idMapInstance.setVendorId("deviceGroup:dev"); - - List idMap = new ArrayList(); - idMap.add(idMapInstance); - - VendorSpecificData vendorStructure= new VendorSpecificData(); - vendorStructure.setIdMap(idMap); - tc.setVendorSpecificData(vendorStructure); - break; - } - } - - tc.setServiceTypeId("/v0/firewall/pan"); - tc.setConfigName(policyData.getConfigName()); - tc.setVendorServiceId("vipr"); - - DeployNowJson deployNow= new DeployNowJson(); - deployNow.setDeployNow(false); - - tc.setDeploymentOption(deployNow); - - Set servListArray = new HashSet<>(); - Set servGroupArray= new HashSet<>(); - Set addrGroupArray= new HashSet<>(); - - ServiceGroupJson targetSg= null; - AddressGroupJson addressSg=null; - ServiceListJson targetAny= null; - ServiceListJson targetAnyTcp=null; - ServiceListJson targetAnyUdp=null; - - for(String serviceList:expandableServicesList){ - for(String t: serviceList.split(",")){ - if((!t.startsWith("Group_"))){ - if(!t.equals("ANY")){ - ServiceList sl = new ServiceList(); - targetSl= new ServiceListJson(); - sl= mappingServiceList(t); - targetSl.setName(sl.getServiceName()); - targetSl.setDescription(sl.getServiceDescription()); - targetSl.setTransportProtocol(sl.getServiceTransProtocol()); - targetSl.setType(sl.getServiceType()); - targetSl.setPorts(sl.getServicePorts()); - servListArray.add(targetSl); - }else{ - //Any for destinationServices. - //Add names any, any-tcp, any-udp to the serviceGroup object. - targetAny= new ServiceListJson(); - targetAny.setName("any"); - targetAny.setType("SERVICE"); - targetAny.setTransportProtocol("any"); - targetAny.setPorts("any"); - - servListArray.add(targetAny); - - targetAnyTcp= new ServiceListJson(); - targetAnyTcp.setName("any-tcp"); - targetAnyTcp.setType("SERVICE"); - targetAnyTcp.setTransportProtocol("tcp"); - targetAnyTcp.setPorts("any"); - - servListArray.add(targetAnyTcp); - - targetAnyUdp= new ServiceListJson(); - targetAnyUdp.setName("any-udp"); - targetAnyUdp.setType("SERVICE"); - targetAnyUdp.setTransportProtocol("udp"); - targetAnyUdp.setPorts("any"); - - servListArray.add(targetAnyUdp); - } - }else{//This is a group - GroupServiceList sg= new GroupServiceList(); - targetSg= new ServiceGroupJson(); - sg= mappingServiceGroup(t); - - String name=sg.getGroupName(); - //Removing the "Group_" prepending string before packing the JSON - targetSg.setName(name.substring(6,name.length())); - List servMembersList= new ArrayList<>(); - - for(String groupString: sg.getServiceList().split(",")){ - ServiceMembers serviceMembers= new ServiceMembers(); - serviceMembers.setType("REFERENCE"); - serviceMembers.setName(groupString); - servMembersList.add(serviceMembers); - //Expand the group Name - ServiceList expandGroupSl = new ServiceList(); - targetSl= new ServiceListJson(); - expandGroupSl= mappingServiceList(groupString); - - targetSl.setName(expandGroupSl.getServiceName()); - targetSl.setDescription(expandGroupSl.getServiceDescription()); - targetSl.setTransportProtocol(expandGroupSl.getServiceTransProtocol()); - targetSl.setType(expandGroupSl.getServiceType()); - targetSl.setPorts(expandGroupSl.getServicePorts()); - servListArray.add(targetSl); - } - - targetSg.setMembers(servMembersList); - servGroupArray.add(targetSg); - - } - } - } - - Set prefixIPList = new HashSet<>(); - for(String prefixList:expandablePrefixIPList){ - for(String prefixIP: prefixList.split(",")){ - if((!prefixIP.startsWith("Group_"))){ - if(!prefixIP.equals("ANY")){ - List addMembersList= new ArrayList<>(); - List valueDesc= new ArrayList<>(); - PrefixIPList targetAddressList = new PrefixIPList(); - AddressMembers addressMembers= new AddressMembers(); - targetAddressList.setName(prefixIP); - policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "PrefixList value:"+prefixIP); - valueDesc = mapping(prefixIP); - if(!valueDesc.isEmpty()){ - policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "PrefixList description:"+valueDesc.get(1)); - targetAddressList.setDescription(valueDesc.get(1)); - } - - - addressMembers.setType("SUBNET"); - if(!valueDesc.isEmpty()) { - addressMembers.setValue(valueDesc.get(0)); - } - - addMembersList.add(addressMembers); - - targetAddressList.setMembers(addMembersList); - prefixIPList.add(targetAddressList); - } - } - else{//This is a group - AddressGroup ag= new AddressGroup(); - addressSg= new AddressGroupJson(); - ag= mappingAddressGroup(prefixIP); - - String name=ag.getGroupName(); - //Removing the "Group_" prepending string before packing the JSON - addressSg.setName(name.substring(6,name.length())); - - List addrMembersList= new ArrayList<>(); - for(String groupString: ag.getPrefixList().split(",")){ - List valueDesc= new ArrayList<>(); - AddressMembers addressMembers= new AddressMembers(); - valueDesc= mapping (groupString); - if(valueDesc.size() > 0){ - addressMembers.setValue(valueDesc.get(0)); - } - addressMembers.setType("SUBNET"); - addrMembersList.add(addressMembers); - //Expand the group Name - } - addressSg.setMembers(addrMembersList); - addrGroupArray.add(addressSg); - } - - - } - } - - Set serviceGroup= new HashSet<>(); - - for(Object obj1:servGroupArray){ - serviceGroup.add(obj1); - } - - for(Object obj:servListArray){ - serviceGroup.add(obj); - } - - Set addressGroup= new HashSet<>(); - - for(Object addObj:prefixIPList){ - addressGroup.add(addObj); - } - - for(Object addObj1:addrGroupArray){ - addressGroup.add(addObj1); - } - - tc.setServiceGroups(serviceGroup); - tc.setAddressGroups(addressGroup); - tc.setFirewallRuleList(termList); - - ObjectWriter om = new ObjectMapper().writer(); - try { - json = om.writeValueAsString(tc); - } catch (Exception e) { - policyLogger.error("Exception Occured"+e); - } - - }catch (Exception e) { - policyLogger.error("Exception Occured"+e); - } - - return json; - } - -} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreatePolicyController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreatePolicyController.java deleted file mode 100644 index 5049d2652..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreatePolicyController.java +++ /dev/null @@ -1,163 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.controller; - - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.openecomp.policy.rest.adapter.PolicyRestAdapter; -import org.openecomp.policy.rest.jpa.PolicyEntity; -import org.openecomp.portalsdk.core.controller.RestrictedBaseController; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; - -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; - -@Controller -@RequestMapping("/") -public class CreatePolicyController extends RestrictedBaseController{ - - protected PolicyRestAdapter policyAdapter = null; - private ArrayList attributeList; - boolean isValidForm = false; - - private String convertDate(String dateTTL, boolean portalType) { - String formateDate = null; - String[] date; - String[] parts; - - if (portalType){ - parts = dateTTL.split("-"); - formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z"; - } else { - date = dateTTL.split("T"); - parts = date[0].split("-"); - formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; - } - return formateDate; - } - - public void prePopulateBaseConfigPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - attributeList = new ArrayList<>(); - if (policyAdapter.getPolicyData() instanceof PolicyType) { - Object policyData = policyAdapter.getPolicyData(); - PolicyType policy = (PolicyType) policyData; - policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - policyAdapter.setConfigType(entity.getConfigurationData().getConfigType()); - policyAdapter.setConfigBodyData(entity.getConfigurationData().getConfigBody()); - String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("_") + 1); - policyAdapter.setPolicyName(policyNameValue); - String description = ""; - try{ - description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); - }catch(Exception e){ - description = policy.getDescription(); - } - policyAdapter.setPolicyDescription(description); - // Get the target data under policy. - TargetType target = policy.getTarget(); - if (target != null) { - // Under target we have AnyOFType - List anyOfList = target.getAnyOf(); - if (anyOfList != null) { - Iterator iterAnyOf = anyOfList.iterator(); - while (iterAnyOf.hasNext()) { - AnyOfType anyOf = iterAnyOf.next(); - // Under AnyOFType we have AllOFType - List allOfList = anyOf.getAllOf(); - if (allOfList != null) { - Iterator iterAllOf = allOfList.iterator(); - int index = 0; - while (iterAllOf.hasNext()) { - AllOfType allOf = iterAllOf.next(); - // Under AllOFType we have Match - List matchList = allOf.getMatch(); - if (matchList != null) { - Iterator iterMatch = matchList.iterator(); - while (iterMatch.hasNext()) { - MatchType match = iterMatch.next(); - // - // Under the match we have attribute value and - // attributeDesignator. So,finally down to the actual attribute. - // - AttributeValueType attributeValue = match.getAttributeValue(); - String value = (String) attributeValue.getContent().get(0); - AttributeDesignatorType designator = match.getAttributeDesignator(); - String attributeId = designator.getAttributeId(); - // First match in the target is EcompName, so set that value. - if (attributeId.equals("ECOMPName")) { - policyAdapter.setEcompName(value); - } - if (attributeId.equals("RiskType")){ - policyAdapter.setRiskType(value); - } - if (attributeId.equals("RiskLevel")){ - policyAdapter.setRiskLevel(value); - } - if (attributeId.equals("guard")){ - policyAdapter.setGuard(value); - } - if (attributeId.equals("TTLDate") && !value.contains("NA")){ - String newDate = convertDate(value, true); - policyAdapter.setTtlDate(newDate); - } - if (attributeId.equals("ConfigName")){ - policyAdapter.setConfigName(value); - } - // After Ecomp and Config it is optional to have attributes, so - // check weather dynamic values or there or not. - if (index >= 7) { - Map attribute = new HashMap<>(); - attribute.put("key", attributeId); - attribute.put("value", value); - attributeList.add(attribute); - } - index++; - } - } - } - } - } - } - - policyAdapter.setAttributes(attributeList); - } - List ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); - for (Object o : ruleList) { - if (o instanceof RuleType) { - // get the condition data under the rule for rule Algorithms. - policyAdapter.setRuleID(((RuleType) o).getRuleId()); - } - } - } - } -} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DashboardController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DashboardController.java deleted file mode 100644 index 230bbe611..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DashboardController.java +++ /dev/null @@ -1,430 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.controller; - - -import java.io.IOException; -import java.net.MalformedURLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.management.AttributeNotFoundException; -import javax.management.InstanceNotFoundException; -import javax.management.MBeanException; -import javax.management.MalformedObjectNameException; -import javax.management.ObjectName; -import javax.management.ReflectionException; -import javax.management.remote.JMXConnector; -import javax.management.remote.JMXConnectorFactory; -import javax.management.remote.JMXServiceURL; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.json.JSONObject; -import org.openecomp.policy.dao.SystemLogDbDao; -import org.openecomp.policy.model.PDPGroupContainer; -import org.openecomp.policy.rest.XACMLRestProperties; -import org.openecomp.policy.rest.dao.CommonClassDao; -import org.openecomp.portalsdk.core.controller.RestrictedBaseController; -import org.openecomp.portalsdk.core.web.support.JsonMessage; -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.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.openecomp.policy.xacml.api.pap.EcompPDP; -import org.openecomp.policy.xacml.api.pap.EcompPDPGroup; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.api.pap.PDP; -import com.att.research.xacml.api.pap.PDPGroup; -import com.att.research.xacml.api.pap.PDPPolicy; -import com.att.research.xacml.util.XACMLProperties; -import com.fasterxml.jackson.annotation.PropertyAccessor; -import com.fasterxml.jackson.databind.ObjectMapper; - -@Controller -@RequestMapping({"/"}) -public class DashboardController extends RestrictedBaseController{ - private static final Logger policyLogger = FlexLogger.getLogger(DashboardController.class); - @Autowired - SystemLogDbDao systemDAO; - - @Autowired - CommonClassDao commonClassDao; - - private int pdpCount; - private PDPGroupContainer pdpConatiner; - private ArrayList pdpStatusData; - private ArrayList papStatusData; - private ArrayList policyActivityData; - - private PolicyController policyController; - public PolicyController getPolicyController() { - return policyController; - } - - public void setPolicyController(PolicyController policyController) { - this.policyController = policyController; - } - - private PolicyController getPolicyControllerInstance(){ - return policyController != null ? getPolicyController() : new PolicyController(); - } - - @RequestMapping(value={"/get_DashboardLoggingData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("availableLoggingDatas", mapper.writeValueAsString(systemDAO.getLoggingData())); - 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); - } - } - - @RequestMapping(value={"/get_DashboardSystemAlertData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getSystemAlertData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("systemAlertsTableDatas", mapper.writeValueAsString(systemDAO.getSystemAlertData())); - 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); - } - } - - @RequestMapping(value={"/get_DashboardPAPStatusData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPAPStatusData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); - addPAPToTable(); - model.put("papTableDatas", mapper.writeValueAsString(papStatusData)); - 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); - } - } - - @RequestMapping(value={"/get_DashboardPDPStatusData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPDPStatusData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); - PolicyController controller = getPolicyControllerInstance(); - this.pdpConatiner = new PDPGroupContainer(controller.getPapEngine()); - addPDPToTable(); - model.put("pdpTableDatas", mapper.writeValueAsString(pdpStatusData)); - 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); - } - } - - @RequestMapping(value={"/get_DashboardPolicyActivityData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPolicyActivityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); - PolicyController controller = getPolicyControllerInstance(); - this.pdpConatiner = new PDPGroupContainer(controller.getPapEngine()); - addPolicyToTable(); - model.put("policyActivityTableDatas", mapper.writeValueAsString(policyActivityData)); - 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); - } - } - - /* - * Add the PAP information to the PAP Table - */ - public void addPAPToTable(){ - papStatusData = new ArrayList<>(); - String papStatus = null; - try { - PolicyController controller = getPolicyControllerInstance(); - Set groups = controller.getPapEngine().getEcompPDPGroups(); - if (groups == null) { - papStatus = "UNKNOWN"; - throw new PAPException("PAP not running"); - }else { - papStatus = "IS_OK"; - } - } catch (PAPException | NullPointerException e1) { - papStatus = "CANNOT_CONNECT"; - policyLogger.error("Error getting PAP status, PAP not responding to requests", e1); - } - String papURL = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); - JSONObject object = new JSONObject(); - object.put("system", papURL); - object.put("status", papStatus); - List data = commonClassDao.getDataByQuery("from PolicyEntity"); - object.put("noOfPolicy", data.size()); - object.put("noOfConnectedTrap", pdpCount); - papStatusData.add(0, object); - } - - /** - * Add PDP Information to the PDP Table - * - */ - public void addPDPToTable(){ - pdpCount = 0; - pdpStatusData = new ArrayList<>(); - long naCount; - long denyCount = 0; - long permitCount = 0; - for (PDPGroup group : this.pdpConatiner.getGroups()){ - for (PDP pdp : group.getPdps()){ - naCount = -1; - if ("UP_TO_DATE".equals(pdp.getStatus().getStatus().toString()) && ((EcompPDP) pdp).getJmxPort() != 0){ - String pdpIpAddress = parseIPSystem(pdp.getId()); - int port = ((EcompPDP) pdp).getJmxPort(); - if (port != 0){ - policyLogger.debug("Getting JMX Response Counts from " + pdpIpAddress + " at JMX port " + port); - naCount = getRequestCounts(pdpIpAddress, port, "pdpEvaluationNA"); - permitCount = getRequestCounts(pdpIpAddress, port, "PdpEvaluationPermit"); - denyCount = getRequestCounts(pdpIpAddress, port, "PdpEvaluationDeny"); - } - } - if (naCount == -1){ - JSONObject object = new JSONObject(); - object.put("id", pdp.getId()); - object.put("name", pdp.getName()); - object.put("groupname", group.getName()); - object.put("status", pdp.getStatus().getStatus().toString()); - object.put("description", pdp.getDescription()); - object.put("permitCount", "NA"); - object.put("denyCount", "NA"); - object.put("naCount", "NA"); - pdpStatusData.add(object); - }else{ - JSONObject object = new JSONObject(); - object.put("id", pdp.getId()); - object.put("name", pdp.getName()); - object.put("groupname", group.getName()); - object.put("status", pdp.getStatus().getStatus().toString()); - object.put("description", pdp.getDescription()); - object.put("permitCount", permitCount); - object.put("denyCount", denyCount); - object.put("naCount", naCount); - pdpStatusData.add(object); - } - pdpCount++; - } - } - } - - private static String parseIPSystem(String line) { - Pattern pattern = Pattern.compile("://(.+?):"); - Matcher ip = pattern.matcher(line); - if (ip.find()) - { - return ip.group(1); - } - return null; - } - - /* - * Contact JMX Connector Sever and return the value of the given jmxAttribute - */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - private long getRequestCounts(String host, int port, String jmxAttribute) { - - policyLogger.debug("Create an RMI connector client and connect it to the JMX connector server"); - HashMap map = new HashMap(); - map = null; - JMXConnector jmxConnection; - try { - jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map); - jmxConnection.connect(); - Object o = jmxConnection.getMBeanServerConnection().getAttribute(new ObjectName("PdpRest:type=PdpRestMonitor"), jmxAttribute); - jmxConnection.close(); - policyLogger.debug("pdpEvaluationNA value retreived: " + o); - return (long) o; - } catch (MalformedURLException e) { - policyLogger.error("MalformedURLException for JMX connection" , e); - } catch (IOException e) { - policyLogger.error("Error in reteriving" + jmxAttribute + " from JMX connection", e); - } catch (AttributeNotFoundException e) { - policyLogger.error("AttributeNotFoundException " + jmxAttribute + " for JMX connection", e); - } catch (InstanceNotFoundException e) { - policyLogger.error("InstanceNotFoundException " + host + " for JMX connection", e); - } catch (MalformedObjectNameException e) { - policyLogger.error("MalformedObjectNameException for JMX connection", e); - } catch (MBeanException e) { - policyLogger.error("MBeanException for JMX connection"); - policyLogger.error("Exception Occured"+e); - } catch (ReflectionException e) { - policyLogger.error("ReflectionException for JMX connection", e); - } - - return -1; - } - - private static JMXServiceURL createConnectionURL(String host, int port) throws MalformedURLException{ - return new JMXServiceURL("rmi", "", 0, "/jndi/rmi://" + host + ":" + port + "/jmxrmi"); - } - - - /* - * Add the information to the Policy Table - */ - private void addPolicyToTable() { - policyActivityData = new ArrayList<>(); - String policyID = null; - int policyFireCount = 0; - Map policyMap = new HashMap<>(); - Object policyList = null; - //get list of policy - - for (PDPGroup group : this.pdpConatiner.getGroups()){ - for (PDPPolicy policy : group.getPolicies()){ - try{ - policyMap.put(policy.getPolicyId().replace(" ", ""), policy.getId()); - }catch(Exception e){ - policyLogger.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID+policy.getName() +e); - } - } - - for (PDP pdp : group.getPdps()){ - // Add rows to the Policy Table - policyList = null; - if ("UP_TO_DATE".equals(pdp.getStatus().getStatus().toString()) && ((EcompPDP) pdp).getJmxPort() != 0){ - String pdpIpAddress = parseIPSystem(pdp.getId()); - policyList = getPolicy(pdpIpAddress, ((EcompPDP) pdp).getJmxPort(), "policyCount"); - } - if (policyList != null && policyList.toString().length() > 3){ - String[] splitPolicy = policyList.toString().split(","); - for (String policyKeyValue : splitPolicy){ - policyID = urnPolicyID(policyKeyValue); - policyFireCount = countPolicyID(policyKeyValue); - if (policyID != null ){ - if (policyMap.containsKey(policyID)){ - JSONObject object = new JSONObject(); - object.put("policyId", policyMap.get(policyID)); - object.put("fireCount", policyFireCount); - object.put("system", pdp.getId()); - policyActivityData.add(object); - } - } - } - }else { - if (policyList != null){ - JSONObject object = new JSONObject(); - object.put("policyId", "Unable to retrieve policy information"); - object.put("fireCount", "NA"); - object.put("system", pdp.getId()); - policyActivityData.add(object); - }else{ - JSONObject object = new JSONObject(); - object.put("policyId", "Unable to access PDP JMX Server"); - object.put("fireCount", "NA"); - object.put("system", pdp.getId()); - policyActivityData.add(object); - } - } - } - } - } - - /* - * Contact JMX Connector Sever and return the list of {policy id , count} - */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - private Object getPolicy(String host, int port, String jmxAttribute){ - policyLogger.debug("Create an RMI connector client and connect it to the JMX connector server for Policy: " + host); - HashMap map = new HashMap(); - map = null; - JMXConnector jmxConnection; - try { - jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map); - jmxConnection.connect(); - Object o = jmxConnection.getMBeanServerConnection().getAttribute(new ObjectName("PdpRest:type=PdpRestMonitor"), "policyMap"); - jmxConnection.close(); - policyLogger.debug("policyMap value retreived: " + o); - return o; - } catch (MalformedURLException e) { - policyLogger.error("MalformedURLException for JMX connection" , e); - } catch (IOException e) { - policyLogger.error("AttributeNotFoundException for policyMap" , e); - } catch (AttributeNotFoundException e) { - policyLogger.error("AttributeNotFoundException for JMX connection", e); - } catch (InstanceNotFoundException e) { - policyLogger.error("InstanceNotFoundException " + host + " for JMX connection", e); - } catch (MalformedObjectNameException e) { - policyLogger.error("MalformedObjectNameException for JMX connection", e); - } catch (MBeanException e) { - policyLogger.error("MBeanException for JMX connection", e); - policyLogger.error("Exception Occured"+e); - } catch (ReflectionException e) { - policyLogger.error("ReflectionException for JMX connection", e); - } - - return null; - - } - - private static String urnPolicyID(String line){ - String[] splitLine = line.toString().split("="); - String removeSpaces = splitLine[0].replaceAll("\\s+", ""); - return removeSpaces.replace("{", ""); - } - - private static Integer countPolicyID(String line){ - String[] splitLine = line.toString().split("="); - String sCount = splitLine[1].replace("}", ""); - int intCount = Integer.parseInt(sCount); - return intCount; - } - -} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java deleted file mode 100644 index f959495c6..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java +++ /dev/null @@ -1,361 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.controller; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import javax.xml.bind.JAXBElement; - -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.rest.adapter.PolicyRestAdapter; -import org.openecomp.policy.rest.adapter.RainyDayParams; -import org.openecomp.policy.rest.adapter.YAMLParams; -import org.openecomp.policy.rest.jpa.PolicyEntity; -import org.openecomp.portalsdk.core.controller.RestrictedBaseController; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; - -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType; - -@Controller -@RequestMapping("/") -public class DecisionPolicyController extends RestrictedBaseController { - private static final Logger policyLogger = FlexLogger.getLogger(DecisionPolicyController.class); - - public DecisionPolicyController(){} - - protected PolicyRestAdapter policyAdapter = null; - private ArrayList attributeList; - private ArrayList decisionList; - private ArrayList ruleAlgorithmList; - private ArrayList treatmentList = null; - protected LinkedList ruleAlgoirthmTracker; - public static final String FUNCTION_NOT = "urn:oasis:names:tc:xacml:1.0:function:not"; - - @SuppressWarnings("unchecked") - public void prePopulateDecisionPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - attributeList = new ArrayList<>(); - decisionList = new ArrayList<>(); - ruleAlgorithmList = new ArrayList<>(); - treatmentList = new ArrayList<>(); - - if (policyAdapter.getPolicyData() instanceof PolicyType) { - RainyDayParams rainydayParams = new RainyDayParams(); - Object policyData = policyAdapter.getPolicyData(); - PolicyType policy = (PolicyType) policyData; - policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("_") + 1); - policyAdapter.setPolicyName(policyNameValue); - String description = ""; - try{ - description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); - }catch(Exception e){ - policyLogger.info("General error", e); - description = policy.getDescription(); - } - policyAdapter.setPolicyDescription(description); - // Get the target data under policy for Action. - TargetType target = policy.getTarget(); - if (target != null) { - // under target we have AnyOFType - List anyOfList = target.getAnyOf(); - if (anyOfList != null) { - Iterator iterAnyOf = anyOfList.iterator(); - while (iterAnyOf.hasNext()) { - AnyOfType anyOf = iterAnyOf.next(); - // Under AntOfType we have AllOfType - List allOfList = anyOf.getAllOf(); - if (allOfList != null) { - Iterator iterAllOf = allOfList.iterator(); - while (iterAllOf.hasNext()) { - AllOfType allOf = iterAllOf.next(); - // Under AllOfType we have Mathch. - List matchList = allOf.getMatch(); - int index = 0; - if (matchList != null) { - Iterator iterMatch = matchList.iterator(); - while (iterMatch.hasNext()) { - MatchType match = iterMatch.next(); - // - // Under the match we have attributevalue and - // attributeDesignator. So,finally down to the actual attribute. - // - AttributeValueType attributeValue = match.getAttributeValue(); - String value = (String) attributeValue.getContent().get(0); - AttributeDesignatorType designator = match.getAttributeDesignator(); - String attributeId = designator.getAttributeId(); - // First match in the target is EcompName, so set that value. - if (attributeId.equals("ECOMPName")) { - policyAdapter.setEcompName(value); - } - // Component attributes are saved under Target here we are fetching them back. - // One row is default so we are not adding dynamic component at index 0. - if (index >= 1) { - Map attribute = new HashMap<>(); - attribute.put("key", attributeId); - attribute.put("value", value); - attributeList.add(attribute); - } - index++; - } - } - policyAdapter.setAttributes(attributeList); - } - } - } - // Setting rainy day attributes to the parameters object if they exist - boolean rainy = false; - if(!attributeList.isEmpty()) { - for(int i=0; i map = (Map)attributeList.get(i); - if(map.get("key").equals("WorkStep")){ - rainydayParams.setWorkstep(map.get("value")); - rainy=true; - }else if(map.get("key").equals("BB_ID")){ - rainydayParams.setBbid(map.get("value")); - rainy=true; - }else if(map.get("key").equals("ServiceType")){ - rainydayParams.setServiceType(map.get("value")); - rainy=true; - }else if(map.get("key").equals("VNFType")){ - rainydayParams.setVnfType(map.get("value")); - rainy=true; - } - } - } - if(rainy){ - policyAdapter.setRuleProvider("Rainy_Day"); - } - } - - List ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); - int index = 0; - for (Object object : ruleList) { - if (object instanceof VariableDefinitionType) { - VariableDefinitionType variableDefinitionType = (VariableDefinitionType) object; - Map settings = new HashMap<>(); - settings.put("key", variableDefinitionType.getVariableId()); - JAXBElement attributeValueTypeElement = (JAXBElement) variableDefinitionType.getExpression(); - if (attributeValueTypeElement != null) { - AttributeValueType attributeValueType = attributeValueTypeElement.getValue(); - settings.put("value", attributeValueType.getContent().get(0).toString()); - } - decisionList.add(settings); - } else if (object instanceof RuleType) { - // get the condition data under the rule for rule Algorithms. - if(((RuleType) object).getEffect().equals(EffectType.DENY)) { - if(((RuleType) object).getAdviceExpressions()!=null){ - if(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId().toString().equalsIgnoreCase("AAF")){ - policyAdapter.setRuleProvider("AAF"); - break; - }else if(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId().toString().equalsIgnoreCase("GUARD_YAML")){ - policyAdapter.setRuleProvider("GUARD_YAML"); - }else if(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId().toString().equalsIgnoreCase("GUARD_BL_YAML")){ - policyAdapter.setRuleProvider("GUARD_BL_YAML"); - } - }else{ - policyAdapter.setRuleProvider("Custom"); - } - ConditionType condition = ((RuleType) object).getCondition(); - if (condition != null) { - ApplyType decisionApply = (ApplyType) condition.getExpression().getValue(); - decisionApply = (ApplyType) decisionApply.getExpression().get(0).getValue(); - ruleAlgoirthmTracker = new LinkedList<>(); - if(policyAdapter.getRuleProvider()!=null && (policyAdapter.getRuleProvider().equals("GUARD_YAML")||(policyAdapter.getRuleProvider().equals("GUARD_BL_YAML")))){ - YAMLParams yamlParams = new YAMLParams(); - for(int i=0; i map = (Map)attributeList.get(i); - if(map.get("key").equals("actor")){ - yamlParams.setActor(map.get("value")); - }else if(map.get("key").equals("recipe")){ - yamlParams.setRecipe(map.get("value")); - }else if(map.get("key").equals("targets")){ - yamlParams.setTargets(Arrays.asList(map.get("value").split("\\|"))); - }else if(map.get("key").equals("clname")){ - yamlParams.setClname(map.get("value")); - } - } - ApplyType apply = ((ApplyType)((ApplyType)decisionApply.getExpression().get(0).getValue()).getExpression().get(0).getValue()); - yamlParams.setGuardActiveStart(((AttributeValueType)apply.getExpression().get(1).getValue()).getContent().get(0).toString()); - yamlParams.setGuardActiveEnd(((AttributeValueType)apply.getExpression().get(2).getValue()).getContent().get(0).toString()); - if(policyAdapter.getRuleProvider().equals("GUARD_BL_YAML")){ - apply = (ApplyType)((ApplyType)((ApplyType)decisionApply.getExpression().get(0).getValue()).getExpression().get(1).getValue()).getExpression().get(2).getValue(); - Iterator> attributes = apply.getExpression().iterator(); - List blackList = new ArrayList<>(); - while(attributes.hasNext()){ - blackList.add(((AttributeValueType)attributes.next().getValue()).getContent().get(0).toString()); - } - yamlParams.setBlackList(blackList); - }else{ - ApplyType timeWindowSection = (ApplyType)((ApplyType)decisionApply.getExpression().get(0).getValue()).getExpression().get(1).getValue(); - yamlParams.setLimit(((AttributeValueType)timeWindowSection.getExpression().get(1).getValue()).getContent().get(0).toString()); - String timeWindow = ((AttributeDesignatorType)((ApplyType)timeWindowSection.getExpression().get(0).getValue()).getExpression().get(0).getValue()).getIssuer(); - yamlParams.setTimeUnits(timeWindow.substring(timeWindow.lastIndexOf(':')+1)); - yamlParams.setTimeWindow(timeWindow.substring(timeWindow.indexOf(":tw:")+4,timeWindow.lastIndexOf(':'))); - } - policyAdapter.setYamlparams(yamlParams); - policyAdapter.setAttributes(new ArrayList()); - policyAdapter.setRuleAlgorithmschoices(new ArrayList()); - break; - } - // Populating Rule Algorithms starting from compound. - prePopulateDecisionCompoundRuleAlgorithm(index, decisionApply); - policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList); - } - } else if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals("Rainy_Day")&& ((RuleType) object).getEffect().equals(EffectType.PERMIT)) { - - TargetType ruleTarget = ((RuleType) object).getTarget(); - AdviceExpressionsType adviceExpression = ((RuleType) object).getAdviceExpressions(); - - String errorcode = ruleTarget.getAnyOf().get(0).getAllOf().get(0).getMatch(). - get(1).getAttributeValue().getContent().get(0).toString(); - JAXBElement tempTreatmentObj = (JAXBElement) adviceExpression.getAdviceExpression(). - get(0).getAttributeAssignmentExpression().get(0).getExpression(); - String treatment = tempTreatmentObj.getValue().getContent().get(0).toString(); - - prePopulateRainyDayTreatments(errorcode, treatment); - - } - } - } - } - - rainydayParams.setTreatmentTableChoices(treatmentList); - policyAdapter.setRainyday(rainydayParams); - policyAdapter.setSettings(decisionList); - } - - } - - private void prePopulateRainyDayTreatments(String errorcode, String treatment) { - Map ruleMap = new HashMap<>(); - - ruleMap.put("errorcode", errorcode); - ruleMap.put("treatment", treatment); - treatmentList.add(ruleMap); - - } - - private void prePopulateDecisionRuleAlgorithms(int index, ApplyType decisionApply, List> jaxbDecisionTypes) { - Map ruleMap = new HashMap<>(); - ruleMap.put("id", "A" + (index +1)); - Map dropDownMap = PolicyController.getDropDownMap(); - for (String key : dropDownMap.keySet()) { - String keyValue = dropDownMap.get(key); - if (keyValue.equals(decisionApply.getFunctionId())) { - ruleMap.put("dynamicRuleAlgorithmCombo", key); - } - } - // Populate the key and value fields - if (((jaxbDecisionTypes.get(0).getValue()) instanceof AttributeValueType)) { - ApplyType innerDecisionApply = (ApplyType) jaxbDecisionTypes.get(1).getValue(); - List> jaxbInnerDecisionTypes = innerDecisionApply.getExpression(); - if (jaxbInnerDecisionTypes.get(0).getValue() instanceof AttributeDesignatorType) { - AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerDecisionTypes.get(0).getValue(); - ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId()); - - // Get from Attribute Value - AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbDecisionTypes.get(0).getValue(); - String attributeValue = (String) actionConditionAttributeValue.getContent().get(0); - ruleMap.put("dynamicRuleAlgorithmField2", attributeValue); - } - } else if ((jaxbDecisionTypes.get(0).getValue()) instanceof VariableReferenceType) { - VariableReferenceType variableReference = (VariableReferenceType) jaxbDecisionTypes.get(0).getValue(); - ruleMap.put("dynamicRuleAlgorithmField1", "S_"+ variableReference.getVariableId()); - - - // Get from Attribute Value - AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbDecisionTypes.get(1).getValue(); - String attributeValue = (String) actionConditionAttributeValue.getContent().get(0); - ruleMap.put("dynamicRuleAlgorithmField2", attributeValue); - } - ruleAlgorithmList.add(ruleMap); - } - - private int prePopulateDecisionCompoundRuleAlgorithm(int index, ApplyType decisionApply) { - boolean isCompoundRule = true; - List> jaxbDecisionTypes = decisionApply.getExpression(); - for (JAXBElement jaxbElement : jaxbDecisionTypes) { - // If There is Attribute Value under Decision Type that means we came to the final child - if (policyLogger.isDebugEnabled()) { - policyLogger.debug("Prepopulating rule algoirthm: " + index); - } - // Check to see if Attribute Value exists, if yes then it is not a compound rule - if(jaxbElement.getValue() instanceof AttributeValueType) { - prePopulateDecisionRuleAlgorithms(index, decisionApply, jaxbDecisionTypes); - ruleAlgoirthmTracker.addLast(index); - isCompoundRule = false; - index++; - } - } - if (isCompoundRule) { - // As it's compound rule, Get the Apply types - for (JAXBElement jaxbElement : jaxbDecisionTypes) { - ApplyType innerDecisionApply = (ApplyType) jaxbElement.getValue(); - index = prePopulateDecisionCompoundRuleAlgorithm(index, innerDecisionApply); - } - // Populate combo box - if (policyLogger.isDebugEnabled()) { - policyLogger.debug("Prepopulating Compound rule algorithm: " + index); - } - Map rule = new HashMap<>(); - for (String key : PolicyController.getDropDownMap().keySet()) { - String keyValue = PolicyController.getDropDownMap().get(key); - if (keyValue.equals(decisionApply.getFunctionId())) { - rule.put("dynamicRuleAlgorithmCombo", key); - break; - } - } - - rule.put("id", "A" + (index +1)); - // Populate Key and values for Compound Rule - rule.put("dynamicRuleAlgorithmField1", "A" + (ruleAlgoirthmTracker.getLast() + 1 )); - ruleAlgoirthmTracker.removeLast(); - rule.put("dynamicRuleAlgorithmField2", "A" + (ruleAlgoirthmTracker.getLast() + 1)); - ruleAlgoirthmTracker.removeLast(); - ruleAlgoirthmTracker.addLast(index); - ruleAlgorithmList.add(rule); - index++; - } - - return index; - } -} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PDPController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PDPController.java deleted file mode 100644 index c2c0bc867..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PDPController.java +++ /dev/null @@ -1,394 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.controller; - - -import java.io.File; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.json.JSONObject; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.model.PDPGroupContainer; -import org.openecomp.policy.model.Roles; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.openecomp.policy.xacml.api.pap.EcompPDPGroup; -import org.openecomp.policy.xacml.std.pap.StdPDP; -import org.openecomp.policy.xacml.std.pap.StdPDPGroup; -import org.openecomp.portalsdk.core.controller.RestrictedBaseController; -import org.openecomp.portalsdk.core.web.support.JsonMessage; -import org.openecomp.portalsdk.core.web.support.UserUtils; -import org.springframework.http.MediaType; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.api.pap.PDPPolicy; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -@Controller -@RequestMapping({"/"}) -public class PDPController extends RestrictedBaseController { - private static final Logger policyLogger = FlexLogger.getLogger(PDPController.class); - - protected List groups = Collections.synchronizedList(new ArrayList()); - private PDPGroupContainer container; - - private static String SUPERADMIN = "super-admin"; - private static String SUPEREDITOR = "super-editor"; - private static String SUPERGUEST = "super-guest"; - - private Set groupsData; - - private boolean junit = false; - - private PolicyController policyController; - public PolicyController getPolicyController() { - return policyController; - } - - public void setPolicyController(PolicyController policyController) { - this.policyController = policyController; - } - - public synchronized void refreshGroups(HttpServletRequest request) { - synchronized(this.groups) { - this.groups.clear(); - try { - PolicyController controller = getPolicyControllerInstance(); - Set filteredPolicies = new HashSet<>(); - Set scopes = null; - List roles = null; - String userId = isJunit() ? "Test" : UserUtils.getUserSession(request).getOrgUserId(); - List userRoles = controller.getRoles(userId); - roles = new ArrayList<>(); - scopes = new HashSet<>(); - for(Object role: userRoles){ - Roles userRole = (Roles) role; - roles.add(userRole.getRole()); - if(userRole.getScope() != null){ - if(userRole.getScope().contains(",")){ - String[] multipleScopes = userRole.getScope().split(","); - for(int i =0; i < multipleScopes.length; i++){ - scopes.add(multipleScopes[i]); - } - }else{ - scopes.add(userRole.getScope()); - } - } - } - if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST) ) { - if(!junit){ - this.groups.addAll(controller.getPapEngine().getEcompPDPGroups()); - }else{ - this.groups.addAll(this.getGroupsData()); - } - }else{ - if(!userRoles.isEmpty()){ - if(!scopes.isEmpty()){ - this.groups.addAll(controller.getPapEngine().getEcompPDPGroups()); - List tempGroups = new ArrayList<>(); - if(!groups.isEmpty()){ - Iterator pdpGroup = groups.iterator(); - while(pdpGroup.hasNext()){ - EcompPDPGroup group = pdpGroup.next(); - Set policies = group.getPolicies(); - for(PDPPolicy policy : policies){ - for(String scope : scopes){ - scope = scope.replace(File.separator, "."); - String policyName = policy.getId(); - if(policyName.contains(".Config_")){ - policyName = policyName.substring(0, policyName.lastIndexOf(".Config_")); - }else if(policyName.contains(".Action_")){ - policyName = policyName.substring(0, policyName.lastIndexOf(".Action_")); - }else if(policyName.contains(".Decision_")){ - policyName = policyName.substring(0, policyName.lastIndexOf(".Decision_")); - } - if(policyName.startsWith(scope)){ - filteredPolicies.add(policy); - } - } - } - pdpGroup.remove(); - StdPDPGroup newGroup = (StdPDPGroup) group; - newGroup.setPolicies(filteredPolicies); - tempGroups.add(newGroup); - } - groups.clear(); - groups = tempGroups; - } - } - } - } - } catch (PAPException e) { - String message = "Unable to retrieve Groups from server: " + e; - policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Pap Engine is Null" + message); - } - } - } - - @RequestMapping(value={"/get_PDPGroupData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPDPGroupEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - ObjectMapper mapper = new ObjectMapper(); - refreshGroups(request); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while retrieving the PDP Group data" + e); - } - } - - @RequestMapping(value={"/pdp_Group/save_pdp_group"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public void savePDPGroup(HttpServletRequest request, HttpServletResponse response){ - try { - ObjectMapper mapper = new ObjectMapper(); - PolicyController controller = getPolicyControllerInstance(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - this.container = new PDPGroupContainer(controller.getPapEngine()); - StdPDPGroup pdpGroupData = mapper.readValue(root.get("pdpGroupData").toString().replace("groupName", "name"), StdPDPGroup.class); - try { - if(pdpGroupData.getId() == null){ - this.container.addNewGroup(pdpGroupData.getName(), pdpGroupData.getDescription()); - }else{ - this.container.updateGroup(pdpGroupData); - } - - } catch (Exception e) { - String message = "Unable to create Group. Reason:\n" + e.getMessage(); - policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while creating the PDP Group" + message + e); - } - - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - refreshGroups(request); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); - JSONObject j = new JSONObject(msg); - out.write(j.toString()); - } - catch (Exception e){ - policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Saving the PDP Group" + e); - response.setCharacterEncoding("UTF-8"); - PrintWriter out = null; - try { - request.setCharacterEncoding("UTF-8"); - out = response.getWriter(); - out.write(e.getMessage()); - } catch (Exception e1) { - policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Saving the PDP Group" + e1); - } - } - } - - @RequestMapping(value={"/pdp_Group/remove_pdp_group"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public void removePDPGroup(HttpServletRequest request, HttpServletResponse response){ - try{ - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - PolicyController controller = getPolicyControllerInstance(); - this.container = new PDPGroupContainer(controller.getPapEngine()); - StdPDPGroup pdpGroupData = mapper.readValue(root.get("pdpGroupData").toString(), StdPDPGroup.class); - if(pdpGroupData.getName().equals("Default")) { - throw new UnsupportedOperationException("You can't remove the Default Group."); - }else{ - this.container.removeGroup(pdpGroupData, null); - } - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - refreshGroups(request); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); - JSONObject j = new JSONObject(msg); - out.write(j.toString()); - } - catch (Exception e){ - policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Removing the PDP Group" + e); - PrintWriter out; - try { - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - out = response.getWriter(); - out.write(e.getMessage()); - } catch (Exception e1) { - policyLogger.error("Exception Occured"+ e1); - } - } - } - - @RequestMapping(value={"/pdp_Group/save_pdpTogroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public void savePDPToGroup(HttpServletRequest request, HttpServletResponse response){ - try { - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - PolicyController controller = getPolicyControllerInstance(); - this.container = new PDPGroupContainer(controller.getPapEngine()); - String update = root.get("update").toString(); - PdpData pdpGroupData = (PdpData)mapper.readValue(root.get("pdpInGroup").toString(), PdpData.class); - StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class); - try { - - if(update.contains("false")){ - this.container.addNewPDP(pdpGroupData.getId(), activeGroupData, pdpGroupData.getName(), pdpGroupData.getDescription(), pdpGroupData.getJmxPort()); - }else{ - this.container.updateGroup(activeGroupData); - } - } catch (Exception e) { - String message = "Unable to create Group. Reason:\n" + e.getMessage(); - policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Creating Pdp in PDP Group" + message + e); - } - - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - refreshGroups(request); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); - JSONObject j = new JSONObject(msg); - out.write(j.toString()); - } - catch (Exception e){ - policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Creating Pdp in PDP Group" + e); - PrintWriter out; - try { - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - out = response.getWriter(); - out.write(e.getMessage()); - } catch (Exception e1) { - policyLogger.error("Exception Occured"+ e1); - } - } - } - - @RequestMapping(value={"/pdp_Group/remove_pdpFromGroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public void removePDPFromGroup(HttpServletRequest request, HttpServletResponse response){ - try{ - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - PolicyController controller = getPolicyControllerInstance(); - this.container = new PDPGroupContainer(controller.getPapEngine()); - StdPDP deletePdp = mapper.readValue(root.get("data").toString(), StdPDP.class); - StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class); - - this.container.removePDP(deletePdp, activeGroupData); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - refreshGroups(request); - String responseString = mapper.writeValueAsString(groups); - JSONObject j = new JSONObject("{pdpEntityDatas: " + responseString + "}"); - out.write(j.toString()); - } - catch (Exception e){ - policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Removing Pdp from PDP Group" + e); - PrintWriter out; - try { - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - out = response.getWriter(); - out.write(e.getMessage()); - } catch (Exception e1) { - policyLogger.error("Exception Occured"+ e1); - } - } - } - - private PolicyController getPolicyControllerInstance(){ - return policyController != null ? getPolicyController() : new PolicyController(); - } - - public boolean isJunit() { - return junit; - } - - public void setJunit(boolean junit) { - this.junit = junit; - } - - public Set getGroupsData() { - return groupsData; - } - - public void setGroupsData(Set groupsData) { - this.groupsData = groupsData; - } -} - -class PdpData{ - String id; - int jmxPort; - String name; - String description; - public String getId() { - return id; - } - public void setId(String id) { - this.id = id; - } - public int getJmxPort() { - return jmxPort; - } - public void setJmxPort(int jmxPort) { - this.jmxPort = jmxPort; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public String getDescription() { - return description; - } - public void setDescription(String description) { - this.description = description; - } - -} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyController.java deleted file mode 100644 index f89687493..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyController.java +++ /dev/null @@ -1,696 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.controller; - - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -import javax.annotation.PostConstruct; -import javax.mail.MessagingException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.json.JSONObject; -import org.openecomp.policy.admin.PolicyNotificationMail; -import org.openecomp.policy.admin.RESTfulPAPEngine; -import org.openecomp.policy.model.PDPGroupContainer; -import org.openecomp.policy.model.Roles; -import org.openecomp.policy.rest.XACMLRestProperties; -import org.openecomp.policy.rest.XacmlAdminAuthorization; -import org.openecomp.policy.rest.dao.CommonClassDao; -import org.openecomp.policy.rest.jpa.Datatype; -import org.openecomp.policy.rest.jpa.FunctionDefinition; -import org.openecomp.policy.rest.jpa.PolicyEntity; -import org.openecomp.policy.rest.jpa.PolicyVersion; -import org.openecomp.policy.rest.jpa.UserInfo; -import org.openecomp.portalsdk.core.controller.RestrictedBaseController; -import org.openecomp.portalsdk.core.web.support.JsonMessage; -import org.openecomp.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; - -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.openecomp.policy.xacml.api.pap.PAPPolicyEngine; - -import com.att.research.xacml.util.XACMLProperties; -import com.fasterxml.jackson.databind.ObjectMapper; - -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; - - -@Controller -@RequestMapping("/") -public class PolicyController extends RestrictedBaseController { - private static final Logger policyLogger = FlexLogger.getLogger(PolicyController.class); - - private static CommonClassDao commonClassDao; - - // Our authorization object - // - XacmlAdminAuthorization authorizer = new XacmlAdminAuthorization(); - // - // The PAP Engine - // - private static PAPPolicyEngine papEngine; - - private static String logTableLimit; - private static String systemAlertTableLimit; - protected static Map dropDownMap = new HashMap<>(); - public static Map getDropDownMap() { - return dropDownMap; - } - - public static void setDropDownMap(Map 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> mapDatatype2Function = null; - private static Map 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"; - - //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 msEcompName; - private static String msPolicyName; - - //WebApp directories - private static String configHome; - private static String actionHome; - - @Autowired - private PolicyController(CommonClassDao commonClassDao){ - PolicyController.commonClassDao = commonClassDao; - } - - public PolicyController() { - } - - @PostConstruct - public void init(){ - Properties prop = new Properties(); - InputStream input = null; - try { - input = new FileInputStream("xacml.admin.properties"); - // load a properties file - prop.load(input); - //pap url - setPapUrl(prop.getProperty("xacml.rest.pap.url")); - // get the property values - setSmtpHost(prop.getProperty("ecomp.smtp.host")); - setSmtpPort(prop.getProperty("ecomp.smtp.port")); - setSmtpUsername(prop.getProperty("ecomp.smtp.userName")); - setSmtpPassword(prop.getProperty("ecomp.smtp.password")); - setSmtpApplicationName(prop.getProperty("ecomp.application.name")); - setSmtpEmailExtension(prop.getProperty("ecomp.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(prop.getProperty("xacml.log.db.password")); - setLogdbDialect(prop.getProperty("ecomp.dialect")); - //Xacml Database Properties - setXacmldbUrl(prop.getProperty("javax.persistence.jdbc.url")); - setXacmldbUserName(prop.getProperty("javax.persistence.jdbc.user")); - setXacmldbPassword(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 - setMsEcompName(prop.getProperty("xacml.policy.msEcompName")); - setMsPolicyName(prop.getProperty("xacml.policy.msPolicyName")); - //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.ecomp.dashboard.logTableLimit")); - setSystemAlertTableLimit(prop.getProperty("xacml.ecomp.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); - } finally { - if (input != null) { - try { - input.close(); - } catch (IOException e) { - policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured while Closing the xacml.admin.properties file" +e); - } - } - } - - //Initialize the FunctionDefinition table at Server Start up - Map> functionMap = getFunctionDatatypeMap(); - for (Datatype id : functionMap.keySet()) { - List functionDefinations = functionMap.get(id); - for (FunctionDefinition functionDef : functionDefinations) { - dropDownMap.put(functionDef.getShortname(),functionDef.getXacmlid()); - } - } - - } - - public static Map> getFunctionDatatypeMap() { - synchronized(mapAccess) { - if (mapDatatype2Function == null) { - buildFunctionMaps(); - } - } - return mapDatatype2Function; - } - - public static Map getFunctionIDMap() { - synchronized(mapAccess) { - if (mapID2Function == null) { - buildFunctionMaps(); - } - } - return mapID2Function; - } - - private static void buildFunctionMaps() { - mapDatatype2Function = new HashMap<>(); - mapID2Function = new HashMap<>(); - List 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()); - } - mapDatatype2Function.get(value.getDatatypeBean()).add(value); - } - } - - @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 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); - } - } - - public PolicyEntity getPolicyEntityData(String scope, String policyName){ - String key = scope + ":" + policyName; - List data = commonClassDao.getDataById(PolicyEntity.class, "scope:policyName", key); - return (PolicyEntity) data.get(0); - } - - public static Map getUserRoles(String userId) { - Map scopes = new HashMap<>(); - List roles = commonClassDao.getDataById(Roles.class, "loginId", userId); - if (roles != null && !roles.isEmpty()) { - for (Object role : roles) { - scopes.put(((Roles) role).getScope(), (Roles) role); - } - } - return scopes; - } - - public List getRolesOfUser(String userId) { - List rolesList = new ArrayList<>(); - List roles = commonClassDao.getDataById(Roles.class, "loginId", userId); - for (Object role: roles) { - rolesList.add(((Roles) role).getRole()); - } - return rolesList; - } - - public List getRoles(String userId) { - return commonClassDao.getDataById(Roles.class, "loginId", userId); - } - - //Get List of User Roles - @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 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 - @RequestMapping(value= {"/policy", "/policy/Editor" } , method = RequestMethod.GET) - public ModelAndView view(HttpServletRequest request){ - String myRequestURL = request.getRequestURL().toString(); - try { - // - // Set the URL for the RESTful PAP Engine - // - setPapEngine((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL)); - new PDPGroupContainer((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL)); - } catch (Exception e) { - policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception Occured while loading PAP"+e); - } - Map model = new HashMap<>(); - return new ModelAndView("policy_Editor","model", model); - } - - public PAPPolicyEngine getPapEngine() { - return papEngine; - } - - public void setPapEngine(PAPPolicyEngine papEngine) { - PolicyController.papEngine = papEngine; - } - - public String getUserName(String createdBy) { - String loginId = createdBy; - List data = commonClassDao.getDataById(UserInfo.class, "loginId", loginId); - return data.get(0).toString(); - } - - public static boolean getActivePolicy(String query) { - if(commonClassDao.getDataByQuery(query).size() > 0){ - return true; - }else{ - return false; - } - } - - 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 getData(@SuppressWarnings("rawtypes") Class className){ - return commonClassDao.getData(className); - } - - public PolicyVersion getPolicyEntityFromPolicyVersion(String query){ - return (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", query); - } - - public List getDataByQuery(String query){ - return commonClassDao.getDataByQuery(query); - } - - - @SuppressWarnings("rawtypes") - public Object getEntityItem(Class className, String columname, String key){ - return commonClassDao.getEntityItem(className, columname, key); - } - - - public void watchPolicyFunction(PolicyVersion entity, String policyName, String mode){ - PolicyNotificationMail email = new PolicyNotificationMail(); - try { - email.sendMail(entity, policyName, mode, commonClassDao); - } catch (MessagingException e) { - policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Excepton Occured while Renaming/Deleting a Policy or Scope" + e); - } - } - - //Switch Version - public JSONObject switchVersionPolicyContent(String policyName) { - 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_")){ - dbCheckName = dbCheckName.replace(".Decision_", ":Decision_"); - } - String[] splitDBCheckName = dbCheckName.split(":"); - String query = "FROM PolicyEntity where policyName like'"+splitDBCheckName[1]+"%' and scope ='"+splitDBCheckName[0]+"'"; - List policyEntity = commonClassDao.getDataByQuery(query); - List av = new ArrayList<>(); - for(Object entity : policyEntity){ - PolicyEntity pEntity = (PolicyEntity) entity; - String removeExtension = pEntity.getPolicyName().replace(".xml", ""); - String version = removeExtension.substring(removeExtension.lastIndexOf(".")+1); - av.add(version); - } - 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 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 XacmlAdminAuthorization getAuthorizer() { - return authorizer; - } - - public void setAuthorizer(XacmlAdminAuthorization authorizer) { - this.authorizer = authorizer; - } - - public static Map> getMapDatatype2Function() { - return mapDatatype2Function; - } - - public static void setMapDatatype2Function(Map> mapDatatype2Function) { - PolicyController.mapDatatype2Function = mapDatatype2Function; - } - - public static Map getMapID2Function() { - return mapID2Function; - } - - public static void setMapID2Function(Map 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 getMsEcompName() { - return msEcompName; - } - - public static void setMsEcompName(String msEcompName) { - PolicyController.msEcompName = msEcompName; - } - - 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; - } -} - diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyExportAndImportController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyExportAndImportController.java deleted file mode 100644 index 8fe2d492f..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyExportAndImportController.java +++ /dev/null @@ -1,384 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.controller; - - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Set; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.json.JSONObject; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.model.Roles; -import org.openecomp.policy.rest.adapter.PolicyExportAdapter; -import org.openecomp.policy.rest.dao.CommonClassDao; -import org.openecomp.policy.rest.jpa.ActionBodyEntity; -import org.openecomp.policy.rest.jpa.ConfigurationDataEntity; -import org.openecomp.policy.rest.jpa.PolicyEditorScopes; -import org.openecomp.policy.rest.jpa.PolicyEntity; -import org.openecomp.policy.rest.jpa.PolicyVersion; -import org.openecomp.policy.rest.jpa.UserInfo; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.openecomp.portalsdk.core.controller.RestrictedBaseController; -import org.openecomp.portalsdk.core.web.support.UserUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; - -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - - -@Controller -@RequestMapping("/") -public class PolicyExportAndImportController extends RestrictedBaseController { - private static Logger logger = FlexLogger.getLogger(PolicyExportAndImportController.class); - - private ArrayList selectedPolicy; - private Set scopes = null; - private List roles = null; - private static String SUPERADMIN = "super-admin"; - private static String SUPEREDITOR = "super-editor"; - private static String ADMIN = "admin"; - private static String EDITOR = "editor"; - - private static CommonClassDao commonClassDao; - - private PolicyEntity policyEntity; - private ConfigurationDataEntity configurationDataEntity; - private ActionBodyEntity actionBodyEntity; - private PolicyVersion policyVersion; - - private Workbook workbook; - - private HSSFWorkbook workBook2; - - private PolicyController policyController; - public PolicyController getPolicyController() { - return policyController; - } - - public void setPolicyController(PolicyController policyController) { - this.policyController = policyController; - } - - public static CommonClassDao getCommonClassDao() { - return commonClassDao; - } - - public static void setCommonClassDao(CommonClassDao commonClassDao) { - PolicyExportAndImportController.commonClassDao = commonClassDao; - } - - @Autowired - private PolicyExportAndImportController(CommonClassDao commonClassDao){ - PolicyExportAndImportController.commonClassDao = commonClassDao; - } - - public PolicyExportAndImportController(){} - - @RequestMapping(value={"/policy_download/exportPolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public void exportPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try{ - String file = null; - selectedPolicy = new ArrayList<>(); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - PolicyExportAdapter adapter = mapper.readValue(root.get("exportData").toString(), PolicyExportAdapter.class); - for (Object policyId : adapter.getPolicyDatas()) { - LinkedHashMap selected = (LinkedHashMap)policyId; - String policyWithScope = selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml"; - String scope = policyWithScope.substring(0 , policyWithScope.lastIndexOf(File.separator)).replace(File.separator, "."); - String policyName = policyWithScope.substring(policyWithScope.lastIndexOf(File.separator)+1); - selectedPolicy.add(policyName+":"+scope); - } - List entityData = commonClassDao.getMultipleDataOnAddingConjunction(PolicyEntity.class, "policyName:scope", selectedPolicy); - - workBook2 = new HSSFWorkbook(); - HSSFSheet sheet = workBook2.createSheet("PolicyEntity"); - - HSSFRow headingRow = sheet.createRow(0); - headingRow.createCell(0).setCellValue("policyName"); - headingRow.createCell(1).setCellValue("scope"); - headingRow.createCell(2).setCellValue("version"); - headingRow.createCell(3).setCellValue("policyData"); - headingRow.createCell(4).setCellValue("description"); - headingRow.createCell(5).setCellValue("configurationbody"); - headingRow.createCell(6).setCellValue("configurationName"); - - short rowNo = 1; - for (Object object : entityData) { - PolicyEntity policyEntity = (PolicyEntity) object; - HSSFRow row = sheet.createRow(rowNo); - row.createCell(0).setCellValue(policyEntity.getPolicyName()); - row.createCell(1).setCellValue(policyEntity.getScope()); - row.createCell(2).setCellValue(policyEntity.getVersion()); - row.createCell(3).setCellValue(policyEntity.getPolicyData()); - row.createCell(4).setCellValue(policyEntity.getDescription()); - if(!policyEntity.getPolicyName().contains("Decision_")){ - if(policyEntity.getConfigurationData() != null){ - row.createCell(5).setCellValue(policyEntity.getConfigurationData().getConfigBody()); - row.createCell(6).setCellValue(policyEntity.getConfigurationData().getConfigurationName()); - } - if(policyEntity.getActionBodyEntity() != null){ - row.createCell(5).setCellValue(policyEntity.getActionBodyEntity().getActionBody()); - row.createCell(6).setCellValue(policyEntity.getActionBodyEntity().getActionBodyName()); - } - }else{ - row.createCell(5).setCellValue(""); - row.createCell(6).setCellValue(""); - } - rowNo++; - } - - String tmp = System.getProperty("catalina.base") + File.separator + "webapps" + File.separator + "temp"; - String deleteCheckPath = tmp + File.separator + "PolicyExport.xls"; - File deleteCheck = new File(deleteCheckPath); - if(deleteCheck.exists()){ - deleteCheck.delete(); - } - File temPath = new File(tmp); - if(!temPath.exists()){ - temPath.mkdir(); - } - - file = temPath + File.separator + "PolicyExport.xls"; - File filepath = new File(file); - FileOutputStream fos = new FileOutputStream(filepath); - workBook2.write(fos); - fos.flush(); - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - String successMap = file.toString().substring(file.toString().lastIndexOf("webapps")+8); - String responseString = mapper.writeValueAsString(successMap); - JSONObject j = new JSONObject("{data: " + responseString + "}"); - out.write(j.toString()); - }catch(Exception e){ - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception Occured while Exporting Policies"+e); - } - } - - //Policy Import - public JSONObject importRepositoryFile(String file, HttpServletRequest request) throws Exception{ - boolean configExists = false; - boolean actionExists = false; - String configName = null; - String scope = null; - boolean finalColumn = false; - PolicyController controller = policyController != null ? getPolicyController() : new PolicyController(); - String userId = UserUtils.getUserSession(request).getOrgUserId(); - UserInfo userInfo = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", userId); - - //Check if the Role and Scope Size are Null get the values from db. - List userRoles = controller.getRoles(userId); - roles = new ArrayList<>(); - scopes = new HashSet<>(); - for(Object role: userRoles){ - Roles userRole = (Roles) role; - roles.add(userRole.getRole()); - if(userRole.getScope() != null){ - if(userRole.getScope().contains(",")){ - String[] multipleScopes = userRole.getScope().split(","); - for(int i =0; i < multipleScopes.length; i++){ - scopes.add(multipleScopes[i]); - } - }else{ - scopes.add(userRole.getScope()); - } - } - } - FileInputStream excelFile = new FileInputStream(new File(file)); - workbook = new HSSFWorkbook(excelFile); - Sheet datatypeSheet = workbook.getSheetAt(0); - Iterator rowIterator = datatypeSheet.iterator(); - - while (rowIterator.hasNext()) { - policyEntity = new PolicyEntity(); - configurationDataEntity = new ConfigurationDataEntity(); - actionBodyEntity = new ActionBodyEntity(); - policyVersion = new PolicyVersion(); - Row currentRow = rowIterator.next(); - if (currentRow.getRowNum() == 0) { - continue; - } - Iterator cellIterator = currentRow.cellIterator(); - while (cellIterator.hasNext()) { - Cell cell = cellIterator.next(); - if (getCellHeaderName(cell).equalsIgnoreCase("policyName")) { - policyEntity.setPolicyName(cell.getStringCellValue()); - } - if (getCellHeaderName(cell).equalsIgnoreCase("scope")) { - policyEntity.setScope(cell.getStringCellValue()); - } - if (getCellHeaderName(cell).equalsIgnoreCase("policyData")) { - policyEntity.setPolicyData(cell.getStringCellValue()); - } - if (getCellHeaderName(cell).equalsIgnoreCase("description")) { - policyEntity.setDescription(cell.getStringCellValue()); - } - if (getCellHeaderName(cell).equalsIgnoreCase("configurationbody")) { - if(policyEntity.getPolicyName().contains("Config_")){ - configExists = true; - configurationDataEntity.setConfigBody(cell.getStringCellValue()); - }else if(policyEntity.getPolicyName().contains("Action_")){ - actionExists = true; - actionBodyEntity.setActionBody(cell.getStringCellValue()); - } - } - if (getCellHeaderName(cell).equalsIgnoreCase("configurationName")) { - finalColumn = true; - configName = cell.getStringCellValue(); - if(policyEntity.getPolicyName().contains("Config_")){ - configurationDataEntity.setConfigurationName(cell.getStringCellValue()); - }else if(policyEntity.getPolicyName().contains("Action_")){ - actionBodyEntity.setActionBodyName(cell.getStringCellValue()); - } - } - - if(finalColumn){ - scope = policyEntity.getScope().replace(".", File.separator); - String query = "FROM PolicyEntity where policyName = '"+policyEntity.getPolicyName()+"' and scope ='"+policyEntity.getScope()+"'"; - List queryData = controller.getDataByQuery(query); - if(!queryData.isEmpty()){ - continue; - } - if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR)) { - //1. if Role contains super admin create scope. - //2. if Role contains super editor don't create new scope and add to list to show to user. - - PolicyEditorScopes policyEditorScope = (PolicyEditorScopes) commonClassDao.getEntityItem(PolicyEditorScopes.class, "scopeName", scope); - if(policyEditorScope == null){ - if(roles.contains(SUPERADMIN)){ - PolicyEditorScopes policyEditorScopeEntity = new PolicyEditorScopes(); - policyEditorScopeEntity.setScopeName(scope); - policyEditorScopeEntity.setUserCreatedBy(userInfo); - policyEditorScopeEntity.setUserModifiedBy(userInfo); - commonClassDao.save(policyEditorScopeEntity); - }else{ - //Add Error Message a new Scope Exists, contact super-admin to create a new scope - continue; - } - } - } - if (roles.contains(ADMIN) || roles.contains(EDITOR)) { - if(scopes.isEmpty()){ - //return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin"); - }else{ - //1. if Role contains admin, then check if parent scope has role admin, if not don't create a scope and add to list. - if(roles.contains(ADMIN)){ - String scopeCheck = scope.substring(0, scope.lastIndexOf(".")); - if(scopes.contains(scopeCheck)){ - PolicyEditorScopes policyEditorScopeEntity = new PolicyEditorScopes(); - policyEditorScopeEntity.setScopeName(scope); - policyEditorScopeEntity.setUserCreatedBy(userInfo); - policyEditorScopeEntity.setUserModifiedBy(userInfo); - commonClassDao.save(policyEditorScopeEntity); - }else{ - continue; - } - }else{ - continue; - } - } - } - - if(configExists){ - if(configName.endsWith("json")){ - configurationDataEntity.setConfigType("JSON"); - }else if(configName.endsWith("txt")){ - configurationDataEntity.setConfigType("OTHER"); - }else if(configName.endsWith("xml")){ - configurationDataEntity.setConfigType("XML"); - }else if(configName.endsWith("properties")){ - configurationDataEntity.setConfigType("PROPERTIES"); - } - configurationDataEntity.setDeleted(false); - configurationDataEntity.setCreatedBy(userId); - configurationDataEntity.setModifiedBy(userId); - commonClassDao.save(configurationDataEntity); - } - if(actionExists){ - actionBodyEntity.setDeleted(false); - actionBodyEntity.setCreatedBy(userId); - actionBodyEntity.setModifiedBy(userId); - commonClassDao.save(actionBodyEntity); - } - if(configName != null){ - if(configName.contains("Config_")){ - ConfigurationDataEntity configuration = (ConfigurationDataEntity) commonClassDao.getEntityItem(ConfigurationDataEntity.class, "configurationName", configName); - policyEntity.setConfigurationData(configuration); - }else{ - ActionBodyEntity actionBody = (ActionBodyEntity) commonClassDao.getEntityItem(ActionBodyEntity.class, "actionBodyName", configName); - policyEntity.setActionBodyEntity(actionBody); - } - } - policyEntity.setCreatedBy(userId); - policyEntity.setModifiedBy(userId); - policyEntity.setDeleted(false); - commonClassDao.save(policyEntity); - - policyVersion = new PolicyVersion(); - String policyName = policyEntity.getPolicyName().replace(".xml", ""); - int version = Integer.parseInt(policyName.substring(policyName.lastIndexOf(".")+1)); - policyName = policyName.substring(0, policyName.lastIndexOf(".")); - - policyVersion.setPolicyName(scope.replace(".", File.separator) + File.separator + policyName); - policyVersion.setActiveVersion(version); - policyVersion.setHigherVersion(version); - policyVersion.setCreatedBy(userId); - policyVersion.setModifiedBy(userId); - commonClassDao.save(policyVersion); - } - } - } - return null; - } - - //return the column header name value - private String getCellHeaderName(Cell cell){ - String cellHeaderName = cell.getSheet().getRow(0).getCell(cell.getColumnIndex()).getRichStringCellValue().toString(); - return cellHeaderName; - } -} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyNotificationController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyNotificationController.java deleted file mode 100644 index 768158453..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyNotificationController.java +++ /dev/null @@ -1,122 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.controller; - - -/* - * - * */ -import java.io.File; -import java.io.PrintWriter; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.json.JSONObject; -import org.openecomp.policy.rest.dao.CommonClassDao; -import org.openecomp.policy.rest.jpa.WatchPolicyNotificationTable; -import org.openecomp.portalsdk.core.controller.RestrictedBaseController; -import org.openecomp.portalsdk.core.web.support.UserUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.servlet.ModelAndView; - -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ArrayNode; - -@Controller -@RequestMapping({"/"}) -public class PolicyNotificationController extends RestrictedBaseController { - - @Autowired - CommonClassDao commonClassDao; - - @RequestMapping(value={"/watchPolicy"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView watchPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ - String path = ""; - String responseValue = ""; - try { - String userId = UserUtils.getUserSession(request).getOrgUserId(); - System.out.println(userId); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - String name = root.get("watchData").get("name").toString(); - JsonNode pathList = root.get("watchData").get("path"); - String finalName = ""; - if(pathList.isArray()){ - ArrayNode arrayNode = (ArrayNode) pathList; - for (int i = 0; i < arrayNode.size(); i++) { - JsonNode individualElement = arrayNode.get(i); - if(i == 0){ - path = path + individualElement.toString().replace("\"", "").trim(); - }else{ - path = path + File.separator + individualElement.toString().replace("\"", "").trim(); - } - } - } - - if(pathList.size() > 0){ - finalName = path + File.separator + name.replace("\"", "").trim(); - }else{ - finalName = name.replace("\"", "").trim(); - } - if(finalName.contains("\\")){ - finalName = finalName.replace("\\", "\\\\"); - } - String query = "from WatchPolicyNotificationTable where POLICYNAME = '"+finalName+"' and LOGINIDS = '"+userId+"'"; - List watchList = commonClassDao.getDataByQuery(query); - if(watchList.isEmpty()){ - if(finalName.contains("\\\\")){ - finalName = finalName.replace("\\\\", File.separator); - } - WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable(); - watch.setPolicyName(finalName); - watch.setLoginIds(userId); - commonClassDao.save(watch); - responseValue = "You have Subscribed Successfully"; - }else{ - commonClassDao.delete(watchList.get(0)); - responseValue = "You have UnSubscribed Successfully"; - } - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(responseValue); - JSONObject j = new JSONObject("{watchData: " + responseString + "}"); - out.write(j.toString()); - return null; - }catch(Exception e){ - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } -} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyRolesController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyRolesController.java deleted file mode 100644 index 219342063..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyRolesController.java +++ /dev/null @@ -1,167 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.controller; - - -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.json.JSONObject; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.rest.dao.CommonClassDao; -import org.openecomp.policy.rest.jpa.PolicyEditorScopes; -import org.openecomp.policy.rest.jpa.PolicyRoles; -import org.openecomp.policy.rest.jpa.UserInfo; -import org.openecomp.portalsdk.core.controller.RestrictedBaseController; -import org.openecomp.portalsdk.core.web.support.JsonMessage; -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.servlet.ModelAndView; - -import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; -import com.fasterxml.jackson.annotation.PropertyAccessor; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -@Controller -@RequestMapping("/") -public class PolicyRolesController extends RestrictedBaseController{ - - private static final Logger LOGGER = FlexLogger.getLogger(PolicyRolesController.class); - - @Autowired - CommonClassDao commonClassDao; - - List scopelist; - - @RequestMapping(value={"/get_RolesData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPolicyRolesEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("rolesDatas", mapper.writeValueAsString(commonClassDao.getUserRoles())); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error("Exception Occured"+e); - } - } - - @RequestMapping(value={"/save_NonSuperRolesData"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView SaveRolesEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - String scopeName = null; - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - ReadScopes adapter = mapper.readValue(root.get("editRoleData").toString(), ReadScopes.class); - for(int i = 0; i < adapter.getScope().size(); i++){ - if(i == 0){ - scopeName = adapter.getScope().get(0); - }else{ - scopeName = scopeName + "," + adapter.getScope().get(i); - } - } - PolicyRoles roles = new PolicyRoles(); - roles.setId(adapter.getId()); - roles.setLoginId(adapter.getLoginId()); - roles.setRole(adapter.getRole()); - roles.setScope(scopeName); - commonClassDao.update(roles); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(commonClassDao.getUserRoles()); - JSONObject j = new JSONObject("{rolesDatas: " + responseString + "}"); - - out.write(j.toString()); - } - catch (Exception e){ - LOGGER.error("Exception Occured"+e); - } - return null; - } - - @RequestMapping(value={"/get_PolicyRolesScopeData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPolicyScopesEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - scopelist = new ArrayList<>(); - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); - List scopesData = commonClassDao.getDataByColumn(PolicyEditorScopes.class, "scopeName"); - model.put("scopeDatas", mapper.writeValueAsString(scopesData)); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error("Exception Occured"+e); - } - } -} - -class ReadScopes{ - private int id; - private UserInfo loginId; - private String role; - private ArrayList scope; - - public int getId() { - return id; - } - public void setId(int id) { - this.id = id; - } - public UserInfo getLoginId() { - return loginId; - } - public void setLoginId(UserInfo loginId) { - this.loginId = loginId; - } - public String getRole() { - return role; - } - public void setRole(String role) { - this.role = role; - } - public ArrayList getScope() { - return scope; - } - public void setScope(ArrayList scope) { - this.scope = scope; - } - -} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java deleted file mode 100644 index 0f8b3795f..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java +++ /dev/null @@ -1,776 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.controller; - - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.io.PrintWriter; -import java.io.StringReader; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Scanner; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.json.Json; -import javax.json.JsonReader; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; - -import org.apache.commons.lang.StringUtils; -import org.dom4j.util.XMLErrorHandler; -import org.json.JSONObject; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.rest.adapter.ClosedLoopFaultBody; -import org.openecomp.policy.rest.adapter.ClosedLoopPMBody; -import org.openecomp.policy.rest.adapter.PolicyRestAdapter; -import org.openecomp.policy.rest.dao.CommonClassDao; -import org.openecomp.policy.rest.jpa.MicroServiceModels; -import org.openecomp.policy.rest.jpa.SafePolicyWarning; -import org.openecomp.policy.utils.PolicyUtils; -import org.openecomp.portalsdk.core.controller.RestrictedBaseController; -import org.openecomp.portalsdk.core.web.support.JsonMessage; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.servlet.ModelAndView; -import org.xml.sax.InputSource; -import org.xml.sax.XMLReader; - -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.base.CharMatcher; -import com.google.common.base.Splitter; -import com.google.common.base.Strings; - -@Controller -@RequestMapping("/") -public class PolicyValidationController extends RestrictedBaseController { - - private static final Logger LOGGER = FlexLogger.getLogger(PolicyValidationController.class); - - public static final String CONFIG_POLICY = "Config"; - public static final String ACTION_POLICY = "Action"; - public static final String DECISION_POLICY = "Decision"; - public static final String CLOSEDLOOP_POLICY = "ClosedLoop_Fault"; - public static final String CLOSEDLOOP_PM = "ClosedLoop_PM"; - public static final String ENFORCER_CONFIG_POLICY= "Enforcer Config"; - public static final String MICROSERVICES="Micro Service"; - private Pattern pattern; - private Matcher matcher; - private static Map mapAttribute = new HashMap<>(); - - private static final String EMAIL_PATTERN = - "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" - + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; - - @Autowired - CommonClassDao commonClassDao; - - @RequestMapping(value={"/policyController/validate_policy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView validatePolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try{ - boolean valid = true; - StringBuilder responseString = new StringBuilder(); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - PolicyRestAdapter policyData = (PolicyRestAdapter)mapper.readValue(root.get("policyData").toString(), PolicyRestAdapter.class); - if(policyData.getPolicyName() != null){ - String policyNameValidate = emptyValidator(policyData.getPolicyName()); - if(!policyNameValidate.contains("success")){ - responseString.append("PolicyName:" + policyNameValidate + "
    "); - valid = false; - }; - }else{ - responseString.append( "PolicyName: PolicyName Should not be empty" + "
    "); - valid = false; - } - if(policyData.getPolicyDescription() != null){ - String descriptionValidate = descriptionValidator(policyData.getPolicyDescription()); - if(!descriptionValidate.contains("success")){ - responseString.append("Description:" + descriptionValidate + "
    "); - valid = false; - } - } - - if(policyData.getPolicyType().equals(CONFIG_POLICY)){ - if (policyData.getConfigPolicyType().equals("Base") || policyData.getConfigPolicyType().equals(CLOSEDLOOP_POLICY) - || policyData.getConfigPolicyType().equals(CLOSEDLOOP_PM) || policyData.getConfigPolicyType().equals(ENFORCER_CONFIG_POLICY) || policyData.getConfigPolicyType().equals(MICROSERVICES)) { - if(policyData.getEcompName() != null){ - String ecompNameValidate = emptyValidator(policyData.getEcompName()); - if(!ecompNameValidate.contains("success")){ - responseString.append("EcompName:" + ecompNameValidate + "
    "); - valid = false; - } - }else{ - responseString.append("Ecomp Name: Ecomp Name Should not be empty" + "
    "); - valid = false; - } - } - - if(policyData.getRiskType() != null){ - String riskTypeValidate = emptyValidator(policyData.getRiskType()); - if(!riskTypeValidate.contains("success")){ - responseString.append("RiskType:" + riskTypeValidate + "
    "); - valid = false; - } - }else { - responseString.append("Risk Type: Risk Type Should not be Empty" + "
    "); - valid = false; - } - - if(policyData.getRiskLevel() != null){ - String validateRiskLevel = emptyValidator(policyData.getRiskLevel()); - if(!validateRiskLevel.contains("success")){ - responseString.append("RiskLevel:" + validateRiskLevel + "
    "); - valid = false; - } - }else { - responseString.append("Risk Level: Risk Level Should not be Empty" + "
    "); - valid = false; - } - - if(policyData.getGuard() != null){ - String validateGuard = emptyValidator(policyData.getGuard()); - if(!validateGuard.contains("success")){ - responseString.append("Guard:" + validateGuard + "
    "); - valid = false; - } - }else { - responseString.append("Guard: Guard Value Should not be Empty" + "
    "); - valid = false; - } - - if(policyData.getConfigPolicyType().equals("Base")){ - if(policyData.getConfigName() != null){ - String configNameValidate = emptyValidator(policyData.getConfigName()); - if(!configNameValidate.contains("success")){ - responseString.append("ConfigName:" + configNameValidate + "
    "); - valid = false; - } - }else{ - responseString.append("Config Name: Config Name Should not be Empty" + "
    "); - valid = false; - } - if(policyData.getConfigType() != null){ - String configTypeValidate = emptyValidator(policyData.getConfigType()); - if(!configTypeValidate.contains("success")){ - responseString.append("ConfigType:" + configTypeValidate + "
    "); - valid = false; - } - }else{ - responseString.append("Config Type: Config Type Should not be Empty" + "
    "); - valid = false; - } - if(policyData.getConfigBodyData() != null){ - String configBodyData = policyData.getConfigBodyData(); - String policyType = policyData.getConfigType(); - if (policyType != null) { - if (policyType.equals("JSON")) { - if (!isJSONValid(configBodyData)) { - responseString.append("Config Body: JSON Content is not valid" + "
    "); - valid = false; - } - } else if (policyType.equals("XML")) { - if (!isXMLValid(configBodyData)) { - responseString.append("Config Body: XML Content data is not valid" + "
    "); - valid = false; - } - } else if (policyType.equals("PROPERTIES")) { - if (!isPropValid(configBodyData)||configBodyData.equals("")) { - responseString.append("Config Body: Property data is not valid" + "
    "); - valid = false; - } - } else if (policyType.equals("OTHER")) { - if (configBodyData.equals("")) { - responseString.append("Config Body: Config Body Should not be Empty" + "
    "); - valid = false; - } - } - } - }else{ - responseString.append("Config Body: Config Body Should not be Empty" + "
    "); - valid = false; - } - } - - if(policyData.getConfigPolicyType().equals("Firewall Config")){ - if(policyData.getConfigName() != null){ - String configNameValidate = PolicyUtils.emptyPolicyValidator(policyData.getConfigName()); - if(!configNameValidate.contains("success")){ - responseString.append("ConfigName:" + configNameValidate + "
    "); - valid = false; - } - }else{ - responseString.append("Config Name: Config Name is required" + "
    "); - valid = false; - } - if(policyData.getSecurityZone() == null){ - responseString.append("Security Zone: Security Zone is required" + "
    "); - valid = false; - } - } - if(policyData.getConfigPolicyType().equals("BRMS_Param")){ - if(policyData.getRuleName() == null){ - responseString.append("BRMS Template:BRMS Template is required
    "); - valid = false; - } - } - if(policyData.getConfigPolicyType().equals("BRMS_Raw")){ - if(policyData.getConfigBodyData() != null){ - String message = PolicyUtils.brmsRawValidate(policyData.getConfigBodyData()); - // If there are any error other than Annotations then this is not Valid - if(message.contains("[ERR")){ - responseString.append("Raw Rule Validate:Raw Rule has error"+ message +"
    "); - valid = false; - } - }else{ - responseString.append("Raw Rule:Raw Rule is required
    "); - valid = false; - } - } - if(policyData.getConfigPolicyType().equals("ClosedLoop_PM")){ - try{ - if(root.get("policyData").get("verticaMetrics").get("serviceTypePolicyName") == null && policyData.getServiceTypePolicyName().isEmpty()){ - responseString.append("ServiceType PolicyName:ServiceType PolicyName is required
    "); - valid = false; - } - }catch(Exception e){ - responseString.append("ServiceType PolicyName:ServiceType PolicyName is required
    "); - valid = false; - } - - if(root.get("policyData").get("jsonBodyData") != null){ - ClosedLoopPMBody pmBody = (ClosedLoopPMBody)mapper.readValue(root.get("policyData").get("jsonBodyData").toString(), ClosedLoopPMBody.class); - if(pmBody.getEmailAddress() != null){ - String result = emailValidation(pmBody.getEmailAddress(), responseString.toString()); - if(result != "success"){ - responseString.append(result + "
    "); - valid = false; - } - } - if(pmBody.getGeoLink() != null){ - String result = PolicyUtils.emptyPolicyValidator(pmBody.getGeoLink()); - if(!result.contains("success")){ - responseString.append("GeoLink:" + result + "
    "); - valid = false; - }; - } - if(pmBody.getAttributes() != null){ - for(Entry entry : pmBody.getAttributes().entrySet()){ - String key = entry.getKey(); - String value = entry.getValue(); - if(!key.contains("Message")){ - String attributeValidate = PolicyUtils.emptyPolicyValidator(value); - if(!attributeValidate.contains("success")){ - responseString.append("Attributes:" + key + " : value has spaces
    "); - valid = false; - }; - } - } - } - }else{ - responseString.append("D2/Virtualized Services:Select atleast one D2/Virtualized Services
    "); - valid = false; - } - } - if(policyData.getConfigPolicyType().equals("ClosedLoop_Fault")){ - if(root.get("policyData").get("jsonBodyData") != null){ - ClosedLoopFaultBody faultBody = (ClosedLoopFaultBody)mapper.readValue(root.get("policyData").get("jsonBodyData").toString(), ClosedLoopFaultBody.class); - if(faultBody.getEmailAddress() != null){ - String result = emailValidation(faultBody.getEmailAddress(), responseString.toString()); - if(result != "success"){ - responseString.append(result+ "
    "); - valid = false; - } - } - if((faultBody.isGama() || faultBody.isMcr() || faultBody.isTrinity() || faultBody.isvDNS() || faultBody.isvUSP()) != true){ - responseString.append("D2/Virtualized Services:Select atleast one D2/Virtualized Services
    "); - valid = false; - } - if(faultBody.getActions() == null){ - responseString.append("vPRO Actions:vPRO Actions is required
    "); - valid = false; - } - if(faultBody.getClosedLoopPolicyStatus() == null){ - responseString.append("Policy Status:Policy Status is required
    "); - valid = false; - } - if(faultBody.getConditions() == null){ - responseString.append("Conditions:Select Atleast one Condition
    "); - valid = false; - } - if(faultBody.getGeoLink() != null){ - String result = PolicyUtils.emptyPolicyValidatorWithSpaceAllowed(faultBody.getGeoLink()); - if(!result.contains("success")){ - responseString.append("GeoLink:" + result + "
    "); - valid = false; - }; - } - - if(faultBody.getTimeInterval() == 0){ - responseString.append("Time Interval:Time Interval is required
    "); - valid = false; - } - if(faultBody.getRetrys() == 0){ - responseString.append("Number of Retries:Number of Retries is required
    "); - valid = false; - } - if(faultBody.getTimeOutvPRO() == 0){ - responseString.append("APP-C Timeout:APP-C Timeout is required
    "); - valid = false; - } - if(faultBody.getTimeOutRuby() == 0){ - responseString.append("TimeOutRuby:TimeOutRuby is required
    "); - valid = false; - } - if(faultBody.getVnfType() == null){ - responseString.append("Vnf Type:Vnf Type is required
    "); - valid = false; - } - }else{ - responseString.append("D2/Virtualized Services:Select atleast one D2/Virtualized Services
    "); - responseString.append("vPRO Actions:vPRO Actions is required
    "); - responseString.append("Aging Window:Aging Window is required
    "); - responseString.append("Policy Status:Policy Status is required
    "); - responseString.append("Conditions:Select Atleast one Condition
    "); - responseString.append("PEP Name:PEP Name is required
    "); - responseString.append("PEP Action:PEP Action is required
    "); - responseString.append("Time Interval:Time Interval is required
    "); - responseString.append("Number of Retries:Number of Retries is required
    "); - responseString.append("APP-C Timeout:APP-C Timeout is required
    "); - responseString.append("TimeOutRuby:TimeOutRuby is required
    "); - responseString.append("Vnf Type:Vnf Type is required
    "); - valid = false; - } - } - - if (policyData.getConfigPolicyType().contains("Micro Service")){ - if(policyData.getServiceType() != null){ - pullJsonKeyPairs(root.get("policyJSON")); - MicroServiceModels returnModel = new MicroServiceModels(); - String service = null; - String version = null; - if (policyData.getServiceType().contains("-v")){ - service = policyData.getServiceType().split("-v")[0]; - version = policyData.getServiceType().split("-v")[1]; - }else { - service = policyData.getServiceType(); - version = policyData.getVersion(); - } - returnModel = getAttributeObject(service, version); - String annoation = returnModel.getAnnotation(); - if (!Strings.isNullOrEmpty(annoation)){ - Map rangeMap = new HashMap<>(); - rangeMap = Splitter.on(",").withKeyValueSeparator("=").split(annoation); - for (Entry rMap : rangeMap.entrySet()){ - if (rMap.getValue().contains("range::")){ - String value = mapAttribute.get(rMap.getKey().trim()); - String[] tempString = rMap.getValue().split("::")[1].split("-"); - int startNum = Integer.parseInt(tempString[0]); - int endNum = Integer.parseInt(tempString[1]); - String returnString = "Invalid Range:" + rMap.getKey() + " must be between " - + startNum + " - " + endNum + ","; - if (PolicyUtils.isInteger(value.replace("\"", ""))){ - int result = Integer.parseInt(value.replace("\"", "")); - if (result < startNum || result > endNum){ - responseString.append(returnString); - valid = false; - } - }else { - responseString.append(returnString); - valid = false; - } - } - } - } - }else{ - responseString.append("Micro Service: Micro Service is required" + "
    "); - valid = false; - } - - if(policyData.getPriority() == null){ - responseString.append("Priority: Priority is required" + "
    "); - valid = false; - } - } - } - if (policyData.getPolicyType().equals(DECISION_POLICY)){ - if(policyData.getEcompName() != null){ - String ecompNameValidate = emptyValidator(policyData.getEcompName()); - if(!ecompNameValidate.contains("success")){ - responseString.append("EcompName:" + ecompNameValidate + "
    "); - valid = false; - } - }else{ - responseString.append("Ecomp Name: Ecomp Name Should not be empty" + "
    "); - valid = false; - } - - if("Rainy_Day".equals(policyData.getRuleProvider())){ - if(policyData.getRainyday()==null){ - responseString.append(" Rainy Day Parameters are Required
    "); - valid = false; - }else{ - if(policyData.getRainyday().getServiceType()==null){ - responseString.append("Rainy Day Service Type is Required
    "); - valid = false; - } - if(policyData.getRainyday().getVnfType()==null){ - responseString.append("Rainy Day VNF Type is Required
    "); - valid = false; - } - if(policyData.getRainyday().getBbid()==null){ - responseString.append("Rainy Day Building Block ID is Required
    "); - valid = false; - } - if(policyData.getRainyday().getWorkstep()==null){ - responseString.append("Rainy Day Work Step is Required
    "); - valid = false; - } - if(policyData.getRainyday().getServiceType()==null){ - responseString.append("Rainy Day Error Code is Required
    "); - valid = false; - } - } - } - - if("GUARD_YAML".equals(policyData.getRuleProvider()) || "GUARD_BL_YAML".equals(policyData.getRuleProvider())){ - if(policyData.getYamlparams()==null){ - responseString.append(" Guard Params are Required " + "
    "); - valid = false; - }else{ - if(policyData.getYamlparams().getActor()==null){ - responseString.append("Guard Params Actor is Required " + "
    "); - valid = false; - } - if(policyData.getYamlparams().getRecipe()==null){ - responseString.append("Guard Params Recipe is Required " + "
    "); - valid = false; - } - if(policyData.getYamlparams().getGuardActiveStart()==null){ - responseString.append("Guard Params Guard Active Start/b>is Required " + "
    "); - valid = false; - } - if(policyData.getYamlparams().getGuardActiveEnd()==null){ - responseString.append("Guard Params Guard Active Endis Required " + "
    "); - valid = false; - } - if("GUARD_YAML".equals(policyData.getRuleProvider())){ - if(policyData.getYamlparams().getLimit()==null){ - responseString.append(" Guard Params Limit is Required " + "
    "); - valid = false; - }else if(!PolicyUtils.isInteger(policyData.getYamlparams().getLimit())){ - responseString.append(" Guard Params Limit Should be Integer " + "
    "); - valid = false; - } - if(policyData.getYamlparams().getTimeWindow()==null){ - responseString.append("Guard Params Time Window is Required" + "
    "); - valid = false; - }else if(!PolicyUtils.isInteger(policyData.getYamlparams().getTimeWindow())){ - responseString.append(" Guard Params Time Window Should be Integer " + "
    "); - valid = false; - } - if(policyData.getYamlparams().getTimeUnits()==null){ - responseString.append("Guard Params Time Units is Required" + "
    "); - valid = false; - } - }else if("GUARD_BL_YAML".equals(policyData.getRuleProvider())){ - if(policyData.getYamlparams().getBlackList()==null || policyData.getYamlparams().getBlackList().isEmpty()){ - responseString.append(" Guard Params BlackList is Required " + "
    "); - valid = false; - }else{ - for(String blackList: policyData.getYamlparams().getBlackList()){ - if(blackList==null || !("success".equals(emptyValidator(blackList)))){ - responseString.append(" Guard Params BlackList Should be valid String" + "
    "); - valid = false; - break; - } - } - } - } - } - } - } - - if(policyData.getPolicyType().equals(ACTION_POLICY)){ - if(policyData.getActionPerformer() != null){ - String actionPerformer = emptyValidator(policyData.getActionPerformer()); - if(!actionPerformer.contains("success")){ - responseString.append("ActionPerformer:" + actionPerformer + "
    "); - valid = false; - }; - }else{ - responseString.append("ActionPerformer: ActionPerformer Should not be empty" + "
    "); - valid = false; - } - if(policyData.getAttributes() != null){ - for(Object attribute : policyData.getAttributes()){ - if(attribute instanceof LinkedHashMap){ - try{ - //This is for validation check if the value exists or not - String key = ((LinkedHashMap) attribute).get("key").toString(); - String value = ((LinkedHashMap) attribute).get("value").toString(); - if("".equals(key) || "".equals(value)){ - responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "
    "); - valid = false; - break; - } - }catch(Exception e){ - LOGGER.error("This is a Policy Validation check" +e); - responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "
    "); - valid = false; - break; - } - } - } - }else{ - responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "
    "); - valid = false; - } - if(policyData.getActionAttributeValue() != null){ - String actionAttribute = emptyValidator(policyData.getActionAttributeValue()); - if(!actionAttribute.contains("success")){ - responseString.append("ActionAttribute:" + actionAttribute + "
    "); - valid = false; - }; - }else{ - responseString.append("ActionAttribute: ActionAttribute Should not be empty" + "
    "); - valid = false; - } - } - - if(policyData.getPolicyType().equals(ACTION_POLICY) || policyData.getPolicyType().equals(DECISION_POLICY)){ - if(!policyData.getRuleAlgorithmschoices().isEmpty()){ - for(Object attribute : policyData.getRuleAlgorithmschoices()){ - if(attribute instanceof LinkedHashMap){ - try{ - String label = ((LinkedHashMap) attribute).get("id").toString(); - String key = ((LinkedHashMap) attribute).get("dynamicRuleAlgorithmField1").toString(); - String rule = ((LinkedHashMap) attribute).get("dynamicRuleAlgorithmCombo").toString(); - String value = ((LinkedHashMap) attribute).get("dynamicRuleAlgorithmField2").toString(); - if("".equals(label) || "".equals(key) || "".equals(rule) || "".equals(value)){ - responseString.append("Rule Algorithms: One or more Fields in Rule Algorithms is Empty." + "
    "); - valid = false; - } - }catch(Exception e){ - LOGGER.error("This is a Policy Validation check" +e); - responseString.append("Rule Algorithms: One or more Fields in Rule Algorithms is Empty." + "
    "); - valid = false; - break; - } - } - } - } - } - - if(policyData.getPolicyType().equals(CONFIG_POLICY)){ - String value = ""; - if(valid){ - List spData = commonClassDao.getDataById(SafePolicyWarning.class, "riskType", policyData.getRiskType()); - if (!spData.isEmpty()){ - SafePolicyWarning safePolicyWarningData = (SafePolicyWarning) spData.get(0); - safePolicyWarningData.getMessage(); - value = "Message:" + safePolicyWarningData.getMessage(); - } - responseString.append("success" + "@#"+ value); - } - }else{ - if(valid){ - responseString.append("success"); - } - } - - PrintWriter out = response.getWriter(); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(responseString.toString())); - JSONObject j = new JSONObject(msg); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error("Exception Occured while Policy Validation" +e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - protected String emptyValidator(String field){ - String error; - if ("".equals(field) || field.contains(" ") || !field.matches("^[a-zA-Z0-9_]*$")) { - error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations"; - return error; - } else { - if(CharMatcher.ASCII.matchesAllOf((CharSequence) field)){ - error = "success"; - }else{ - error = "The Value Contains Non ASCII Characters"; - return error; - } - } - return error; - } - - protected String descriptionValidator(String field) { - String error; - if (field.contains("@CreatedBy:") || field.contains("@ModifiedBy:")) { - error = "The value in the description shouldn't contain @CreatedBy: or @ModifiedBy:"; - return error; - } else { - error = "success"; - } - return error; - } - - public String validateEmailAddress(String emailAddressValue) { - String error = "success"; - List emailList = Arrays.asList(emailAddressValue.toString().split(",")); - for(int i =0 ; i < emailList.size() ; i++){ - pattern = Pattern.compile(EMAIL_PATTERN); - matcher = pattern.matcher(emailList.get(i).trim()); - if(!matcher.matches()){ - error = "Please check the Following Email Address is not Valid .... " +emailList.get(i).toString(); - return error; - }else{ - error = "success"; - } - } - return error; - } - - protected String emailValidation(String email, String response){ - if(email != null){ - String validateEmail = PolicyUtils.validateEmailAddress(email.replace("\"", "")); - if(!validateEmail.contains("success")){ - response += "Email:" + validateEmail+ "
    "; - }else{ - return "success"; - } - } - return response; - } - - private MicroServiceModels getAttributeObject(String name, String version) { - MicroServiceModels workingModel = new MicroServiceModels(); - List microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName:version", name+":"+version); - if(microServiceModelsData != null){ - workingModel = (MicroServiceModels) microServiceModelsData.get(0); - } - return workingModel; - } - - private void pullJsonKeyPairs(JsonNode rootNode) { - Iterator> fieldsIterator = rootNode.fields(); - - while (fieldsIterator.hasNext()) { - Map.Entry field = fieldsIterator.next(); - final String key = field.getKey(); - final JsonNode value = field.getValue(); - if (value.isContainerNode() && !value.isArray()) { - pullJsonKeyPairs(value); // RECURSIVE CALL - } else { - if (value.isArray()){ - String newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, new String[]{"", "", ""}); - mapAttribute.put(key, newValue); - }else { - mapAttribute.put(key, value.toString().trim()); - } - } - } - } - - // Validation for json. - protected static boolean isJSONValid(String data) { - JsonReader jsonReader = null; - try { - new JSONObject(data); - InputStream stream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); - jsonReader = Json.createReader(stream); - LOGGER.info("Json Value is: " + jsonReader.read().toString() ); - } catch (Exception e) { - LOGGER.error("Exception Occured While Validating"+e); - return false; - }finally{ - if(jsonReader != null){ - jsonReader.close(); - } - } - return true; - } - - // Validation for XML. - private boolean isXMLValid(String data) { - SAXParserFactory factory = SAXParserFactory.newInstance(); - factory.setValidating(false); - factory.setNamespaceAware(true); - try { - SAXParser parser = factory.newSAXParser(); - XMLReader reader = parser.getXMLReader(); - reader.setErrorHandler(new XMLErrorHandler()); - reader.parse(new InputSource(new StringReader(data))); - } catch (Exception e) { - LOGGER.error("Exception Occured While Validating"+e); - return false; - } - return true; - } - - // Validation for Properties file. - public boolean isPropValid(String prop) { - Scanner scanner = new Scanner(prop); - while (scanner.hasNextLine()) { - String line = scanner.nextLine(); - line = line.replaceAll("\\s+", ""); - if (line.startsWith("#")) { - continue; - } else { - if (line.contains("=")) { - String[] parts = line.split("="); - if (parts.length < 2) { - scanner.close(); - return false; - } - } else { - scanner.close(); - return false; - } - } - } - scanner.close(); - return true; - } - -} \ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/dao/SystemLogDbDao.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/dao/SystemLogDbDao.java deleted file mode 100644 index bdfdd8f0a..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/dao/SystemLogDbDao.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.dao; - - -import java.util.List; - -import org.openecomp.policy.rest.jpa.SystemLogDB; - - - -public abstract interface SystemLogDbDao { - public abstract List getLoggingData(); - public abstract List getSystemAlertData(); -} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/daoImp/CommonClassDaoImpl.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/daoImp/CommonClassDaoImpl.java deleted file mode 100644 index 477850a11..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/daoImp/CommonClassDaoImpl.java +++ /dev/null @@ -1,382 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.daoImp; - -import java.util.ArrayList; -import java.util.List; - -import org.hibernate.Criteria; -import org.hibernate.Query; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.Transaction; -import org.hibernate.criterion.Conjunction; -import org.hibernate.criterion.Disjunction; -import org.hibernate.criterion.Projections; -import org.hibernate.criterion.Restrictions; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.rest.dao.CommonClassDao; -import org.openecomp.policy.rest.jpa.PolicyRoles; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service("CommonClassDao") -public class CommonClassDaoImpl implements CommonClassDao{ - - private static final Logger LOGGER = FlexLogger.getLogger(CommonClassDaoImpl.class); - - @Autowired - SessionFactory sessionfactory; - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Override - public List getData(Class className) { - Session session = sessionfactory.openSession(); - List data = null; - try{ - Criteria cr = session.createCriteria(className); - data = cr.list(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e); - }finally{ - try{ - session.close(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e); - } - } - return data; - } - - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public List getDataById(Class className, String columnName, String key) { - Session session = sessionfactory.openSession(); - List data = null; - try { - Criteria cr = session.createCriteria(className); - if(columnName.contains(":") && key.contains(":")){ - String[] columns = columnName.split(":"); - String[] keys = key.split(":"); - for(int i=0; i < columns.length; i++){ - cr.add(Restrictions.eq(columns[i], keys[i])); - } - }else{ - cr.add(Restrictions.eq(columnName, key)); - } - data = cr.list(); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e); - }finally{ - try{ - session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - } - } - return data; - } - - @Override - public void save(Object entity) { - Session session = sessionfactory.openSession(); - Transaction tx = session.beginTransaction(); - try { - session.persist(entity); - tx.commit(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving data to Table"+e); - }finally{ - try{ - session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - } - } - - } - - @Override - public void delete(Object entity) { - Session session = sessionfactory.openSession(); - Transaction tx = session.beginTransaction(); - try { - session.delete(entity); - tx.commit(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting data from Table"+e); - }finally{ - try{ - session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - } - } - - } - - - @Override - public void update(Object entity) { - Session session = sessionfactory.openSession(); - Transaction tx = session.beginTransaction(); - try { - session.update(entity); - tx.commit(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating data to Table"+e); - }finally{ - try{ - session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - } - } - - } - - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Override - public List checkDuplicateEntry(String value, String columnName, Class className) { - Session session = sessionfactory.openSession(); - Transaction tx = session.beginTransaction(); - List data = null; - String[] columnNames = null; - if(columnName != null && columnName.contains(":")){ - columnNames = columnName.split(":"); - } - String[] values = null; - if(value != null && value.contains(":")){ - values = value.split(":"); - } - try { - Criteria cr = session.createCriteria(className); - if(columnNames != null && values != null && columnNames.length == values.length){ - for (int i = 0; i < columnNames.length; i++){ - cr.add(Restrictions.eq(columnNames[i],values[i])); - } - }else{ - cr.add(Restrictions.eq(columnName,value)); - } - data = cr.list(); - tx.commit(); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying for Duplicate Entries for Table"+e + className); - }finally{ - try{ - session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - } - } - return data; - } - - - @SuppressWarnings("unchecked") - @Override - public List getUserRoles() { - Session session = sessionfactory.openSession(); - Transaction tx = session.beginTransaction(); - List rolesData = null; - try { - Criteria cr = session.createCriteria(PolicyRoles.class); - Disjunction disjunction = Restrictions.disjunction(); - Conjunction conjunction1 = Restrictions.conjunction(); - conjunction1.add(Restrictions.eq("role", "admin")); - Conjunction conjunction2 = Restrictions.conjunction(); - conjunction2.add(Restrictions.eq("role", "editor")); - Conjunction conjunction3 = Restrictions.conjunction(); - conjunction3.add(Restrictions.eq("role", "guest")); - disjunction.add(conjunction1); - disjunction.add(conjunction2); - disjunction.add(conjunction3); - rolesData = cr.add(disjunction).list(); - tx.commit(); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying PolicyRoles Table"+e); - }finally{ - try{ - session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - } - } - return rolesData; - } - - - @Override - public List checkExistingGroupListforUpdate(String arg0, String arg1) { - return null; - } - - - @Override - public void deleteAll() {} - - - @SuppressWarnings("unchecked") - @Override - public List getDataByQuery(String query) { - Session session = sessionfactory.openSession(); - Transaction tx = session.beginTransaction(); - List data = null; - try { - Query hbquery = session.createQuery(query); - data = hbquery.list(); - tx.commit(); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Database Table"+e); - }finally{ - try{ - session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - } - } - return data; - } - - - @SuppressWarnings("rawtypes") - @Override - public Object getEntityItem(Class className, String columnName, String key) { - Session session = sessionfactory.openSession(); - Transaction tx = session.beginTransaction(); - Object data = null; - try { - Criteria cr = session.createCriteria(className); - if(columnName.contains(":") && key.contains(":")){ - String[] columns = columnName.split(":"); - String[] keys = key.split(":"); - for(int i=0; i < columns.length; i++){ - cr.add(Restrictions.eq(columns[i], keys[i])); - } - }else{ - cr.add(Restrictions.eq(columnName, key)); - } - data = cr.list().get(0); - tx.commit(); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Database Table"+e); - }finally{ - try{ - session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - } - } - return data; - } - - - @Override - public void updateClAlarms(String arg0, String arg1) {} - - - @Override - public void updateClYaml(String arg0, String arg1) {} - - - @Override - public void updateQuery(String query) { - Session session = sessionfactory.openSession(); - Transaction tx = session.beginTransaction(); - try { - Query hbquery = session.createQuery(query); - hbquery.executeUpdate(); - tx.commit(); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating Database Table"+e); - }finally{ - try{ - session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - } - } - - } - - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public List getDataByColumn(Class className, String columnName) { - Session session = sessionfactory.openSession(); - List data = null; - try{ - Criteria cr = session.createCriteria(className); - cr.setProjection(Projections.property(columnName)); - data = cr.list(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e); - }finally{ - try{ - session.close(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e); - } - } - return data; - } - - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public List getMultipleDataOnAddingConjunction(Class className, String columnName, List data) { - Session session = sessionfactory.openSession(); - Transaction tx = session.beginTransaction(); - List entityData = null; - try { - Criteria cr = session.createCriteria(className); - Disjunction disjunction = Restrictions.disjunction(); - List conjunctionList = new ArrayList<>(); - String[] columNames = columnName.split(":"); - for(int i =0; i < data.size(); i++){ - String[] entiySplit = data.get(i).split(":"); - Conjunction conjunction = Restrictions.conjunction(); - conjunction.add(Restrictions.eq(columNames[0], entiySplit[0])); - conjunction.add(Restrictions.eq(columNames[1], entiySplit[1])); - conjunctionList.add(conjunction); - } - for(int j =0 ; j < conjunctionList.size(); j++){ - disjunction.add(conjunctionList.get(j)); - } - entityData = cr.add(disjunction).list(); - tx.commit(); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table" +className +e); - }finally{ - try{ - session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - } - } - return entityData; - } - -} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/daoImp/SystemLogDbDaoImpl.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/daoImp/SystemLogDbDaoImpl.java deleted file mode 100644 index fbca821d4..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/daoImp/SystemLogDbDaoImpl.java +++ /dev/null @@ -1,93 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.daoImp; - - -import java.util.List; - -import org.hibernate.Criteria; -import org.hibernate.Session; -import org.springframework.stereotype.Service; - -import org.openecomp.policy.xacml.api.XACMLErrorConstants; - -import org.hibernate.Transaction; -import org.hibernate.criterion.Restrictions; -import org.openecomp.policy.conf.HibernateSession; -import org.openecomp.policy.controller.PolicyController; -import org.openecomp.policy.dao.SystemLogDbDao; -import org.openecomp.policy.rest.jpa.SystemLogDB; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; - - -@Service("SystemLogDbDao") -public class SystemLogDbDaoImpl implements SystemLogDbDao { - private static final Logger logger = FlexLogger.getLogger(SystemLogDbDaoImpl.class); - @SuppressWarnings("unchecked") - @Override - public List getLoggingData() { - Session session = HibernateSession.getSession(); - Transaction tx = session.beginTransaction(); - List system = null; - try { - String sqlWhere = "date > DATE_SUB(curdate(), INTERVAL 5 DAY) ORDER BY date DESC limit "+PolicyController.getLogTableLimit()+""; - Criteria cr = session.createCriteria(SystemLogDB.class); - cr.add(Restrictions.sqlRestriction(sqlWhere)); - system = cr.list(); - tx.commit(); - } catch (Exception e) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying SystemLogDB Table"+e); - }finally{ - try{ - session.close(); - }catch(Exception e1){ - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - } - } - return system; - } - - @SuppressWarnings("unchecked") - @Override - public List getSystemAlertData() { - Session session = HibernateSession.getSession();; - Transaction tx = session.beginTransaction(); - List system = null; - try { - String sqlWhere = "date > DATE_SUB(curdate(), INTERVAL 5 DAY) and logtype = 'error' ORDER BY date DESC limit "+PolicyController.getSystemAlertTableLimit()+""; - Criteria cr = session.createCriteria(SystemLogDB.class); - cr.add(Restrictions.sqlRestriction(sqlWhere)); - system = cr.list(); - tx.commit(); - } catch (Exception e) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying SystemLogDB Table"+e); - }finally{ - try{ - session.close(); - }catch(Exception e1){ - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - } - } - return system; - } - -} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/PDPGroupContainer.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/PDPGroupContainer.java deleted file mode 100644 index d048ded99..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/PDPGroupContainer.java +++ /dev/null @@ -1,522 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.model; - - -import java.awt.Checkbox; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.utils.PolicyContainer; -import org.openecomp.policy.utils.PolicyItemSetChangeNotifier; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.openecomp.policy.xacml.api.pap.EcompPDP; -import org.openecomp.policy.xacml.api.pap.EcompPDPGroup; -import org.openecomp.policy.xacml.api.pap.PAPPolicyEngine; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.api.pap.PDP; -//import com.att.research.xacml.api.pap.PDP; -//import com.att.research.xacml.api.pap.PDPGroup; -import com.att.research.xacml.api.pap.PDPPIPConfig; -import com.att.research.xacml.api.pap.PDPPolicy; - -public class PDPGroupContainer extends PolicyItemSetChangeNotifier implements PolicyContainer.Indexed, PolicyContainer.ItemSetChangeNotifier { - private static final long serialVersionUID = 1L; - private static Logger LOGGER = FlexLogger.getLogger(PDPGroupContainer.class); - - /** - * String identifier of a file's "Id" property. - */ - private static String PROPERTY_ID = "Id"; - - /** - * String identifier of a file's "name" property. - */ - private static String PROPERTY_NAME = "Name"; - - /** - * String identifier of a file's "Description" property. - */ - private static String PROPERTY_DESCRIPTION = "Description"; - - /** - * String identifier of a file's "Default" property. - */ - private static String PROPERTY_DEFAULT = "Default"; - /** - * String identifier of a file's "Status" property. - */ - private static String PROPERTY_STATUS = "Status"; - - /** - * String identifier of a file's "PDPs" property. - */ - private static String PROPERTY_PDPS = "PDPs"; - - /** - * String identifier of a file's "Policies" property. - */ - private static String PROPERTY_POLICIES = "Policies"; - - /** - * String identifier of a file's "PIP Configurations" property. - */ - private static String PROPERTY_PIPCONFIG = "PIP Configurations"; - - /** - * String identifier of a file's "Selected" property. - */ - private static String PROPERTY_SELECTED = "Selected"; - - /** - * List of the string identifiers for the available properties. - */ - private static Collection PDP_PROPERTIES; - - private PAPPolicyEngine papEngine = null; - protected List groups = Collections.synchronizedList(new ArrayList()); - - public PDPGroupContainer(PAPPolicyEngine papPolicyEngine) { - super(); - this.setContainer(this); - // - // - // - this.papEngine = (PAPPolicyEngine) papPolicyEngine; - // - // - // - this.refreshGroups(); - } - - public boolean isSupported(Object itemId) { - if (itemId instanceof EcompPDPGroup) { - return true; - } - return false; - } - - public synchronized void refreshGroups() { - synchronized(this.groups) { - this.groups.clear(); - try { - this.groups.addAll(this.papEngine.getEcompPDPGroups()); - } catch (PAPException e) { - String message = "Unable to retrieve Groups from server: " + e; - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); - } - LOGGER.info("refreshGroups"); - } - // - // Notify that we have changed - // - this.fireItemSetChange(); - } - - public List getGroups() { - return Collections.unmodifiableList(this.groups); - } - - public void makeDefault(EcompPDPGroup group) { - try { - this.papEngine.SetDefaultGroup(group); - } catch (PAPException e) { - String message = "Unable to set Default Group on server: " + e; - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); - } - return; - } - - public void removeGroup(EcompPDPGroup group, EcompPDPGroup newGroup) throws PAPException { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("removeGroup: " + group + " new group for PDPs: " + newGroup); - } - if (group.isDefaultGroup()) { - throw new UnsupportedOperationException("You can't remove the Default Group."); - } - try { - this.papEngine.removeGroup(group, newGroup); - } catch (NullPointerException | PAPException e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to removeGroup " + group.getId(), e); - throw new PAPException("Failed to remove group '" + group.getId()+ "'", e); - } - } - - public void removePDP(EcompPDP pdp, EcompPDPGroup group) throws PAPException { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("removePDP: " + pdp + " from group: " + group); - } - try { - this.papEngine.removePDP(pdp); - } catch (PAPException e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to removePDP " + pdp.getId(), e); - throw new PAPException("Failed to remove pdp '" + pdp.getId()+ "'", e); - } - } - - public void updatePDP(EcompPDP pdp) { - try { - papEngine.updatePDP(pdp); - } catch (PAPException e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } - - public void updateGroup(EcompPDPGroup group) { - try { - papEngine.updateGroup(group); - } catch (PAPException e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } - - @Override - public Collection getContainerPropertyIds() { - return PDP_PROPERTIES; - } - - @Override - public Collection getItemIds() { - final Collection items = new ArrayList<>(); - items.addAll(this.groups); - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("getItemIds: " + items); - } - return Collections.unmodifiableCollection(items); - } - - @Override - public Class getType(Object propertyId) { - if (propertyId.equals(PROPERTY_ID)) { - return String.class; - } - if (propertyId.equals(PROPERTY_NAME)) { - return String.class; - } - if (propertyId.equals(PROPERTY_DESCRIPTION)) { - return String.class; - } - if (propertyId.equals(PROPERTY_DEFAULT)) { - return Boolean.class; - } - if (propertyId.equals(PROPERTY_STATUS)) { - return String.class; - } - if (propertyId.equals(PROPERTY_PDPS)) { - return Set.class; - } - if (propertyId.equals(PROPERTY_POLICIES)) { - return Set.class; - } - if (propertyId.equals(PROPERTY_PIPCONFIG)) { - return Set.class; - } - if (propertyId.equals(PROPERTY_SELECTED)) { - return Checkbox.class; - } - return null; - } - - @Override - public int size() { - return this.groups.size(); - } - - @Override - public boolean containsId(Object itemId) { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("containsId: " + itemId); - } - if (this.isSupported(itemId) == false) { - return false; - } - return this.groups.contains(itemId); - } - - @Override - public Object addItem() throws UnsupportedOperationException { - throw new UnsupportedOperationException("PDP Container cannot add a given item."); - } - - public void addNewGroup(String name, String description) throws NullPointerException, PAPException { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("addNewGroup " + name + " " + description); - } - this.papEngine.newGroup(name, description); - } - - public void addNewPDP(String id, EcompPDPGroup group, String name, String description, int jmxport) throws NullPointerException, PAPException { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("addNewPDP " + id + " " + name + " " + description + " " + jmxport); - } - this.papEngine.newPDP(id, group, name, description, jmxport); - } - - public void movePDP(EcompPDP pdp, EcompPDPGroup group) { - try { - this.papEngine.movePDP(pdp, group); - } catch (PAPException e) { - String message = "Unable to move PDP to new group on server: " + e; - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); - } - return; - } - - @Override - public boolean addContainerProperty(Object propertyId, Class type, Object defaultValue) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Cannot add a container property."); - } - - @Override - public boolean removeContainerProperty(Object propertyId) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Cannot remove a container property."); - } - - @Override - public boolean removeAllItems() throws UnsupportedOperationException { - throw new UnsupportedOperationException("PDP Container cannot remove all items. You must have at least the Default group."); - } - - @Override - public void addItemSetChangeListener(ItemSetChangeListener listener) { - if (getItemSetChangeListeners() == null) { - setItemSetChangeListeners(new LinkedList()); - } - getItemSetChangeListeners().add(listener); - } - - @Override - public Object nextItemId(Object itemId) { - if (this.isSupported(itemId) == false) { - return null; - } - int index = this.groups.indexOf(itemId); - if (index == -1) { - // - // We don't know this group - // - return null; - } - // - // Is it the last one? - // - if (index == this.groups.size() - 1) { - // - // Yes - // - return null; - } - // - // Return the next one - // - return this.groups.get(index + 1); - } - - @Override - public Object prevItemId(Object itemId) { - if (this.isSupported(itemId) == false) { - return null; - } - int index = this.groups.indexOf(itemId); - if (index == -1) { - // - // We don't know this group - // - return null; - } - // - // Is it the first one? - // - if (index == 0) { - // - // Yes - // - return null; - } - // - // Return the previous one - // - return this.groups.get(index - 1); - } - - @Override - public Object firstItemId() { - synchronized (this.groups) { - if (this.groups.size() > 0) { - return this.groups.get(0); - } - } - return null; - } - - @Override - public Object lastItemId() { - synchronized (this.groups) { - if (this.groups.size() > 0) { - return this.groups.get(this.groups.size() - 1); - } - } - return null; - } - - @Override - public boolean isFirstId(Object itemId) { - synchronized (this.groups) { - if (this.groups.size() > 0) { - return (this.groups.get(0).equals(itemId)); - } - } - return false; - } - - @Override - public boolean isLastId(Object itemId) { - synchronized (this.groups) { - if (this.groups.size() > 0) { - return (this.groups.get(this.groups.size() - 1).equals(itemId)); - } - } - return false; - } - - @Override - public Object addItemAfter(Object previousItemId) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Cannot addItemAfter, there really is no real ordering."); - } - - @Override - public int indexOfId(Object itemId) { - return this.groups.indexOf(itemId); - } - - @Override - public Object getIdByIndex(int index) { - return this.groups.get(index); - } - - @Override - public List getItemIds(int startIndex, int numberOfItems) { - synchronized (this.groups) { - int endIndex = startIndex + numberOfItems; - if (endIndex > this.groups.size()) { - endIndex = this.groups.size() - 1; - } - return this.groups.subList(startIndex, endIndex); - } - } - - @Override - public Object addItemAt(int index) throws UnsupportedOperationException { - throw new UnsupportedOperationException("Cannot addItemAt"); - } - - @Override - public boolean removeItem(Object itemId) throws UnsupportedOperationException { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("removeItem: " + itemId); - } - if (this.isSupported(itemId) == false) { - return false; - } - // - // You cannot remove the default group - // - if (((EcompPDPGroup) itemId).getId().equals("Default")) { - throw new UnsupportedOperationException("You can't remove the Default Group."); - } - // - // Remove PDPGroup and move any PDP's in it into the default group - // - try { - this.papEngine.removeGroup((EcompPDPGroup) itemId, this.papEngine.getDefaultGroup()); - return true; - } catch (NullPointerException | PAPException e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to remove group", e); - } - return false; - } - - public class PDPGroupItem{ - private final EcompPDPGroup group; - - public PDPGroupItem(EcompPDPGroup itemId) { - this.group = itemId; - } - - public String getId() { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("getId: " + this.group); - } - return this.group.getId(); - } - - public String getName() { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("getName: " + this.group); - } - return this.group.getName(); - } - - public String getDescription() { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("getDescription: " + this.group); - } - return this.group.getDescription(); - } - - public Boolean getDefault() { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("getDefault: " + this.group); - } - return this.group.isDefaultGroup(); - } - - - public String getStatus() { - return this.group.getStatus().getStatus().toString(); - } - - public Set getPDPs() { - return Collections.unmodifiableSet(this.group.getPdps()); - } - - public Set getPolicies() { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("getPolicies: " + this.group); - } - return this.group.getPolicies(); - } - - public Set getPipConfigs() { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("getPIPConfigs: " + this.group); - } - return this.group.getPipConfigs(); - } - } -} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/PDPPolicyContainer.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/PDPPolicyContainer.java deleted file mode 100644 index 1cdf7d6a3..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/PDPPolicyContainer.java +++ /dev/null @@ -1,348 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.model; - - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Set; - -import org.openecomp.policy.utils.PolicyContainer; -import org.openecomp.policy.utils.PolicyItemSetChangeNotifier; -import org.openecomp.policy.common.logging.flexlogger.*; - -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import com.att.research.xacml.api.pap.PDP; -import com.att.research.xacml.api.pap.PDPGroup; -import com.att.research.xacml.api.pap.PDPPolicy; -import org.openecomp.policy.xacml.std.pap.StdPDPPolicy; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class PDPPolicyContainer extends PolicyItemSetChangeNotifier implements PolicyContainer.Indexed { - private static final long serialVersionUID = 1L; - private static Logger LOGGER = FlexLogger.getLogger(PDPPolicyContainer.class); - - /** - * String identifier of a file's "Id" property. - */ - private static String PROPERTY_ID = "Id"; - - /** - * String identifier of a file's "name" property. - */ - private static String PROPERTY_NAME = "Name"; - - /** - * String identifier of a file's "name" property. - */ - private static String PROPERTY_VERSION = "Version"; - - /** - * String identifier of a file's "Description" property. - */ - private static String PROPERTY_DESCRIPTION = "Description"; - - /** - * String identifier of a file's "IsRoot" property. - */ - private static String PROPERTY_ISROOT = "Root"; - - /** - * List of the string identifiers for the available properties. - */ - private static Collection PDPPOLICY_PROPERTIES; - - private final Object data; - private List policies; - - @SuppressWarnings("unchecked") - public PDPPolicyContainer(Object data) { - super(); - this.data = data; - if (this.data instanceof PDPGroup) { - policies = new ArrayList (((PDPGroup) this.data).getPolicies()); - } - if (this.data instanceof PDP) { - policies = new ArrayList (((PDP) this.data).getPolicies()); - } - if (this.data instanceof Set) { - policies = new ArrayList ((Set)data); - } - if (this.policies == null) { - LOGGER.info("NULL policies"); - throw new NullPointerException("PDPPolicyContainer created with unexpected Object type '" + data.getClass().getName() + "'"); - } - this.setContainer(this); - } - - @Override - public Object nextItemId(Object itemId) { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("nextItemId: " + itemId); - } - int index = this.policies.indexOf(itemId); - if (index == -1 || ((index + 1) >= this.policies.size())) { - return null; - } - return new PDPPolicyItem(this.policies.get(index + 1)); - } - - @Override - public Object prevItemId(Object itemId) { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("prevItemId: " + itemId); - } - int index = this.policies.indexOf(itemId); - if (index <= 0) { - return null; - } - return new PDPPolicyItem(this.policies.get(index - 1)); - } - - @Override - public Object firstItemId() { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("firstItemId: "); - } - if (this.policies.isEmpty()) { - return null; - } - return new PDPPolicyItem(this.policies.get(0)); - } - - @Override - public Object lastItemId() { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("lastItemid: "); - } - if (this.policies.isEmpty()) { - return null; - } - return new PDPPolicyItem(this.policies.get(this.policies.size() - 1)); - } - - @Override - public boolean isFirstId(Object itemId) { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("isFirstId: " + itemId); - } - if (this.policies.isEmpty()) { - return false; - } - return (itemId.equals(this.policies.get(0))); - } - - @Override - public boolean isLastId(Object itemId) { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("isLastId: " + itemId); - } - if (this.policies.isEmpty()) { - return false; - } - return (itemId.equals(this.policies.get(this.policies.size() - 1))); - } - - @Override - public Object addItemAfter(Object previousItemId) - throws UnsupportedOperationException { - return null; - } - - @Override - public Collection getContainerPropertyIds() { - return PDPPOLICY_PROPERTIES; - } - - @Override - public Collection getItemIds() { - final Collection items = new ArrayList<>(); - items.addAll(this.policies); - return Collections.unmodifiableCollection(items); - } - - - @Override - public Class getType(Object propertyId) { - if (propertyId.equals(PROPERTY_ID)) { - return String.class; - } - if (propertyId.equals(PROPERTY_NAME)) { - return String.class; - } - if (propertyId.equals(PROPERTY_VERSION)) { - return String.class; - } - if (propertyId.equals(PROPERTY_DESCRIPTION)) { - return String.class; - } - if (propertyId.equals(PROPERTY_ISROOT)) { - return Boolean.class; - } - return null; - } - - @Override - public int size() { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("size: " + this.policies.size()); - } - return this.policies.size(); - } - - @Override - public boolean containsId(Object itemId) { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("containsId: " + itemId); - } - return this.policies.contains(itemId); - } - - @Override - public Object addItem() throws UnsupportedOperationException { - throw new UnsupportedOperationException("Cannot add an empty policy."); - } - - @Override - public boolean removeItem(Object itemId) - throws UnsupportedOperationException { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("removeItem: " + itemId); - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - StdPDPPolicy pdpPolicy = null; - try { - pdpPolicy = mapper.readValue(itemId.toString() , StdPDPPolicy.class); - for(int i = 0; i< policies.size(); i++){ - if(policies.get(i).getId().equalsIgnoreCase(pdpPolicy.getId())){ - return this.policies.remove(this.policies.get(i)); - } - } - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Mapping the Removing Policy from PDP Group to Std Policy"+e); - } - return this.policies.remove(itemId); - } - - @Override - public boolean addContainerProperty(Object propertyId, Class type, - Object defaultValue) throws UnsupportedOperationException { - return false; - } - - @Override - public boolean removeContainerProperty(Object propertyId) - throws UnsupportedOperationException { - return false; - } - - @Override - public boolean removeAllItems() throws UnsupportedOperationException { - return false; - } - - @Override - public int indexOfId(Object itemId) { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("indexOfId: " + itemId); - } - return this.policies.indexOf(itemId); - } - - @Override - public Object getIdByIndex(int index) { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("getIdByIndex: " + index); - } - return this.policies.get(index); - } - - @Override - public List getItemIds(int startIndex, int numberOfItems) { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("getItemIds: " + startIndex + " " + numberOfItems); - } - if (numberOfItems < 0) { - throw new IllegalArgumentException(); - } - return this.policies.subList(startIndex, startIndex + numberOfItems); - } - - @Override - public Object addItemAt(int index) throws UnsupportedOperationException { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("addItemAt: " + index); - } - return null; - } - - public class PDPPolicyItem { - private final PDPPolicy policy; - - public PDPPolicyItem(PDPPolicy itemId) { - this.policy = itemId; - } - - public String getId() { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("getId: " + this.policy); - } - return this.policy.getId(); - } - - public String getName() { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("getName: " + this.policy); - } - return this.policy.getName(); - } - - public String getVersion() { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("getVersion: " + this.policy); - } - return this.policy.getVersion(); - } - - public String getDescription() { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("getDescription: " + this.policy); - } - return this.policy.getDescription(); - } - - public boolean getRoot() { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("isRoot: " + this.policy); - } - return this.policy.isRoot(); - } - - public void setRoot(Boolean root) { - ((StdPDPPolicy)this.policy).setRoot(root); - } - - } -} \ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/Roles.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/Roles.java deleted file mode 100644 index 9cb554a2a..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/Roles.java +++ /dev/null @@ -1,99 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.model; - - -import java.io.Serializable; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.NamedQuery; -import javax.persistence.Table; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -@Entity -@Table(name="Roles") -@NamedQuery(name="Roles.findAll", query="SELECT r FROM Roles r ") -@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) -public class Roles implements Serializable{ - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - - @Column(name="id") - private int id; - - @Column(name="loginId") - private String loginId; - - private String name; - private String scope; - private String role; - - public Roles(){ - - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - public String getLoginId() { - return this.loginId; - } - - public void setLoginId(String loginId) { - this.loginId = loginId; - - } - public String getScope() { - return this.scope; - } - - public void setScope(String scope) { - this.scope = scope; - - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - public String getRole() { - return this.role; - } - - public void setRole(String role) { - this.role = role; - } -} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/ConfigurableRESTUtils.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/ConfigurableRESTUtils.java deleted file mode 100644 index 58d53a1f4..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/ConfigurableRESTUtils.java +++ /dev/null @@ -1,163 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.utils; - - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStreamWriter; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.Map; - -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; - - -public class ConfigurableRESTUtils { - - protected Logger LOGGER = FlexLogger.getLogger(this.getClass()); - - // - // How the value is returned from the RESTful server - // httpResponseCode means the result is simply the HTTP Response code (e.g. 200, 505, etc.) - // other values identify the encoding used for the string in the body of the HTTP response - // - public enum REST_RESPONSE_FORMAT {httpResponseCode, json } - public enum RESQUEST_METHOD { - GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE; - } - - private String ERROR_RECEIVED = "ERROR - Unexpected HTTP response: "; - - public ConfigurableRESTUtils() { - //Default Constructor - } - - - /** - * Call the RESTful API and return a string containing the result. The string may be either a httpResponseCode or json body - * - * @param fullURI - * @param hardCodedHeaders - * @param httpResponseCodes - * @param responseFormat - * @param jsonBody - * @param requestMethod - * @return String - */ - public String sendRESTRequest(String fullURI, Map hardCodedHeaderMap, - Map httpResponseCodeMap, - REST_RESPONSE_FORMAT responseFormat, - String jsonBody, - RESQUEST_METHOD requestMethod ){ - - String responseString = null; - HttpURLConnection connection = null; - try { - - URL url = new URL(fullURI); - - // - // Open up the connection - // - connection = (HttpURLConnection)url.openConnection(); - // - // Setup our method and headers - // - connection.setRequestMethod(requestMethod.toString()); - - connection.setUseCaches(false); - - // add hard-coded headers - for (String headerName : hardCodedHeaderMap.keySet()) { - connection.addRequestProperty(headerName, hardCodedHeaderMap.get(headerName)); - } - - - - if (jsonBody != null){ - connection.setDoInput(true); - connection.setDoOutput(true); - OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); - out.write(jsonBody); - out.flush(); - out.close(); - } else{ - connection.connect(); - } - - int responseCode = connection.getResponseCode(); - - // check that the response is one we expected (and get the associated value at the same time) - responseString = httpResponseCodeMap.get(responseCode); - if (responseString == null) { - // the response was not configured, meaning it is unexpected and therefore an error - LOGGER.error("Unexpected HTTP response code '" + responseCode + "' from RESTful Server"); - return ERROR_RECEIVED + " code" + responseCode + " from RESTful Server"; - } - - // if the response is contained only in the http code we are done. Otherwise we need to read the body - if (responseFormat == REST_RESPONSE_FORMAT.httpResponseCode) { - return responseString; - } - - // Need to read the body and return that as the responseString. - - responseString = null; - // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file) - java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream()); - scanner.useDelimiter("\\A"); - responseString = scanner.hasNext() ? scanner.next() : ""; - scanner.close(); - LOGGER.debug("RESTful body: " + responseString); - return responseString; - - } catch (Exception e) { - LOGGER.error("HTTP Request/Response from RESTFUL server: " + e); - responseString = ERROR_RECEIVED + e; - } finally { - // cleanup the connection - if (connection != null) { - try { - // For some reason trying to get the inputStream from the connection - // throws an exception rather than returning null when the InputStream does not exist. - InputStream is = null; - try { - is = connection.getInputStream(); - } catch (Exception e1) { - LOGGER.error("Exception Occured"+e1); - } - if (is != null) { - is.close(); - } - - } catch (IOException ex) { - LOGGER.error("Failed to close connection: " + ex, ex); - } - connection.disconnect(); - } - } - return responseString; - - } - -} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/PolicyContainer.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/PolicyContainer.java deleted file mode 100644 index fdca336ea..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/PolicyContainer.java +++ /dev/null @@ -1,121 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.utils; - -import java.io.Serializable; -import java.util.Collection; -import java.util.List; - - -public interface PolicyContainer extends Serializable{ - - public Collection getContainerPropertyIds(); - - public Collection getItemIds(); - - public Class getType(Object propertyId); - - public int size(); - - public boolean containsId(Object itemId); - - public Object addItem() throws UnsupportedOperationException; - - public boolean removeItem(Object itemId) - throws UnsupportedOperationException; - - public boolean addContainerProperty(Object propertyId, Class type, - Object defaultValue) throws UnsupportedOperationException; - - public boolean removeContainerProperty(Object propertyId) - throws UnsupportedOperationException; - - public boolean removeAllItems() throws UnsupportedOperationException; - - public interface Ordered extends PolicyContainer { - - public Object nextItemId(Object itemId); - - public Object prevItemId(Object itemId); - - public Object firstItemId(); - - public Object lastItemId(); - - public boolean isFirstId(Object itemId); - - public boolean isLastId(Object itemId); - - public Object addItemAfter(Object previousItemId) - throws UnsupportedOperationException; - - } - - - public interface Indexed extends Ordered { - - public int indexOfId(Object itemId); - - public Object getIdByIndex(int index); - - public List getItemIds(int startIndex, int numberOfItems); - - public Object addItemAt(int index) throws UnsupportedOperationException; - - public interface ItemAddEvent extends ItemSetChangeEvent { - - public Object getFirstItemId(); - - public int getFirstIndex(); - - public int getAddedItemsCount(); - } - - - public interface ItemRemoveEvent extends ItemSetChangeEvent { - - public Object getFirstItemId(); - - public int getFirstIndex(); - - public int getRemovedItemsCount(); - } - } - - public interface ItemSetChangeEvent extends Serializable { - - public PolicyContainer getContainer(); - } - - public interface ItemSetChangeListener extends Serializable { - - public void containerItemSetChange(PolicyContainer.ItemSetChangeEvent event); - } - - public interface ItemSetChangeNotifier extends Serializable { - - public void addItemSetChangeListener( - PolicyContainer.ItemSetChangeListener listener); - - public void removeItemSetChangeListener( - PolicyContainer.ItemSetChangeListener listener); - } -} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/PolicyItemSetChangeNotifier.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/PolicyItemSetChangeNotifier.java deleted file mode 100644 index 934c30564..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/PolicyItemSetChangeNotifier.java +++ /dev/null @@ -1,95 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.utils; - - -import java.io.Serializable; -import java.util.Collection; -import java.util.EventObject; -import java.util.LinkedList; - -import org.openecomp.policy.utils.PolicyContainer.ItemSetChangeEvent; -import org.openecomp.policy.utils.PolicyContainer.ItemSetChangeListener; - - - -public class PolicyItemSetChangeNotifier implements PolicyContainer.ItemSetChangeNotifier { - private static final long serialVersionUID = 1L; - private Collection itemSetChangeListeners = null; - private PolicyContainer container = null; - - public PolicyItemSetChangeNotifier() { - } - - protected void setContainer(PolicyContainer c) { - this.container = c; - } - - @Override - public void addItemSetChangeListener(ItemSetChangeListener listener) { - if (getItemSetChangeListeners() == null) { - setItemSetChangeListeners(new LinkedList()); - } - getItemSetChangeListeners().add(listener); } - - @Override - public void removeItemSetChangeListener(ItemSetChangeListener listener) { - if (getItemSetChangeListeners() != null) { - getItemSetChangeListeners().remove(listener); - } - } - - protected static class BaseItemSetChangeEvent extends EventObject implements - PolicyContainer.ItemSetChangeEvent, Serializable { - private static final long serialVersionUID = 1L; - - protected BaseItemSetChangeEvent(PolicyContainer source) { - super(source); - } - - @Override - public PolicyContainer getContainer() { - return (PolicyContainer) getSource(); - } - } - - protected void setItemSetChangeListeners( - Collection itemSetChangeListeners) { - this.itemSetChangeListeners = itemSetChangeListeners; - } - protected Collection getItemSetChangeListeners() { - return itemSetChangeListeners; - } - - protected void fireItemSetChange() { - fireItemSetChange(new BaseItemSetChangeEvent(this.container)); - } - - protected void fireItemSetChange(ItemSetChangeEvent event) { - if (getItemSetChangeListeners() != null) { - final Object[] l = getItemSetChangeListeners().toArray(); - for (int i = 0; i < l.length; i++) { - ((PolicyContainer.ItemSetChangeListener) l[i]) - .containerItemSetChange(event); - } - } - } -} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/XACMLPolicyWriterWithPapNotify.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/XACMLPolicyWriterWithPapNotify.java deleted file mode 100644 index 0abd874f6..000000000 --- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/XACMLPolicyWriterWithPapNotify.java +++ /dev/null @@ -1,483 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP Policy Engine - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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.openecomp.policy.utils; - - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.ProtocolException; -import java.net.URL; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.nio.file.DirectoryNotEmptyException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Base64; -import java.util.UUID; - -import org.openecomp.policy.rest.XACMLRestProperties; - -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.openecomp.policy.xacml.util.XACMLPolicyWriter; -import com.att.research.xacml.util.XACMLProperties; - -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.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; - -/** - * Helper static class that wraps XACMLPolicyWriter - * - * - */ -public class XACMLPolicyWriterWithPapNotify{ - private static final Logger LOGGER = FlexLogger.getLogger(XACMLPolicyWriterWithPapNotify.class); - - /** - * Helper static class that does the work to write a policy set to a file on disk and notify PAP - * - * - */ - public static Path writePolicyFile(Path filename, PolicySetType policySet) { - if(LOGGER.isDebugEnabled()){ - LOGGER.debug("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet)" - + "\nfilename = " + filename - + "\npolicySet = " + policySet); - } - //write to file - Path path = XACMLPolicyWriter.writePolicyFile(filename, policySet); - - if(path!=null){ - //write to DB - if(notifyPapOfCreateUpdate(filename.toAbsolutePath().toString())){ - return path; - }else{ - //write to DB failed. So, delete the file - try{ - Files.deleteIfExists(path); - }catch(DirectoryNotEmptyException e){ - //We are trying to delete a directory and it is not empty - LOGGER.error("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet): Files.deleteIfExists(path)" - + "\nDirectoryNotEmptyException for path = " + path - + "\nException message = " + e); - }catch(IOException e) { - // File permission problems are caught here. - LOGGER.error("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet): Files.deleteIfExists(path)" - + "\nIOException for path = " + path - + "\nException message = " + e); - }catch(Exception e){ - LOGGER.error("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet): Files.deleteIfExists(path)" - + "\nException for path = " + path - + "\nException message = " + e); - } - return null; - } - - }else{ - return null; - } - } - - /** - * Helper static class that does the work to write a policy set to an output stream and notify PAP - * - * - */ - public static void writePolicyFile(OutputStream os, PolicySetType policySet) { - if(LOGGER.isDebugEnabled()){ - LOGGER.debug("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(OutputStream os, PolicySetType policySet)" - + "\nos = " + os - + "\npolicySet = " + policySet); - } - //Only used for writing a byte array output stream for a message. No file is written - XACMLPolicyWriter.writePolicyFile(os, policySet); - } - - /** - * Helper static class that does the work to write a policy to a file on disk. - * - * - */ - public static Path writePolicyFile(Path filename, PolicyType policy) { - if(LOGGER.isDebugEnabled()){ - LOGGER.debug("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicyType policy)" - + "\nfilename = " + filename - + "\npolicy = " + policy); - } - - //write to file - Path path = XACMLPolicyWriter.writePolicyFile(filename, policy); - - if(path!=null){ - //write to DB - if(notifyPapOfCreateUpdate(filename.toAbsolutePath().toString())){ - return path; - }else{ - //write to DB failed so delete the file - try{ - Files.deleteIfExists(path); - }catch(DirectoryNotEmptyException e){ - //We are trying to delete a directory and it is not empty - LOGGER.error("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet)Files.deleteIfExists(path) :" - + "\nDirectoryNotEmptyException for path = " + path - + "\nException message = " + e); - }catch(IOException e) { - // File permission problems are caught here. - LOGGER.error("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet): Files.deleteIfExists(path)" - + "\nIOException for path = " + path - + "\nException message = " + e); - }catch(Exception e){ - LOGGER.error("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet): Files.deleteIfExists(path)" - + "\nException for path = " + path - + "\nException message = " + e); - } - return null; - } - - }else{ - return null; - } - } - - - /** - * Helper static class that does the work to write a policy to a file on disk. - * - * - */ - public static InputStream getXmlAsInputStream(PolicyType policy) { - if(LOGGER.isDebugEnabled()){ - LOGGER.debug("\nXACMLPolicyWriterWithPapNotify.getXmlAsInputStream(PolicyType policy)" - + "\npolicy = " + policy); - } - return XACMLPolicyWriter.getXmlAsInputStream(policy); - } - /** - * Helper static class that does the work to write a policy set to an output stream. - * - * - */ - public static void writePolicyFile(OutputStream os, PolicyType policy) { - if(LOGGER.isDebugEnabled()){ - LOGGER.debug("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(OutputStream os, PolicyType policy)" - + "\nos = " + os - + "\npolicy = " + policy); - } - //There are no references to this and if there were, it would most likely be used in an http message - XACMLPolicyWriter.writePolicyFile(os, policy); - } - - public static String changeFileNameInXmlWhenRenamePolicy(Path filename) { - if(LOGGER.isDebugEnabled()){ - LOGGER.debug("\nXACMLPolicyWriterWithPapNotify.changeFileNameInXmlWhenRenamePolicy(Path filename)" - + "\nfilename = " + filename); - } - return XACMLPolicyWriter.changeFileNameInXmlWhenRenamePolicy(filename); - } - - public static boolean notifyPapOfPolicyRename(String oldPolicyName, String newPolicyName){ - if(LOGGER.isDebugEnabled()){ - LOGGER.debug("\nXACMLPolicyWriterWithPapNotify.notifyPapOfCreateUpdate(String policyToCreateUpdate) " - + "\npolicyToCreateUpdate = " + " "); - } - Base64.Encoder encoder = Base64.getEncoder(); - String encoding = encoder.encodeToString((XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID)+":"+XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)).getBytes(StandardCharsets.UTF_8)); - HttpURLConnection connection = null; - UUID requestID = UUID.randomUUID(); - URL url; - try { - url = new URL(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL)+"?oldPolicyName="+ URLEncoder.encode(oldPolicyName, "UTF-8")+"&newPolicyName="+URLEncoder.encode(newPolicyName,"UTF-8")); - if(LOGGER.isDebugEnabled()){ - LOGGER.debug("\nnotifyPapOfCreateUpdate: URL = " + url); - } - } catch (MalformedURLException e) { - LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" - + "\nMalformedURLException message = " + e); - - return false; - } catch (UnsupportedEncodingException e) { - LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" - + "\nUnsupportedEncodingException message = " + e); - - return false; - } - // - // Open up the connection - // - try { - connection = (HttpURLConnection)url.openConnection(); - } catch (IOException e) { - LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" - + "\nurl.openConnection() IOException message = " + e); - return false; - } - // - // Setup our method and headers - // - try { - connection.setRequestMethod("PUT"); - } catch (ProtocolException e) { - LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" - + "\nconnection.setRequestMethod(PUT) ProtocolException message = " + e); - connection.disconnect(); - return false; - } - connection.setRequestProperty("Authorization", "Basic " + encoding); - connection.setRequestProperty("Accept", "text/x-java-properties"); - connection.setRequestProperty("Content-Type", "text/x-java-properties"); - connection.setRequestProperty("requestID", requestID.toString()); - connection.setUseCaches(false); - // - // Adding this in. It seems the HttpUrlConnection class does NOT - // properly forward our headers for POST re-direction. It does so - // for a GET re-direction. - // - // So we need to handle this ourselves. - // - connection.setInstanceFollowRedirects(false); - connection.setDoOutput(true); - connection.setDoInput(true); - try { - connection.connect(); - } catch (IOException e) { - LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" - + "\nconnection.connect() IOException message = " + e); - connection.disconnect(); - return false; - } - try { - int responseCode = connection.getResponseCode(); - if(LOGGER.isDebugEnabled()){ - LOGGER.debug("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" - + "\nconnection.getResponseCode() = " + responseCode); - } - if (responseCode == 200) { - connection.disconnect(); - return true; - } else { - connection.disconnect(); - return false; - } - } catch (IOException e) { - LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" - + "\nconnection.getResponseCode() IOException message = " + e); - connection.disconnect(); - return false; - } - } - - public static boolean notifyPapOfDelete(String policyToDelete){ - Base64.Encoder encoder = Base64.getEncoder(); - String encoding = encoder.encodeToString((XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID)+":"+XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)).getBytes(StandardCharsets.UTF_8)); - HttpURLConnection connection = null; - UUID requestID = UUID.randomUUID(); - //loggingContext.setRequestID(requestID.toString()); - //loggingContext.transactionStarted(); - String papUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); - if(papUrl == null){ - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + - "PAP url property does not exist"); - return false; - } - String urlString = ""; - try{ - urlString = papUrl+"?groupId=0&isDeleteNotify=1&policyToDelete="+ URLEncoder.encode(policyToDelete, "UTF-8"); - } catch(UnsupportedEncodingException e){ - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + - "Invalid encoding: UTF-8", e); - return false; - } - URL url; - try { - url = new URL(urlString); - } catch (MalformedURLException e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + - "Error parsing PAP url: " - + urlString - , e); - return false; - } - // - // Open up the connection - // - try { - connection = (HttpURLConnection)url.openConnection(); - } catch (IOException e) { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + - "Error opening HttpURLConnection to: " - + url.toString() - , e); - return false; - } - // - // Setup our method and headers - // - try { - connection.setRequestMethod("DELETE"); - } catch (ProtocolException e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + - "Invalid request method: DELETE", e); - connection.disconnect(); - return false; - } - connection.setRequestProperty("Authorization", "Basic " + encoding); - connection.setRequestProperty("Accept", "text/x-java-properties"); - connection.setRequestProperty("Content-Type", "text/x-java-properties"); - connection.setRequestProperty("requestID", requestID.toString()); - connection.setUseCaches(false); - // - // Adding this in. It seems the HttpUrlConnection class does NOT - // properly forward our headers for POST re-direction. It does so - // for a GET re-direction. - // - // So we need to handle this ourselves. - // - connection.setInstanceFollowRedirects(false); - connection.setDoOutput(true); - connection.setDoInput(true); - try { - connection.connect(); - } catch (IOException e) { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + - "Error connecting HttpURLConnection to: " - + connection.getURL().toString() - , e); - connection.disconnect(); - return false; - } - try { - if (connection.getResponseCode() == 200) { - connection.disconnect(); - //worked - return true; - } else { - connection.disconnect(); - return false; - } - } catch (IOException e) { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + - "Error getting HttpUrlConnection response code for: " - + connection.getURL().toString() - , e); - connection.disconnect(); - return false; - } - } - - public static boolean notifyPapOfCreateUpdate(String policyToCreateUpdate){ - if(LOGGER.isDebugEnabled()){ - LOGGER.debug("\nXACMLPolicyWriterWithPapNotify.notifyPapOfCreateUpdate(String policyToCreateUpdate) " - + "\npolicyToCreateUpdate = " + policyToCreateUpdate); - } - Base64.Encoder encoder = Base64.getEncoder(); - String encoding = encoder.encodeToString((XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID)+":"+XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)).getBytes(StandardCharsets.UTF_8)); - HttpURLConnection connection = null; - UUID requestID = UUID.randomUUID(); - //loggingContext.setRequestID(requestID.toString()); - //loggingContext.transactionStarted(); - URL url; - try { - url = new URL(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL)+"?policyToCreateUpdate="+ URLEncoder.encode(policyToCreateUpdate, "UTF-8")); - if(LOGGER.isDebugEnabled()){ - LOGGER.debug("\nnotifyPapOfCreateUpdate: URL = " + url); - } - } catch (MalformedURLException e) { - LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" - + "\nMalformedURLException message = " + e); - - return false; - } catch (UnsupportedEncodingException e) { - LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" - + "\nUnsupportedEncodingException message = " + e); - - return false; - } - // - // Open up the connection - // - try { - connection = (HttpURLConnection)url.openConnection(); - } catch (IOException e) { - LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" - + "\nurl.openConnection() IOException message = " + e); - return false; - } - // - // Setup our method and headers - // - try { - connection.setRequestMethod("PUT"); - } catch (ProtocolException e) { - LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" - + "\nconnection.setRequestMethod(PUT) ProtocolException message = " + e); - connection.disconnect(); - return false; - } - connection.setRequestProperty("Authorization", "Basic " + encoding); - connection.setRequestProperty("Accept", "text/x-java-properties"); - connection.setRequestProperty("Content-Type", "text/x-java-properties"); - connection.setRequestProperty("requestID", requestID.toString()); - connection.setUseCaches(false); - // - // Adding this in. It seems the HttpUrlConnection class does NOT - // properly forward our headers for POST re-direction. It does so - // for a GET re-direction. - // - // So we need to handle this ourselves. - // - connection.setInstanceFollowRedirects(false); - connection.setDoOutput(true); - connection.setDoInput(true); - try { - connection.connect(); - } catch (IOException e) { - LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" - + "\nconnection.connect() IOException message = " + e); - connection.disconnect(); - return false; - } - try { - int responseCode = connection.getResponseCode(); - if(LOGGER.isDebugEnabled()){ - LOGGER.debug("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" - + "\nconnection.getResponseCode() = " + responseCode); - } - if (responseCode == 200) { - connection.disconnect(); - return true; - } else { - connection.disconnect(); - return false; - } - } catch (IOException e) { - LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" - + "\nconnection.getResponseCode() IOException message = " + e); - connection.disconnect(); - return false; - } - } -} diff --git a/POLICY-SDK-APP/src/main/webapp/WEB-INF/conf/system.properties b/POLICY-SDK-APP/src/main/webapp/WEB-INF/conf/system.properties index cc0b602cc..43b2de708 100644 --- a/POLICY-SDK-APP/src/main/webapp/WEB-INF/conf/system.properties +++ b/POLICY-SDK-APP/src/main/webapp/WEB-INF/conf/system.properties @@ -1,4 +1,4 @@ -# Properties read by ECOMP Core library, ecompSDK-core.jar +# Properties read by ONAP Core library, onapSDK-core.jar ########################################################################## # The following properties should NOT be changed by partner applications. @@ -24,7 +24,7 @@ decryption_key = AGLDdG4D04BKm2IxIWEr8o== ########################################################################## #Mysql db.driver = com.mysql.jdbc.Driver -db.connectionURL = jdbc:mysql://localhost:3306/ecompsdk1707 +db.connectionURL = jdbc:mysql://localhost:3306/onapsdk1707 db.userName = root db.password = db.hib.dialect = org.hibernate.dialect.MySQLDialect @@ -49,8 +49,8 @@ mylogins_feed_cron = 0 0/60 * * * ?; #sessiontimeout_feed_cron = 0 * * * * ? * my_login_feed_output_dir = /tmp/MyLogins -# ECOMP Portal Shared Context REST API URL -ecomp_shared_context_rest_url= todo_add_Shared_context_rest_url +# ONAP Portal Shared Context REST API URL +onap_shared_context_rest_url= todo_add_Shared_context_rest_url # Link shown in Help menu contact_us_link = todo_Add_contact_link @@ -60,7 +60,7 @@ camunda_cockpit_link = todo_Add_camunda_cockpit_link # An Unique 128-bit value defined to identify a specific version # of an application deployed on a specific virtual machine. # This value must be generated and updated by the application -# which is using the ECOMP SDK at the time of its deployment. +# which is using the ONAP SDK at the time of its deployment. # Online Unique UUID generator - https://www.uuidgenerator.net/ instance_uuid=8da691c9-987d-43ed-a358-00ac2f35685d diff --git a/POLICY-SDK-APP/src/main/webapp/WEB-INF/fusion/orm/RNoteBookIntegration.hbm.xml b/POLICY-SDK-APP/src/main/webapp/WEB-INF/fusion/orm/RNoteBookIntegration.hbm.xml index 6638b4bc7..984e2369b 100644 --- a/POLICY-SDK-APP/src/main/webapp/WEB-INF/fusion/orm/RNoteBookIntegration.hbm.xml +++ b/POLICY-SDK-APP/src/main/webapp/WEB-INF/fusion/orm/RNoteBookIntegration.hbm.xml @@ -1,7 +1,7 @@ diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/UIGrid/ui-grid.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/UIGrid/ui-grid.js index 363a54596..af636803d 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/UIGrid/ui-grid.js +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/UIGrid/ui-grid.js @@ -272,7 +272,7 @@ angular.module('ui.grid').directive('uiGridCell', ['$compile', '$parse', 'gridUt // No controller, compile the element manually (for unit tests) else { if ( uiGridCtrl && !$scope.col.compiledElementFn ){ - // gridUtil.logError('Render has been called before precompile. Please log a ui-grid issue'); + // gridUtil.logError('Render has been called before pronapile. Please log a ui-grid issue'); $scope.col.getCompiledElementFn() .then(function (compiledElementFn) { @@ -4658,7 +4658,7 @@ angular.module('ui.grid') * @ngdoc function * @name preCompileCellTemplates * @methodOf ui.grid.class:Grid - * @description precompiles all cell templates + * @description pronapiles all cell templates */ Grid.prototype.preCompileCellTemplates = function() { var self = this; @@ -8110,7 +8110,7 @@ angular.module('ui.grid') *
      $scope.gridOptions.headerTemplate = 'header_template.html';
    * inline html *
      $scope.gridOptions.headerTemplate = '
    I am a Custom Grid Header
    '
    - * or the id of a precompiled template (TBD how to use this). + * or the id of a pronapiled template (TBD how to use this). *
    Refer to the custom header tutorial for more information. * If you want no header at all, you can set to an empty div: *
      $scope.gridOptions.headerTemplate = '
    ';
    @@ -8130,7 +8130,7 @@ angular.module('ui.grid') * aggregation totals. * When provided, this setting uses a custom footer template. Can be set to either the name of a template file 'footer_template.html', inline html *
    '
    I am a Custom Grid Footer
    '
    , or the id - * of a precompiled template (TBD how to use this). Refer to the custom footer tutorial for more information. + * of a pronapiled template (TBD how to use this). Refer to the custom footer tutorial for more information. */ baseOptions.footerTemplate = baseOptions.footerTemplate || 'ui-grid/ui-grid-footer'; @@ -8152,7 +8152,7 @@ angular.module('ui.grid') *
     $scope.gridOptions.rowTemplate = 'row_template.html';
    * inline html *
      $scope.gridOptions.rowTemplate = '
    ';
    - * or the id of a precompiled template (TBD how to use this) can be provided. + * or the id of a pronapiled template (TBD how to use this) can be provided. *
    Refer to the custom row template tutorial for more information. */ baseOptions.rowTemplate = baseOptions.rowTemplate || 'ui-grid/ui-grid-row'; diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/b2b-angular.css b/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/b2b-angular.css index a894691ca..a2d43a1d3 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/b2b-angular.css +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/b2b-angular.css @@ -73,7 +73,7 @@ .b2b-subnav-content > li li > a.active { color: #0574ac; text-decoration: none; - font-family: "Omnes-ECOMP-W02", Arial; } } + font-family: "Omnes-ONAP-W02", Arial; } } .b2b-list-box-item { white-space: nowrap; @@ -404,7 +404,7 @@ color: #009fdb; font-size: 18px; font-style: normal; - font-family: "Omnes-ECOMP-W02-Medium", Arial; + font-family: "Omnes-ONAP-W02-Medium", Arial; line-height: 23.9px; margin: 0; } .b2b-footer-container .footer-columns li { @@ -414,7 +414,7 @@ .b2b-footer-container .footer-columns li a { color: #fff; font-size: 16px; - font-family: "Omnes-ECOMP-W02", Arial; } + font-family: "Omnes-ONAP-W02", Arial; } .b2b-footer-container .footer-nav-content { padding-bottom: 10px; } .b2b-footer-container .footer-nav-content li { @@ -427,7 +427,7 @@ font-size: 14px; vertical-align: middle; margin-right: 5px; - font-family: "Omnes-ECOMP-W02", Arial; } + font-family: "Omnes-ONAP-W02", Arial; } .b2b-footer-wrapper .b2b-footer-container hr { background: #d2d2d2; @@ -454,7 +454,7 @@ color: #fff; font-size: 11px; text-align: left; - font-family: "Omnes-ECOMP-W02", Arial; } + font-family: "Omnes-ONAP-W02", Arial; } .b2b-footer-wrapper .copyright-text a { color: #fff; text-decoration: underline; @@ -512,9 +512,9 @@ top: 0; transition: none; } .btn-switch input[type="checkbox"] + .switch-overlay .btn-slider-on .activo { - font: 0px/0 "Omnes-ECOMP-W02", Arial; } + font: 0px/0 "Omnes-ONAP-W02", Arial; } .btn-switch input[type="checkbox"] + .switch-overlay .btn-slider-on + .btn + .btn-slider-off .inactivo { - font: 0px/0 "Omnes-ECOMP-W02", Arial; } + font: 0px/0 "Omnes-ONAP-W02", Arial; } .btn-switch input:checked + .switch-overlay { left: 0; transition: all .3s linear .0s; } @@ -581,7 +581,7 @@ .btn-switch input[type="checkbox"][disabled] + .switch-overlay .btn-slider-on .activo { border: medium none; color: #666; - font: 16px/32px "Omnes-ECOMP-W02", Arial; + font: 16px/32px "Omnes-ONAP-W02", Arial; height: auto; margin: 0 auto; width: auto; } @@ -595,7 +595,7 @@ .btn-switch input[type="checkbox"][disabled] + .switch-overlay .btn-slider-on + .switch-handle + .btn-slider-off .inactivo { border: medium none; color: #666; - font: 16px/32px "Omnes-ECOMP-W02", Arial; + font: 16px/32px "Omnes-ONAP-W02", Arial; height: auto; margin: 0 auto; width: auto; } @@ -628,7 +628,7 @@ text-align: left; padding-left: 12px; display: inline-block; - font-family: "Omnes-ECOMP-W02", Arial; + font-family: "Omnes-ONAP-W02", Arial; height: 32px; line-height: 32px; position: absolute; @@ -637,7 +637,7 @@ .btn-slider-off { display: inline-block; - font-family: "Omnes-ECOMP-W02", Arial; + font-family: "Omnes-ONAP-W02", Arial; height: 32px; line-height: 32px; position: absolute; @@ -708,7 +708,7 @@ text-align: left; width: auto; font-size: 14px; - font-family: "Omnes-ECOMP-W02", Arial; + font-family: "Omnes-ONAP-W02", Arial; cursor: pointer; padding: 0 15px 4px 15px; /*margin-top:-3px;*/ @@ -841,7 +841,7 @@ .b2b-header-tabs .header-quarternary li { padding-left: 15px; - font-family: "Omnes-ECOMP-W02", Arial; + font-family: "Omnes-ONAP-W02", Arial; display: none; } .b2b-header-tabs .header-quarternary li.active { diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/docs/_includes/getting-started/download.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/docs/_includes/getting-started/download.html index 290731fae..89ec1485c 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/docs/_includes/getting-started/download.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/docs/_includes/getting-started/download.html @@ -51,9 +51,9 @@

    Bootstrap's package.json contains some additional metadata under the following keys:

    • less - path to Bootstrap's main Less source file
    • -
    • style - path to Bootstrap's non-minified CSS that's been precompiled using the default settings (no customization)
    • +
    • style - path to Bootstrap's non-minified CSS that's been pronapiled using the default settings (no customization)

    Autoprefixer required for Less/Sass

    -

    Bootstrap uses Autoprefixer to deal with CSS vendor prefixes. If you're compiling Bootstrap from its Less/Sass source and not using our Gruntfile, you'll need to integrate Autoprefixer into your build process yourself. If you're using precompiled Bootstrap or using our Gruntfile, you don't need to worry about this because Autoprefixer is already integrated into our Gruntfile.

    +

    Bootstrap uses Autoprefixer to deal with CSS vendor prefixes. If you're compiling Bootstrap from its Less/Sass source and not using our Gruntfile, you'll need to integrate Autoprefixer into your build process yourself. If you're using pronapiled Bootstrap or using our Gruntfile, you don't need to worry about this because Autoprefixer is already integrated into our Gruntfile.

    diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/docs/_includes/getting-started/grunt.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/docs/_includes/getting-started/grunt.html index a700c2f03..f1cb18427 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/docs/_includes/getting-started/grunt.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/docs/_includes/getting-started/grunt.html @@ -19,7 +19,7 @@

    Regenerates the /dist/ directory with compiled and minified CSS and JavaScript files. As a Bootstrap user, this is normally the command you want.

    grunt watch (Watch)

    -

    Watches the Less source files and automatically recompiles them to CSS whenever you save a change.

    +

    Watches the Less source files and automatically ronapiles them to CSS whenever you save a change.

    grunt test (Run tests)

    Runs JSHint and runs the QUnit tests headlessly in PhantomJS.

    diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/docs/_includes/getting-started/whats-included.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/docs/_includes/getting-started/whats-included.html index 8aa8cf2a9..a05db45c9 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/docs/_includes/getting-started/whats-included.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/docs/_includes/getting-started/whats-included.html @@ -8,7 +8,7 @@

    Please note that all JavaScript plugins require jQuery to be included, as shown in the starter template. Consult our bower.json to see which versions of jQuery are supported.

    -

    Precompiled Bootstrap

    +

    Pronapiled Bootstrap

    Once downloaded, unzip the compressed folder to see the structure of (the compiled) Bootstrap. You'll see something like this:

    @@ -33,10 +33,10 @@ bootstrap/ {% endhighlight %} -

    This is the most basic form of Bootstrap: precompiled files for quick drop-in usage in nearly any web project. We provide compiled CSS and JS (bootstrap.*), as well as compiled and minified CSS and JS (bootstrap.min.*). CSS source maps (bootstrap.*.map) are available for use with certain browsers' developer tools. Fonts from Glyphicons are included, as is the optional Bootstrap theme.

    +

    This is the most basic form of Bootstrap: pronapiled files for quick drop-in usage in nearly any web project. We provide compiled CSS and JS (bootstrap.*), as well as compiled and minified CSS and JS (bootstrap.min.*). CSS source maps (bootstrap.*.map) are available for use with certain browsers' developer tools. Fonts from Glyphicons are included, as is the optional Bootstrap theme.

    Bootstrap source code

    -

    The Bootstrap source code download includes the precompiled CSS, JavaScript, and font assets, along with source Less, JavaScript, and documentation. More specifically, it includes the following and more:

    +

    The Bootstrap source code download includes the pronapiled CSS, JavaScript, and font assets, along with source Less, JavaScript, and documentation. More specifically, it includes the following and more:

    {% highlight bash %} bootstrap/ ├── less/ @@ -49,5 +49,5 @@ bootstrap/ └── docs/ └── examples/ {% endhighlight %} -

    The less/, js/, and fonts/ are the source code for our CSS, JS, and icon fonts (respectively). The dist/ folder includes everything listed in the precompiled download section above. The docs/ folder includes the source code for our documentation, and examples/ of Bootstrap usage. Beyond that, any other included file provides support for packages, license information, and development.

    +

    The less/, js/, and fonts/ are the source code for our CSS, JS, and icon fonts (respectively). The dist/ folder includes everything listed in the pronapiled download section above. The docs/ folder includes the source code for our documentation, and examples/ of Bootstrap usage. Beyond that, any other included file provides support for packages, license information, and development.

    diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/docs/_includes/nav/getting-started.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/docs/_includes/nav/getting-started.html index 4a07fe79c..f983d47c5 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/docs/_includes/nav/getting-started.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/docs/_includes/nav/getting-started.html @@ -4,7 +4,7 @@
  • What's included
  • diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/docs/assets/js/customize.min.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/docs/assets/js/customize.min.js index 877085c06..83c69598a 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/docs/assets/js/customize.min.js +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/docs/assets/js/customize.min.js @@ -58,7 +58,7 @@ Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/js JSZip uses the library pako released under the MIT license : https://github.com/nodeca/pako/blob/master/LICENSE */ -!function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;"undefined"!=typeof window?b=window:"undefined"!=typeof global?b=global:"undefined"!=typeof self&&(b=self),b.JSZip=a()}}(function(){return function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);throw new Error("Cannot find module '"+g+"'")}var j=c[g]={exports:{}};b[g][0].call(j.exports,function(a){var c=b[g][1][a];return e(c?c:a)},j,j.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g>2,g=(3&b)<<4|c>>4,h=(15&c)<<2|e>>6,i=63&e,isNaN(c)?h=i=64:isNaN(e)&&(i=64),j=j+d.charAt(f)+d.charAt(g)+d.charAt(h)+d.charAt(i);return j},c.decode=function(a){var b,c,e,f,g,h,i,j="",k=0;for(a=a.replace(/[^A-Za-z0-9\+\/\=]/g,"");k>4,c=(15&g)<<4|h>>2,e=(3&h)<<6|i,j+=String.fromCharCode(b),64!=h&&(j+=String.fromCharCode(c)),64!=i&&(j+=String.fromCharCode(e));return j}},{}],2:[function(a,b){"use strict";function c(){this.compressedSize=0,this.uncompressedSize=0,this.crc32=0,this.compressionMethod=null,this.compressedContent=null}c.prototype={getContent:function(){return null},getCompressedContent:function(){return null}},b.exports=c},{}],3:[function(a,b,c){"use strict";c.STORE={magic:"\x00\x00",compress:function(a){return a},uncompress:function(a){return a},compressInputType:null,uncompressInputType:null},c.DEFLATE=a("./flate")},{"./flate":8}],4:[function(a,b){"use strict";var c=a("./utils"),d=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117];b.exports=function(a,b){if("undefined"==typeof a||!a.length)return 0;var e="string"!==c.getTypeOf(a);"undefined"==typeof b&&(b=0);var f=0,g=0,h=0;b=-1^b;for(var i=0,j=a.length;j>i;i++)h=e?a[i]:a.charCodeAt(i),g=255&(b^h),f=d[g],b=b>>>8^f;return-1^b}},{"./utils":21}],5:[function(a,b){"use strict";function c(){this.data=null,this.length=0,this.index=0}var d=a("./utils");c.prototype={checkOffset:function(a){this.checkIndex(this.index+a)},checkIndex:function(a){if(this.lengtha)throw new Error("End of data reached (data length = "+this.length+", asked index = "+a+"). Corrupted zip ?")},setIndex:function(a){this.checkIndex(a),this.index=a},skip:function(a){this.setIndex(this.index+a)},byteAt:function(){},readInt:function(a){var b,c=0;for(this.checkOffset(a),b=this.index+a-1;b>=this.index;b--)c=(c<<8)+this.byteAt(b);return this.index+=a,c},readString:function(a){return d.transformTo("string",this.readData(a))},readData:function(){},lastIndexOfSignature:function(){},readDate:function(){var a=this.readInt(4);return new Date((a>>25&127)+1980,(a>>21&15)-1,a>>16&31,a>>11&31,a>>5&63,(31&a)<<1)}},b.exports=c},{"./utils":21}],6:[function(a,b,c){"use strict";c.base64=!1,c.binary=!1,c.dir=!1,c.createFolders=!1,c.date=null,c.compression=null,c.comment=null},{}],7:[function(a,b,c){"use strict";var d=a("./utils");c.string2binary=function(a){return d.string2binary(a)},c.string2Uint8Array=function(a){return d.transformTo("uint8array",a)},c.uint8Array2String=function(a){return d.transformTo("string",a)},c.string2Blob=function(a){var b=d.transformTo("arraybuffer",a);return d.arrayBuffer2Blob(b)},c.arrayBuffer2Blob=function(a){return d.arrayBuffer2Blob(a)},c.transformTo=function(a,b){return d.transformTo(a,b)},c.getTypeOf=function(a){return d.getTypeOf(a)},c.checkSupport=function(a){return d.checkSupport(a)},c.MAX_VALUE_16BITS=d.MAX_VALUE_16BITS,c.MAX_VALUE_32BITS=d.MAX_VALUE_32BITS,c.pretty=function(a){return d.pretty(a)},c.findCompression=function(a){return d.findCompression(a)},c.isRegExp=function(a){return d.isRegExp(a)}},{"./utils":21}],8:[function(a,b,c){"use strict";var d="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array,e=a("pako");c.uncompressInputType=d?"uint8array":"array",c.compressInputType=d?"uint8array":"array",c.magic="\b\x00",c.compress=function(a){return e.deflateRaw(a)},c.uncompress=function(a){return e.inflateRaw(a)}},{pako:24}],9:[function(a,b){"use strict";function c(a,b){return this instanceof c?(this.files={},this.comment=null,this.root="",a&&this.load(a,b),void(this.clone=function(){var a=new c;for(var b in this)"function"!=typeof this[b]&&(a[b]=this[b]);return a})):new c(a,b)}var d=a("./base64");c.prototype=a("./object"),c.prototype.load=a("./load"),c.support=a("./support"),c.defaults=a("./defaults"),c.utils=a("./deprecatedPublicUtils"),c.base64={encode:function(a){return d.encode(a)},decode:function(a){return d.decode(a)}},c.compressions=a("./compressions"),b.exports=c},{"./base64":1,"./compressions":3,"./defaults":6,"./deprecatedPublicUtils":7,"./load":10,"./object":13,"./support":17}],10:[function(a,b){"use strict";var c=a("./base64"),d=a("./zipEntries");b.exports=function(a,b){var e,f,g,h;for(b=b||{},b.base64&&(a=c.decode(a)),f=new d(a,b),e=f.files,g=0;gc;c++)d+=String.fromCharCode(255&a),a>>>=8;return d},t=function(){var a,b,c={};for(a=0;a0?a.substring(0,b):""},x=function(a,b){return"/"!=a.slice(-1)&&(a+="/"),b="undefined"!=typeof b?b:!1,this.files[a]||v.call(this,a,null,{dir:!0,createFolders:b}),this.files[a]},y=function(a,b){var c,f=new j;return a._data instanceof j?(f.uncompressedSize=a._data.uncompressedSize,f.crc32=a._data.crc32,0===f.uncompressedSize||a.dir?(b=i.STORE,f.compressedContent="",f.crc32=0):a._data.compressionMethod===b.magic?f.compressedContent=a._data.getCompressedContent():(c=a._data.getContent(),f.compressedContent=b.compress(d.transformTo(b.compressInputType,c)))):(c=p(a),(!c||0===c.length||a.dir)&&(b=i.STORE,c=""),f.uncompressedSize=c.length,f.crc32=e(c),f.compressedContent=b.compress(d.transformTo(b.compressInputType,c))),f.compressedSize=f.compressedContent.length,f.compressionMethod=b.magic,f},z=function(a,b,c,g){var h,i,j,k,m=(c.compressedContent,d.transformTo("string",l.utf8encode(b.name))),n=b.comment||"",o=d.transformTo("string",l.utf8encode(n)),p=m.length!==b.name.length,q=o.length!==n.length,r=b.options,t="",u="",v="";j=b._initialMetadata.dir!==b.dir?b.dir:r.dir,k=b._initialMetadata.date!==b.date?b.date:r.date,h=k.getHours(),h<<=6,h|=k.getMinutes(),h<<=5,h|=k.getSeconds()/2,i=k.getFullYear()-1980,i<<=4,i|=k.getMonth()+1,i<<=5,i|=k.getDate(),p&&(u=s(1,1)+s(e(m),4)+m,t+="up"+s(u.length,2)+u),q&&(v=s(1,1)+s(this.crc32(o),4)+o,t+="uc"+s(v.length,2)+v);var w="";w+="\n\x00",w+=p||q?"\x00\b":"\x00\x00",w+=c.compressionMethod,w+=s(h,2),w+=s(i,2),w+=s(c.crc32,4),w+=s(c.compressedSize,4),w+=s(c.uncompressedSize,4),w+=s(m.length,2),w+=s(t.length,2);var x=f.LOCAL_FILE_HEADER+w+m+t,y=f.CENTRAL_FILE_HEADER+"\x00"+w+s(o.length,2)+"\x00\x00\x00\x00"+(j===!0?"\x00\x00\x00":"\x00\x00\x00\x00")+s(g,4)+m+t+o;return{fileRecord:x,dirRecord:y,compressedObject:c}},A={load:function(){throw new Error("Load method is not defined. Is the file jszip-load.js included ?")},filter:function(a){var b,c,d,e,f=[];for(b in this.files)this.files.hasOwnProperty(b)&&(d=this.files[b],e=new r(d.name,d._data,t(d.options)),c=b.slice(this.root.length,b.length),b.slice(0,this.root.length)===this.root&&a(c,e)&&f.push(e));return f},file:function(a,b,c){if(1===arguments.length){if(d.isRegExp(a)){var e=a;return this.filter(function(a,b){return!b.dir&&e.test(a)})}return this.filter(function(b,c){return!c.dir&&b===a})[0]||null}return a=this.root+a,v.call(this,a,b,c),this},folder:function(a){if(!a)return this;if(d.isRegExp(a))return this.filter(function(b,c){return c.dir&&a.test(b)});var b=this.root+a,c=x.call(this,b),e=this.clone();return e.root=c.name,e},remove:function(a){a=this.root+a;var b=this.files[a];if(b||("/"!=a.slice(-1)&&(a+="/"),b=this.files[a]),b&&!b.dir)delete this.files[a];else for(var c=this.filter(function(b,c){return c.name.slice(0,a.length)===a}),d=0;d=0;--f)if(this.data[f]===b&&this.data[f+1]===c&&this.data[f+2]===d&&this.data[f+3]===e)return f;return-1},c.prototype.readData=function(a){if(this.checkOffset(a),0===a)return new Uint8Array(0);var b=this.data.subarray(this.index,this.index+a);return this.index+=a,b},b.exports=c},{"./dataReader":5}],19:[function(a,b){"use strict";var c=a("./utils"),d=function(a){this.data=new Uint8Array(a),this.index=0};d.prototype={append:function(a){0!==a.length&&(a=c.transformTo("uint8array",a),this.data.set(a,this.index),this.index+=a.length)},finalize:function(){return this.data}},b.exports=d},{"./utils":21}],20:[function(a,b,c){"use strict";for(var d=a("./utils"),e=a("./support"),f=a("./nodeBuffer"),g=new Array(256),h=0;256>h;h++)g[h]=h>=252?6:h>=248?5:h>=240?4:h>=224?3:h>=192?2:1;g[254]=g[254]=1;var i=function(a){var b,c,d,f,g,h=a.length,i=0;for(f=0;h>f;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),i+=128>c?1:2048>c?2:65536>c?3:4;for(b=e.uint8array?new Uint8Array(i):new Array(i),g=0,f=0;i>g;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),128>c?b[g++]=c:2048>c?(b[g++]=192|c>>>6,b[g++]=128|63&c):65536>c?(b[g++]=224|c>>>12,b[g++]=128|c>>>6&63,b[g++]=128|63&c):(b[g++]=240|c>>>18,b[g++]=128|c>>>12&63,b[g++]=128|c>>>6&63,b[g++]=128|63&c);return b},j=function(a,b){var c;for(b=b||a.length,b>a.length&&(b=a.length),c=b-1;c>=0&&128===(192&a[c]);)c--;return 0>c?b:0===c?b:c+g[a[c]]>b?c:b},k=function(a){var b,c,e,f,h=a.length,i=new Array(2*h);for(c=0,b=0;h>b;)if(e=a[b++],128>e)i[c++]=e;else if(f=g[e],f>4)i[c++]=65533,b+=f-1;else{for(e&=2===f?31:3===f?15:7;f>1&&h>b;)e=e<<6|63&a[b++],f--;f>1?i[c++]=65533:65536>e?i[c++]=e:(e-=65536,i[c++]=55296|e>>10&1023,i[c++]=56320|1023&e)}return i.length!==c&&(i.subarray?i=i.subarray(0,c):i.length=c),d.applyFromCharCode(i)};c.utf8encode=function(a){return e.nodebuffer?f(a,"utf-8"):i(a)},c.utf8decode=function(a){if(e.nodebuffer)return d.transformTo("nodebuffer",a).toString("utf-8");a=d.transformTo(e.uint8array?"uint8array":"array",a);for(var b=[],c=0,f=a.length,g=65536;f>c;){var h=j(a,Math.min(c+g,f));b.push(k(e.uint8array?a.subarray(c,h):a.slice(c,h))),c=h}return b.join("")}},{"./nodeBuffer":11,"./support":17,"./utils":21}],21:[function(a,b,c){"use strict";function d(a){return a}function e(a,b){for(var c=0;cg&&b>1;)try{d.push("array"===f||"nodebuffer"===f?String.fromCharCode.apply(null,a.slice(g,Math.min(g+b,e))):String.fromCharCode.apply(null,a.subarray(g,Math.min(g+b,e)))),g+=b}catch(i){b=Math.floor(b/2)}return d.join("")}function g(a,b){for(var c=0;cb?"0":"")+b.toString(16).toUpperCase();return d},c.findCompression=function(a){for(var b in i)if(i.hasOwnProperty(b)&&i[b].magic===a)return i[b];return null},c.isRegExp=function(a){return"[object RegExp]"===Object.prototype.toString.call(a)}},{"./compressions":3,"./nodeBuffer":11,"./support":17}],22:[function(a,b){"use strict";function c(a,b){this.files=[],this.loadOptions=b,a&&this.load(a)}var d=a("./stringReader"),e=a("./nodeBufferReader"),f=a("./uint8ArrayReader"),g=a("./utils"),h=a("./signature"),i=a("./zipEntry"),j=a("./support"),k=a("./object");c.prototype={checkSignature:function(a){var b=this.reader.readString(4);if(b!==a)throw new Error("Corrupted zip or bug : unexpected signature ("+g.pretty(b)+", expected "+g.pretty(a)+")")},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2),this.zipComment=this.reader.readString(this.zipCommentLength),this.zipComment=k.utf8decode(this.zipComment)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.versionMadeBy=this.reader.readString(2),this.versionNeeded=this.reader.readInt(2),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var a,b,c,d=this.zip64EndOfCentralSize-44,e=0;d>e;)a=this.reader.readInt(2),b=this.reader.readInt(4),c=this.reader.readString(b),this.zip64ExtensibleData[a]={id:a,length:b,value:c}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),this.disksCount>1)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var a,b;for(a=0;a0?b.windowBits=-b.windowBits:b.gzip&&b.windowBits>0&&b.windowBits<16&&(b.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new k,this.strm.avail_out=0;var c=g.deflateInit2(this.strm,b.level,b.method,b.windowBits,b.memLevel,b.strategy);if(c!==n)throw new Error(j[c]);b.header&&g.deflateSetHeader(this.strm,b.header); +!function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;"undefined"!=typeof window?b=window:"undefined"!=typeof global?b=global:"undefined"!=typeof self&&(b=self),b.JSZip=a()}}(function(){return function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);throw new Error("Cannot find module '"+g+"'")}var j=c[g]={exports:{}};b[g][0].call(j.exports,function(a){var c=b[g][1][a];return e(c?c:a)},j,j.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g>2,g=(3&b)<<4|c>>4,h=(15&c)<<2|e>>6,i=63&e,isNaN(c)?h=i=64:isNaN(e)&&(i=64),j=j+d.charAt(f)+d.charAt(g)+d.charAt(h)+d.charAt(i);return j},c.decode=function(a){var b,c,e,f,g,h,i,j="",k=0;for(a=a.replace(/[^A-Za-z0-9\+\/\=]/g,"");k>4,c=(15&g)<<4|h>>2,e=(3&h)<<6|i,j+=String.fromCharCode(b),64!=h&&(j+=String.fromCharCode(c)),64!=i&&(j+=String.fromCharCode(e));return j}},{}],2:[function(a,b){"use strict";function c(){this.compressedSize=0,this.uncompressedSize=0,this.crc32=0,this.compressionMethod=null,this.compressedContent=null}c.prototype={getContent:function(){return null},getCompressedContent:function(){return null}},b.exports=c},{}],3:[function(a,b,c){"use strict";c.STORE={magic:"\x00\x00",compress:function(a){return a},uncompress:function(a){return a},compressInputType:null,uncompressInputType:null},c.DEFLATE=a("./flate")},{"./flate":8}],4:[function(a,b){"use strict";var c=a("./utils"),d=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117];b.exports=function(a,b){if("undefined"==typeof a||!a.length)return 0;var e="string"!==c.getTypeOf(a);"undefined"==typeof b&&(b=0);var f=0,g=0,h=0;b=-1^b;for(var i=0,j=a.length;j>i;i++)h=e?a[i]:a.charCodeAt(i),g=255&(b^h),f=d[g],b=b>>>8^f;return-1^b}},{"./utils":21}],5:[function(a,b){"use strict";function c(){this.data=null,this.length=0,this.index=0}var d=a("./utils");c.prototype={checkOffset:function(a){this.checkIndex(this.index+a)},checkIndex:function(a){if(this.lengtha)throw new Error("End of data reached (data length = "+this.length+", asked index = "+a+"). Corrupted zip ?")},setIndex:function(a){this.checkIndex(a),this.index=a},skip:function(a){this.setIndex(this.index+a)},byteAt:function(){},readInt:function(a){var b,c=0;for(this.checkOffset(a),b=this.index+a-1;b>=this.index;b--)c=(c<<8)+this.byteAt(b);return this.index+=a,c},readString:function(a){return d.transformTo("string",this.readData(a))},readData:function(){},lastIndexOfSignature:function(){},readDate:function(){var a=this.readInt(4);return new Date((a>>25&127)+1980,(a>>21&15)-1,a>>16&31,a>>11&31,a>>5&63,(31&a)<<1)}},b.exports=c},{"./utils":21}],6:[function(a,b,c){"use strict";c.base64=!1,c.binary=!1,c.dir=!1,c.createFolders=!1,c.date=null,c.compression=null,c.comment=null},{}],7:[function(a,b,c){"use strict";var d=a("./utils");c.string2binary=function(a){return d.string2binary(a)},c.string2Uint8Array=function(a){return d.transformTo("uint8array",a)},c.uint8Array2String=function(a){return d.transformTo("string",a)},c.string2Blob=function(a){var b=d.transformTo("arraybuffer",a);return d.arrayBuffer2Blob(b)},c.arrayBuffer2Blob=function(a){return d.arrayBuffer2Blob(a)},c.transformTo=function(a,b){return d.transformTo(a,b)},c.getTypeOf=function(a){return d.getTypeOf(a)},c.checkSupport=function(a){return d.checkSupport(a)},c.MAX_VALUE_16BITS=d.MAX_VALUE_16BITS,c.MAX_VALUE_32BITS=d.MAX_VALUE_32BITS,c.pretty=function(a){return d.pretty(a)},c.findCompression=function(a){return d.findCompression(a)},c.isRegExp=function(a){return d.isRegExp(a)}},{"./utils":21}],8:[function(a,b,c){"use strict";var d="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array,e=a("pako");c.uncompressInputType=d?"uint8array":"array",c.compressInputType=d?"uint8array":"array",c.magic="\b\x00",c.compress=function(a){return e.deflateRaw(a)},c.uncompress=function(a){return e.inflateRaw(a)}},{pako:24}],9:[function(a,b){"use strict";function c(a,b){return this instanceof c?(this.files={},this.comment=null,this.root="",a&&this.load(a,b),void(this.clone=function(){var a=new c;for(var b in this)"function"!=typeof this[b]&&(a[b]=this[b]);return a})):new c(a,b)}var d=a("./base64");c.prototype=a("./object"),c.prototype.load=a("./load"),c.support=a("./support"),c.defaults=a("./defaults"),c.utils=a("./deprecatedPublicUtils"),c.base64={encode:function(a){return d.encode(a)},decode:function(a){return d.decode(a)}},c.compressions=a("./compressions"),b.exports=c},{"./base64":1,"./compressions":3,"./defaults":6,"./deprecatedPublicUtils":7,"./load":10,"./object":13,"./support":17}],10:[function(a,b){"use strict";var c=a("./base64"),d=a("./zipEntries");b.exports=function(a,b){var e,f,g,h;for(b=b||{},b.base64&&(a=c.decode(a)),f=new d(a,b),e=f.files,g=0;gc;c++)d+=String.fromCharCode(255&a),a>>>=8;return d},t=function(){var a,b,c={};for(a=0;a0?a.substring(0,b):""},x=function(a,b){return"/"!=a.slice(-1)&&(a+="/"),b="undefined"!=typeof b?b:!1,this.files[a]||v.call(this,a,null,{dir:!0,createFolders:b}),this.files[a]},y=function(a,b){var c,f=new j;return a._data instanceof j?(f.uncompressedSize=a._data.uncompressedSize,f.crc32=a._data.crc32,0===f.uncompressedSize||a.dir?(b=i.STORE,f.compressedContent="",f.crc32=0):a._data.compressionMethod===b.magic?f.compressedContent=a._data.getCompressedContent():(c=a._data.getContent(),f.compressedContent=b.compress(d.transformTo(b.compressInputType,c)))):(c=p(a),(!c||0===c.length||a.dir)&&(b=i.STORE,c=""),f.uncompressedSize=c.length,f.crc32=e(c),f.compressedContent=b.compress(d.transformTo(b.compressInputType,c))),f.compressedSize=f.compressedContent.length,f.compressionMethod=b.magic,f},z=function(a,b,c,g){var h,i,j,k,m=(c.compressedContent,d.transformTo("string",l.utf8encode(b.name))),n=b.comment||"",o=d.transformTo("string",l.utf8encode(n)),p=m.length!==b.name.length,q=o.length!==n.length,r=b.options,t="",u="",v="";j=b._initialMetadata.dir!==b.dir?b.dir:r.dir,k=b._initialMetadata.date!==b.date?b.date:r.date,h=k.getHours(),h<<=6,h|=k.getMinutes(),h<<=5,h|=k.getSeconds()/2,i=k.getFullYear()-1980,i<<=4,i|=k.getMonth()+1,i<<=5,i|=k.getDate(),p&&(u=s(1,1)+s(e(m),4)+m,t+="up"+s(u.length,2)+u),q&&(v=s(1,1)+s(this.crc32(o),4)+o,t+="uc"+s(v.length,2)+v);var w="";w+="\n\x00",w+=p||q?"\x00\b":"\x00\x00",w+=c.compressionMethod,w+=s(h,2),w+=s(i,2),w+=s(c.crc32,4),w+=s(c.compressedSize,4),w+=s(c.uncompressedSize,4),w+=s(m.length,2),w+=s(t.length,2);var x=f.LOCAL_FILE_HEADER+w+m+t,y=f.CENTRAL_FILE_HEADER+"\x00"+w+s(o.length,2)+"\x00\x00\x00\x00"+(j===!0?"\x00\x00\x00":"\x00\x00\x00\x00")+s(g,4)+m+t+o;return{fileRecord:x,dirRecord:y,compressedObject:c}},A={load:function(){throw new Error("Load method is not defined. Is the file jszip-load.js included ?")},filter:function(a){var b,c,d,e,f=[];for(b in this.files)this.files.hasOwnProperty(b)&&(d=this.files[b],e=new r(d.name,d._data,t(d.options)),c=b.slice(this.root.length,b.length),b.slice(0,this.root.length)===this.root&&a(c,e)&&f.push(e));return f},file:function(a,b,c){if(1===arguments.length){if(d.isRegExp(a)){var e=a;return this.filter(function(a,b){return!b.dir&&e.test(a)})}return this.filter(function(b,c){return!c.dir&&b===a})[0]||null}return a=this.root+a,v.call(this,a,b,c),this},folder:function(a){if(!a)return this;if(d.isRegExp(a))return this.filter(function(b,c){return c.dir&&a.test(b)});var b=this.root+a,c=x.call(this,b),e=this.clone();return e.root=c.name,e},remove:function(a){a=this.root+a;var b=this.files[a];if(b||("/"!=a.slice(-1)&&(a+="/"),b=this.files[a]),b&&!b.dir)delete this.files[a];else for(var c=this.filter(function(b,c){return c.name.slice(0,a.length)===a}),d=0;d=0;--f)if(this.data[f]===b&&this.data[f+1]===c&&this.data[f+2]===d&&this.data[f+3]===e)return f;return-1},c.prototype.readData=function(a){if(this.checkOffset(a),0===a)return new Uint8Array(0);var b=this.data.subarray(this.index,this.index+a);return this.index+=a,b},b.exports=c},{"./dataReader":5}],19:[function(a,b){"use strict";var c=a("./utils"),d=function(a){this.data=new Uint8Array(a),this.index=0};d.prototype={append:function(a){0!==a.length&&(a=c.transformTo("uint8array",a),this.data.set(a,this.index),this.index+=a.length)},finalize:function(){return this.data}},b.exports=d},{"./utils":21}],20:[function(a,b,c){"use strict";for(var d=a("./utils"),e=a("./support"),f=a("./nodeBuffer"),g=new Array(256),h=0;256>h;h++)g[h]=h>=252?6:h>=248?5:h>=240?4:h>=224?3:h>=192?2:1;g[254]=g[254]=1;var i=function(a){var b,c,d,f,g,h=a.length,i=0;for(f=0;h>f;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),i+=128>c?1:2048>c?2:65536>c?3:4;for(b=e.uint8array?new Uint8Array(i):new Array(i),g=0,f=0;i>g;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),128>c?b[g++]=c:2048>c?(b[g++]=192|c>>>6,b[g++]=128|63&c):65536>c?(b[g++]=224|c>>>12,b[g++]=128|c>>>6&63,b[g++]=128|63&c):(b[g++]=240|c>>>18,b[g++]=128|c>>>12&63,b[g++]=128|c>>>6&63,b[g++]=128|63&c);return b},j=function(a,b){var c;for(b=b||a.length,b>a.length&&(b=a.length),c=b-1;c>=0&&128===(192&a[c]);)c--;return 0>c?b:0===c?b:c+g[a[c]]>b?c:b},k=function(a){var b,c,e,f,h=a.length,i=new Array(2*h);for(c=0,b=0;h>b;)if(e=a[b++],128>e)i[c++]=e;else if(f=g[e],f>4)i[c++]=65533,b+=f-1;else{for(e&=2===f?31:3===f?15:7;f>1&&h>b;)e=e<<6|63&a[b++],f--;f>1?i[c++]=65533:65536>e?i[c++]=e:(e-=65536,i[c++]=55296|e>>10&1023,i[c++]=56320|1023&e)}return i.length!==c&&(i.subarray?i=i.subarray(0,c):i.length=c),d.applyFromCharCode(i)};c.utf8encode=function(a){return e.nodebuffer?f(a,"utf-8"):i(a)},c.utf8decode=function(a){if(e.nodebuffer)return d.transformTo("nodebuffer",a).toString("utf-8");a=d.transformTo(e.uint8array?"uint8array":"array",a);for(var b=[],c=0,f=a.length,g=65536;f>c;){var h=j(a,Math.min(c+g,f));b.push(k(e.uint8array?a.subarray(c,h):a.slice(c,h))),c=h}return b.join("")}},{"./nodeBuffer":11,"./support":17,"./utils":21}],21:[function(a,b,c){"use strict";function d(a){return a}function e(a,b){for(var c=0;cg&&b>1;)try{d.push("array"===f||"nodebuffer"===f?String.fromCharCode.apply(null,a.slice(g,Math.min(g+b,e))):String.fromCharCode.apply(null,a.subarray(g,Math.min(g+b,e)))),g+=b}catch(i){b=Math.floor(b/2)}return d.join("")}function g(a,b){for(var c=0;cb?"0":"")+b.toString(16).toUpperCase();return d},c.findCompression=function(a){for(var b in i)if(i.hasOwnProperty(b)&&i[b].magic===a)return i[b];return null},c.isRegExp=function(a){return"[object RegExp]"===Object.prototype.toString.call(a)}},{"./compressions":3,"./nodeBuffer":11,"./support":17}],22:[function(a,b){"use strict";function c(a,b){this.files=[],this.loadOptions=b,a&&this.load(a)}var d=a("./stringReader"),e=a("./nodeBufferReader"),f=a("./uint8ArrayReader"),g=a("./utils"),h=a("./signature"),i=a("./zipEntry"),j=a("./support"),k=a("./object");c.prototype={checkSignature:function(a){var b=this.reader.readString(4);if(b!==a)throw new Error("Corrupted zip or bug : unexpected signature ("+g.pretty(b)+", expected "+g.pretty(a)+")")},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2),this.zipComment=this.reader.readString(this.zipCommentLength),this.zipComment=k.utf8decode(this.zipComment)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.versionMadeBy=this.reader.readString(2),this.versionNeeded=this.reader.readInt(2),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var a,b,c,d=this.zip64EndOfCentralSize-44,e=0;d>e;)a=this.reader.readInt(2),b=this.reader.readInt(4),c=this.reader.readString(b),this.zip64ExtensibleData[a]={id:a,length:b,value:c}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),this.disksCount>1)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var a,b;for(a=0;a0?b.windowBits=-b.windowBits:b.gzip&&b.windowBits>0&&b.windowBits<16&&(b.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new k,this.strm.avail_out=0;var c=g.deflateInit2(this.strm,b.level,b.method,b.windowBits,b.memLevel,b.strategy);if(c!==n)throw new Error(j[c]);b.header&&g.deflateSetHeader(this.strm,b.header); };s.prototype.push=function(a,b){var c,d,e=this.strm,f=this.options.chunkSize;if(this.ended)return!1;d=b===~~b?b:b===!0?m:l,e.input="string"==typeof a?i.string2buf(a):a,e.next_in=0,e.avail_in=e.input.length;do{if(0===e.avail_out&&(e.output=new h.Buf8(f),e.next_out=0,e.avail_out=f),c=g.deflate(e,d),c!==o&&c!==n)return this.onEnd(c),this.ended=!0,!1;(0===e.avail_out||0===e.avail_in&&d===m)&&this.onData("string"===this.options.to?i.buf2binstring(h.shrinkBuf(e.output,e.next_out)):h.shrinkBuf(e.output,e.next_out))}while((e.avail_in>0||0===e.avail_out)&&c!==o);return d===m?(c=g.deflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===n):!0},s.prototype.onData=function(a){this.chunks.push(a)},s.prototype.onEnd=function(a){a===n&&(this.result="string"===this.options.to?this.chunks.join(""):h.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Deflate=s,c.deflate=d,c.deflateRaw=e,c.gzip=f},{"./utils/common":27,"./utils/strings":28,"./zlib/deflate.js":32,"./zlib/messages":37,"./zlib/zstream":39}],26:[function(a,b,c){"use strict";function d(a,b){var c=new m(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function e(a,b){return b=b||{},b.raw=!0,d(a,b)}var f=a("./zlib/inflate.js"),g=a("./utils/common"),h=a("./utils/strings"),i=a("./zlib/constants"),j=a("./zlib/messages"),k=a("./zlib/zstream"),l=a("./zlib/gzheader"),m=function(a){this.options=g.assign({chunkSize:16384,windowBits:0,to:""},a||{});var b=this.options;b.raw&&b.windowBits>=0&&b.windowBits<16&&(b.windowBits=-b.windowBits,0===b.windowBits&&(b.windowBits=-15)),!(b.windowBits>=0&&b.windowBits<16)||a&&a.windowBits||(b.windowBits+=32),b.windowBits>15&&b.windowBits<48&&0===(15&b.windowBits)&&(b.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new k,this.strm.avail_out=0;var c=f.inflateInit2(this.strm,b.windowBits);if(c!==i.Z_OK)throw new Error(j[c]);this.header=new l,f.inflateGetHeader(this.strm,this.header)};m.prototype.push=function(a,b){var c,d,e,j,k,l=this.strm,m=this.options.chunkSize;if(this.ended)return!1;d=b===~~b?b:b===!0?i.Z_FINISH:i.Z_NO_FLUSH,l.input="string"==typeof a?h.binstring2buf(a):a,l.next_in=0,l.avail_in=l.input.length;do{if(0===l.avail_out&&(l.output=new g.Buf8(m),l.next_out=0,l.avail_out=m),c=f.inflate(l,i.Z_NO_FLUSH),c!==i.Z_STREAM_END&&c!==i.Z_OK)return this.onEnd(c),this.ended=!0,!1;l.next_out&&(0===l.avail_out||c===i.Z_STREAM_END||0===l.avail_in&&d===i.Z_FINISH)&&("string"===this.options.to?(e=h.utf8border(l.output,l.next_out),j=l.next_out-e,k=h.buf2string(l.output,e),l.next_out=j,l.avail_out=m-j,j&&g.arraySet(l.output,l.output,e,j,0),this.onData(k)):this.onData(g.shrinkBuf(l.output,l.next_out)))}while(l.avail_in>0&&c!==i.Z_STREAM_END);return c===i.Z_STREAM_END&&(d=i.Z_FINISH),d===i.Z_FINISH?(c=f.inflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===i.Z_OK):!0},m.prototype.onData=function(a){this.chunks.push(a)},m.prototype.onEnd=function(a){a===i.Z_OK&&(this.result="string"===this.options.to?this.chunks.join(""):g.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Inflate=m,c.inflate=d,c.inflateRaw=e,c.ungzip=d},{"./utils/common":27,"./utils/strings":28,"./zlib/constants":30,"./zlib/gzheader":33,"./zlib/inflate.js":35,"./zlib/messages":37,"./zlib/zstream":39}],27:[function(a,b,c){"use strict";var d="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;c.assign=function(a){for(var b=Array.prototype.slice.call(arguments,1);b.length;){var c=b.shift();if(c){if("object"!=typeof c)throw new TypeError(c+"must be non-object");for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d])}}return a},c.shrinkBuf=function(a,b){return a.length===b?a:a.subarray?a.subarray(0,b):(a.length=b,a)};var e={arraySet:function(a,b,c,d,e){if(b.subarray&&a.subarray)return void a.set(b.subarray(c,c+d),e);for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){var b,c,d,e,f,g;for(d=0,b=0,c=a.length;c>b;b++)d+=a[b].length;for(g=new Uint8Array(d),e=0,b=0,c=a.length;c>b;b++)f=a[b],g.set(f,e),e+=f.length;return g}},f={arraySet:function(a,b,c,d,e){for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){return[].concat.apply([],a)}};c.setTyped=function(a){a?(c.Buf8=Uint8Array,c.Buf16=Uint16Array,c.Buf32=Int32Array,c.assign(c,e)):(c.Buf8=Array,c.Buf16=Array,c.Buf32=Array,c.assign(c,f))},c.setTyped(d)},{}],28:[function(a,b,c){"use strict";function d(a,b){if(65537>b&&(a.subarray&&g||!a.subarray&&f))return String.fromCharCode.apply(null,e.shrinkBuf(a,b));for(var c="",d=0;b>d;d++)c+=String.fromCharCode(a[d]);return c}var e=a("./common"),f=!0,g=!0;try{String.fromCharCode.apply(null,[0])}catch(h){f=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(h){g=!1}for(var i=new e.Buf8(256),j=0;256>j;j++)i[j]=j>=252?6:j>=248?5:j>=240?4:j>=224?3:j>=192?2:1;i[254]=i[254]=1,c.string2buf=function(a){var b,c,d,f,g,h=a.length,i=0;for(f=0;h>f;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),i+=128>c?1:2048>c?2:65536>c?3:4;for(b=new e.Buf8(i),g=0,f=0;i>g;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),128>c?b[g++]=c:2048>c?(b[g++]=192|c>>>6,b[g++]=128|63&c):65536>c?(b[g++]=224|c>>>12,b[g++]=128|c>>>6&63,b[g++]=128|63&c):(b[g++]=240|c>>>18,b[g++]=128|c>>>12&63,b[g++]=128|c>>>6&63,b[g++]=128|63&c);return b},c.buf2binstring=function(a){return d(a,a.length)},c.binstring2buf=function(a){for(var b=new e.Buf8(a.length),c=0,d=b.length;d>c;c++)b[c]=a.charCodeAt(c);return b},c.buf2string=function(a,b){var c,e,f,g,h=b||a.length,j=new Array(2*h);for(e=0,c=0;h>c;)if(f=a[c++],128>f)j[e++]=f;else if(g=i[f],g>4)j[e++]=65533,c+=g-1;else{for(f&=2===g?31:3===g?15:7;g>1&&h>c;)f=f<<6|63&a[c++],g--;g>1?j[e++]=65533:65536>f?j[e++]=f:(f-=65536,j[e++]=55296|f>>10&1023,j[e++]=56320|1023&f)}return d(j,e)},c.utf8border=function(a,b){var c;for(b=b||a.length,b>a.length&&(b=a.length),c=b-1;c>=0&&128===(192&a[c]);)c--;return 0>c?b:0===c?b:c+i[a[c]]>b?c:b}},{"./common":27}],29:[function(a,b){"use strict";function c(a,b,c,d){for(var e=65535&a|0,f=a>>>16&65535|0,g=0;0!==c;){g=c>2e3?2e3:c,c-=g;do e=e+b[d++]|0,f=f+e|0;while(--g);e%=65521,f%=65521}return e|f<<16|0}b.exports=c},{}],30:[function(a,b){b.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],31:[function(a,b){"use strict";function c(){for(var a,b=[],c=0;256>c;c++){a=c;for(var d=0;8>d;d++)a=1&a?3988292384^a>>>1:a>>>1;b[c]=a}return b}function d(a,b,c,d){var f=e,g=d+c;a=-1^a;for(var h=d;g>h;h++)a=a>>>8^f[255&(a^b[h])];return-1^a}var e=c();b.exports=d},{}],32:[function(a,b,c){"use strict";function d(a,b){return a.msg=G[b],b}function e(a){return(a<<1)-(a>4?9:0)}function f(a){for(var b=a.length;--b>=0;)a[b]=0}function g(a){var b=a.state,c=b.pending;c>a.avail_out&&(c=a.avail_out),0!==c&&(C.arraySet(a.output,b.pending_buf,b.pending_out,c,a.next_out),a.next_out+=c,b.pending_out+=c,a.total_out+=c,a.avail_out-=c,b.pending-=c,0===b.pending&&(b.pending_out=0))}function h(a,b){D._tr_flush_block(a,a.block_start>=0?a.block_start:-1,a.strstart-a.block_start,b),a.block_start=a.strstart,g(a.strm)}function i(a,b){a.pending_buf[a.pending++]=b}function j(a,b){a.pending_buf[a.pending++]=b>>>8&255,a.pending_buf[a.pending++]=255&b}function k(a,b,c,d){var e=a.avail_in;return e>d&&(e=d),0===e?0:(a.avail_in-=e,C.arraySet(b,a.input,a.next_in,e,c),1===a.state.wrap?a.adler=E(a.adler,b,e,c):2===a.state.wrap&&(a.adler=F(a.adler,b,e,c)),a.next_in+=e,a.total_in+=e,e)}function l(a,b){var c,d,e=a.max_chain_length,f=a.strstart,g=a.prev_length,h=a.nice_match,i=a.strstart>a.w_size-ja?a.strstart-(a.w_size-ja):0,j=a.window,k=a.w_mask,l=a.prev,m=a.strstart+ia,n=j[f+g-1],o=j[f+g];a.prev_length>=a.good_match&&(e>>=2),h>a.lookahead&&(h=a.lookahead);do if(c=b,j[c+g]===o&&j[c+g-1]===n&&j[c]===j[f]&&j[++c]===j[f+1]){f+=2,c++;do;while(j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&m>f);if(d=ia-(m-f),f=m-ia,d>g){if(a.match_start=b,g=d,d>=h)break;n=j[f+g-1],o=j[f+g]}}while((b=l[b&k])>i&&0!==--e);return g<=a.lookahead?g:a.lookahead}function m(a){var b,c,d,e,f,g=a.w_size;do{if(e=a.window_size-a.lookahead-a.strstart,a.strstart>=g+(g-ja)){C.arraySet(a.window,a.window,g,g,0),a.match_start-=g,a.strstart-=g,a.block_start-=g,c=a.hash_size,b=c;do d=a.head[--b],a.head[b]=d>=g?d-g:0;while(--c);c=g,b=c;do d=a.prev[--b],a.prev[b]=d>=g?d-g:0;while(--c);e+=g}if(0===a.strm.avail_in)break;if(c=k(a.strm,a.window,a.strstart+a.lookahead,e),a.lookahead+=c,a.lookahead+a.insert>=ha)for(f=a.strstart-a.insert,a.ins_h=a.window[f],a.ins_h=(a.ins_h<a.pending_buf_size-5&&(c=a.pending_buf_size-5);;){if(a.lookahead<=1){if(m(a),0===a.lookahead&&b===H)return sa;if(0===a.lookahead)break}a.strstart+=a.lookahead,a.lookahead=0;var d=a.block_start+c;if((0===a.strstart||a.strstart>=d)&&(a.lookahead=a.strstart-d,a.strstart=d,h(a,!1),0===a.strm.avail_out))return sa;if(a.strstart-a.block_start>=a.w_size-ja&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.strstart>a.block_start&&(h(a,!1),0===a.strm.avail_out)?sa:sa}function o(a,b){for(var c,d;;){if(a.lookahead=ha&&(a.ins_h=(a.ins_h<=ha)if(d=D._tr_tally(a,a.strstart-a.match_start,a.match_length-ha),a.lookahead-=a.match_length,a.match_length<=a.max_lazy_match&&a.lookahead>=ha){a.match_length--;do a.strstart++,a.ins_h=(a.ins_h<=ha&&(a.ins_h=(a.ins_h<4096)&&(a.match_length=ha-1)),a.prev_length>=ha&&a.match_length<=a.prev_length){e=a.strstart+a.lookahead-ha,d=D._tr_tally(a,a.strstart-1-a.prev_match,a.prev_length-ha),a.lookahead-=a.prev_length-1,a.prev_length-=2;do++a.strstart<=e&&(a.ins_h=(a.ins_h<=ha&&a.strstart>0&&(e=a.strstart-1,d=g[e],d===g[++e]&&d===g[++e]&&d===g[++e])){f=a.strstart+ia;do;while(d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&f>e);a.match_length=ia-(f-e),a.match_length>a.lookahead&&(a.match_length=a.lookahead)}if(a.match_length>=ha?(c=D._tr_tally(a,1,a.match_length-ha),a.lookahead-=a.match_length,a.strstart+=a.match_length,a.match_length=0):(c=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++),c&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function r(a,b){for(var c;;){if(0===a.lookahead&&(m(a),0===a.lookahead)){if(b===H)return sa;break}if(a.match_length=0,c=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++,c&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function s(a){a.window_size=2*a.w_size,f(a.head),a.max_lazy_match=B[a.level].max_lazy,a.good_match=B[a.level].good_length,a.nice_match=B[a.level].nice_length,a.max_chain_length=B[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=ha-1,a.match_available=0,a.ins_h=0}function t(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Y,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new C.Buf16(2*fa),this.dyn_dtree=new C.Buf16(2*(2*da+1)),this.bl_tree=new C.Buf16(2*(2*ea+1)),f(this.dyn_ltree),f(this.dyn_dtree),f(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new C.Buf16(ga+1),this.heap=new C.Buf16(2*ca+1),f(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new C.Buf16(2*ca+1),f(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function u(a){var b;return a&&a.state?(a.total_in=a.total_out=0,a.data_type=X,b=a.state,b.pending=0,b.pending_out=0,b.wrap<0&&(b.wrap=-b.wrap),b.status=b.wrap?la:qa,a.adler=2===b.wrap?0:1,b.last_flush=H,D._tr_init(b),M):d(a,O)}function v(a){var b=u(a);return b===M&&s(a.state),b}function w(a,b){return a&&a.state?2!==a.state.wrap?O:(a.state.gzhead=b,M):O}function x(a,b,c,e,f,g){if(!a)return O;var h=1;if(b===R&&(b=6),0>e?(h=0,e=-e):e>15&&(h=2,e-=16),1>f||f>Z||c!==Y||8>e||e>15||0>b||b>9||0>g||g>V)return d(a,O);8===e&&(e=9);var i=new t;return a.state=i,i.strm=a,i.wrap=h,i.gzhead=null,i.w_bits=e,i.w_size=1<>1,i.l_buf=3*i.lit_bufsize,i.level=b,i.strategy=g,i.method=c,v(a)}function y(a,b){return x(a,b,Y,$,_,W)}function z(a,b){var c,h,k,l;if(!a||!a.state||b>L||0>b)return a?d(a,O):O;if(h=a.state,!a.output||!a.input&&0!==a.avail_in||h.status===ra&&b!==K)return d(a,0===a.avail_out?Q:O);if(h.strm=a,c=h.last_flush,h.last_flush=b,h.status===la)if(2===h.wrap)a.adler=0,i(h,31),i(h,139),i(h,8),h.gzhead?(i(h,(h.gzhead.text?1:0)+(h.gzhead.hcrc?2:0)+(h.gzhead.extra?4:0)+(h.gzhead.name?8:0)+(h.gzhead.comment?16:0)),i(h,255&h.gzhead.time),i(h,h.gzhead.time>>8&255),i(h,h.gzhead.time>>16&255),i(h,h.gzhead.time>>24&255),i(h,9===h.level?2:h.strategy>=T||h.level<2?4:0),i(h,255&h.gzhead.os),h.gzhead.extra&&h.gzhead.extra.length&&(i(h,255&h.gzhead.extra.length),i(h,h.gzhead.extra.length>>8&255)),h.gzhead.hcrc&&(a.adler=F(a.adler,h.pending_buf,h.pending,0)),h.gzindex=0,h.status=ma):(i(h,0),i(h,0),i(h,0),i(h,0),i(h,0),i(h,9===h.level?2:h.strategy>=T||h.level<2?4:0),i(h,wa),h.status=qa);else{var m=Y+(h.w_bits-8<<4)<<8,n=-1;n=h.strategy>=T||h.level<2?0:h.level<6?1:6===h.level?2:3,m|=n<<6,0!==h.strstart&&(m|=ka),m+=31-m%31,h.status=qa,j(h,m),0!==h.strstart&&(j(h,a.adler>>>16),j(h,65535&a.adler)),a.adler=1}if(h.status===ma)if(h.gzhead.extra){for(k=h.pending;h.gzindex<(65535&h.gzhead.extra.length)&&(h.pending!==h.pending_buf_size||(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending!==h.pending_buf_size));)i(h,255&h.gzhead.extra[h.gzindex]),h.gzindex++;h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),h.gzindex===h.gzhead.extra.length&&(h.gzindex=0,h.status=na)}else h.status=na;if(h.status===na)if(h.gzhead.name){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindexk&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.gzindex=0,h.status=oa)}else h.status=oa;if(h.status===oa)if(h.gzhead.comment){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindexk&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.status=pa)}else h.status=pa;if(h.status===pa&&(h.gzhead.hcrc?(h.pending+2>h.pending_buf_size&&g(a),h.pending+2<=h.pending_buf_size&&(i(h,255&a.adler),i(h,a.adler>>8&255),a.adler=0,h.status=qa)):h.status=qa),0!==h.pending){if(g(a),0===a.avail_out)return h.last_flush=-1,M}else if(0===a.avail_in&&e(b)<=e(c)&&b!==K)return d(a,Q);if(h.status===ra&&0!==a.avail_in)return d(a,Q);if(0!==a.avail_in||0!==h.lookahead||b!==H&&h.status!==ra){var o=h.strategy===T?r(h,b):h.strategy===U?q(h,b):B[h.level].func(h,b);if((o===ua||o===va)&&(h.status=ra),o===sa||o===ua)return 0===a.avail_out&&(h.last_flush=-1),M;if(o===ta&&(b===I?D._tr_align(h):b!==L&&(D._tr_stored_block(h,0,0,!1),b===J&&(f(h.head),0===h.lookahead&&(h.strstart=0,h.block_start=0,h.insert=0))),g(a),0===a.avail_out))return h.last_flush=-1,M}return b!==K?M:h.wrap<=0?N:(2===h.wrap?(i(h,255&a.adler),i(h,a.adler>>8&255),i(h,a.adler>>16&255),i(h,a.adler>>24&255),i(h,255&a.total_in),i(h,a.total_in>>8&255),i(h,a.total_in>>16&255),i(h,a.total_in>>24&255)):(j(h,a.adler>>>16),j(h,65535&a.adler)),g(a),h.wrap>0&&(h.wrap=-h.wrap),0!==h.pending?M:N)}function A(a){var b;return a&&a.state?(b=a.state.status,b!==la&&b!==ma&&b!==na&&b!==oa&&b!==pa&&b!==qa&&b!==ra?d(a,O):(a.state=null,b===qa?d(a,P):M)):O}var B,C=a("../utils/common"),D=a("./trees"),E=a("./adler32"),F=a("./crc32"),G=a("./messages"),H=0,I=1,J=3,K=4,L=5,M=0,N=1,O=-2,P=-3,Q=-5,R=-1,S=1,T=2,U=3,V=4,W=0,X=2,Y=8,Z=9,$=15,_=8,aa=29,ba=256,ca=ba+1+aa,da=30,ea=19,fa=2*ca+1,ga=15,ha=3,ia=258,ja=ia+ha+1,ka=32,la=42,ma=69,na=73,oa=91,pa=103,qa=113,ra=666,sa=1,ta=2,ua=3,va=4,wa=3,xa=function(a,b,c,d,e){this.good_length=a,this.max_lazy=b,this.nice_length=c,this.max_chain=d,this.func=e};B=[new xa(0,0,0,0,n),new xa(4,4,8,4,o),new xa(4,5,16,8,o),new xa(4,6,32,32,o),new xa(4,4,16,16,p),new xa(8,16,32,32,p),new xa(8,16,128,128,p),new xa(8,32,128,256,p),new xa(32,128,258,1024,p),new xa(32,258,258,4096,p)],c.deflateInit=y,c.deflateInit2=x,c.deflateReset=v,c.deflateResetKeep=u,c.deflateSetHeader=w,c.deflate=z,c.deflateEnd=A,c.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":27,"./adler32":29,"./crc32":31,"./messages":37,"./trees":38}],33:[function(a,b){"use strict";function c(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}b.exports=c},{}],34:[function(a,b){"use strict";var c=30,d=12;b.exports=function(a,b){var e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C;e=a.state,f=a.next_in,B=a.input,g=f+(a.avail_in-5),h=a.next_out,C=a.output,i=h-(b-a.avail_out),j=h+(a.avail_out-257),k=e.dmax,l=e.wsize,m=e.whave,n=e.wnext,o=e.window,p=e.hold,q=e.bits,r=e.lencode,s=e.distcode,t=(1<q&&(p+=B[f++]<>>24,p>>>=w,q-=w,w=v>>>16&255,0===w)C[h++]=65535&v;else{if(!(16&w)){if(0===(64&w)){v=r[(65535&v)+(p&(1<q&&(p+=B[f++]<>>=w,q-=w),15>q&&(p+=B[f++]<>>24,p>>>=w,q-=w,w=v>>>16&255,!(16&w)){if(0===(64&w)){v=s[(65535&v)+(p&(1<q&&(p+=B[f++]<q&&(p+=B[f++]<k){a.msg="invalid distance too far back",e.mode=c;break a}if(p>>>=w,q-=w,w=h-i,y>w){if(w=y-w,w>m&&e.sane){a.msg="invalid distance too far back",e.mode=c;break a}if(z=0,A=o,0===n){if(z+=l-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}else if(w>n){if(z+=l+n-w,w-=n,x>w){x-=w;do C[h++]=o[z++];while(--w);if(z=0,x>n){w=n,x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}}else if(z+=n-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}for(;x>2;)C[h++]=A[z++],C[h++]=A[z++],C[h++]=A[z++],x-=3;x&&(C[h++]=A[z++],x>1&&(C[h++]=A[z++]))}else{z=h-y;do C[h++]=C[z++],C[h++]=C[z++],C[h++]=C[z++],x-=3;while(x>2);x&&(C[h++]=C[z++],x>1&&(C[h++]=C[z++]))}break}}break}}while(g>f&&j>h);x=q>>3,f-=x,q-=x<<3,p&=(1<f?5+(g-f):5-(f-g),a.avail_out=j>h?257+(j-h):257-(h-j),e.hold=p,e.bits=q}},{}],35:[function(a,b,c){"use strict";function d(a){return(a>>>24&255)+(a>>>8&65280)+((65280&a)<<8)+((255&a)<<24)}function e(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new r.Buf16(320),this.work=new r.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function f(a){var b;return a&&a.state?(b=a.state,a.total_in=a.total_out=b.total=0,a.msg="",b.wrap&&(a.adler=1&b.wrap),b.mode=K,b.last=0,b.havedict=0,b.dmax=32768,b.head=null,b.hold=0,b.bits=0,b.lencode=b.lendyn=new r.Buf32(oa),b.distcode=b.distdyn=new r.Buf32(pa),b.sane=1,b.back=-1,C):F}function g(a){var b;return a&&a.state?(b=a.state,b.wsize=0,b.whave=0,b.wnext=0,f(a)):F}function h(a,b){var c,d;return a&&a.state?(d=a.state,0>b?(c=0,b=-b):(c=(b>>4)+1,48>b&&(b&=15)),b&&(8>b||b>15)?F:(null!==d.window&&d.wbits!==b&&(d.window=null),d.wrap=c,d.wbits=b,g(a))):F}function i(a,b){var c,d;return a?(d=new e,a.state=d,d.window=null,c=h(a,b),c!==C&&(a.state=null),c):F}function j(a){return i(a,ra)}function k(a){if(sa){var b;for(p=new r.Buf32(512),q=new r.Buf32(32),b=0;144>b;)a.lens[b++]=8;for(;256>b;)a.lens[b++]=9;for(;280>b;)a.lens[b++]=7;for(;288>b;)a.lens[b++]=8;for(v(x,a.lens,0,288,p,0,a.work,{bits:9}),b=0;32>b;)a.lens[b++]=5;v(y,a.lens,0,32,q,0,a.work,{bits:5}),sa=!1}a.lencode=p,a.lenbits=9,a.distcode=q,a.distbits=5}function l(a,b,c,d){var e,f=a.state;return null===f.window&&(f.wsize=1<=f.wsize?(r.arraySet(f.window,b,c-f.wsize,f.wsize,0),f.wnext=0,f.whave=f.wsize):(e=f.wsize-f.wnext,e>d&&(e=d),r.arraySet(f.window,b,c-d,e,f.wnext),d-=e,d?(r.arraySet(f.window,b,c-d,d,0),f.wnext=d,f.whave=f.wsize):(f.wnext+=e,f.wnext===f.wsize&&(f.wnext=0),f.whaven;){if(0===i)break a;i--,m+=e[g++]<>>8&255,c.check=t(c.check,Ba,2,0),m=0,n=0,c.mode=L;break}if(c.flags=0,c.head&&(c.head.done=!1),!(1&c.wrap)||(((255&m)<<8)+(m>>8))%31){a.msg="incorrect header check",c.mode=la;break}if((15&m)!==J){a.msg="unknown compression method",c.mode=la;break}if(m>>>=4,n-=4,wa=(15&m)+8,0===c.wbits)c.wbits=wa;else if(wa>c.wbits){a.msg="invalid window size",c.mode=la;break}c.dmax=1<n;){if(0===i)break a;i--,m+=e[g++]<>8&1),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0,c.mode=M;case M:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<>>8&255,Ba[2]=m>>>16&255,Ba[3]=m>>>24&255,c.check=t(c.check,Ba,4,0)),m=0,n=0,c.mode=N;case N:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<>8),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0,c.mode=O;case O:if(1024&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0}else c.head&&(c.head.extra=null);c.mode=P;case P:if(1024&c.flags&&(q=c.length,q>i&&(q=i),q&&(c.head&&(wa=c.head.extra_len-c.length,c.head.extra||(c.head.extra=new Array(c.head.extra_len)),r.arraySet(c.head.extra,e,g,q,wa)),512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,c.length-=q),c.length))break a;c.length=0,c.mode=Q;case Q:if(2048&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.name+=String.fromCharCode(wa));while(wa&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.name=null);c.length=0,c.mode=R;case R:if(4096&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.comment+=String.fromCharCode(wa));while(wa&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.comment=null);c.mode=S;case S:if(512&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<>9&1,c.head.done=!0),a.adler=c.check=0,c.mode=V;break;case T:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<>>=7&n,n-=7&n,c.mode=ia;break}for(;3>n;){if(0===i)break a;i--,m+=e[g++]<>>=1,n-=1,3&m){case 0:c.mode=X;break;case 1:if(k(c),c.mode=ba,b===B){m>>>=2,n-=2;break a}break;case 2:c.mode=$;break;case 3:a.msg="invalid block type",c.mode=la}m>>>=2,n-=2;break;case X:for(m>>>=7&n,n-=7&n;32>n;){if(0===i)break a;i--,m+=e[g++]<>>16^65535)){a.msg="invalid stored block lengths",c.mode=la;break}if(c.length=65535&m,m=0,n=0,c.mode=Y,b===B)break a;case Y:c.mode=Z;case Z:if(q=c.length){if(q>i&&(q=i),q>j&&(q=j),0===q)break a;r.arraySet(f,e,g,q,h),i-=q,g+=q,j-=q,h+=q,c.length-=q;break}c.mode=V;break;case $:for(;14>n;){if(0===i)break a;i--,m+=e[g++]<>>=5,n-=5,c.ndist=(31&m)+1,m>>>=5,n-=5,c.ncode=(15&m)+4,m>>>=4,n-=4,c.nlen>286||c.ndist>30){a.msg="too many length or distance symbols",c.mode=la;break}c.have=0,c.mode=_;case _:for(;c.haven;){if(0===i)break a;i--,m+=e[g++]<>>=3,n-=3}for(;c.have<19;)c.lens[Ca[c.have++]]=0;if(c.lencode=c.lendyn,c.lenbits=7,ya={bits:c.lenbits},xa=v(w,c.lens,0,19,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid code lengths set",c.mode=la;break}c.have=0,c.mode=aa;case aa:for(;c.have>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<sa)m>>>=qa,n-=qa,c.lens[c.have++]=sa;else{if(16===sa){for(za=qa+2;za>n;){if(0===i)break a;i--,m+=e[g++]<>>=qa,n-=qa,0===c.have){a.msg="invalid bit length repeat",c.mode=la;break}wa=c.lens[c.have-1],q=3+(3&m),m>>>=2,n-=2}else if(17===sa){for(za=qa+3;za>n;){if(0===i)break a;i--,m+=e[g++]<>>=qa,n-=qa,wa=0,q=3+(7&m),m>>>=3,n-=3}else{for(za=qa+7;za>n;){if(0===i)break a;i--,m+=e[g++]<>>=qa,n-=qa,wa=0,q=11+(127&m),m>>>=7,n-=7}if(c.have+q>c.nlen+c.ndist){a.msg="invalid bit length repeat",c.mode=la;break}for(;q--;)c.lens[c.have++]=wa}}if(c.mode===la)break;if(0===c.lens[256]){a.msg="invalid code -- missing end-of-block",c.mode=la;break}if(c.lenbits=9,ya={bits:c.lenbits},xa=v(x,c.lens,0,c.nlen,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid literal/lengths set",c.mode=la;break}if(c.distbits=6,c.distcode=c.distdyn,ya={bits:c.distbits},xa=v(y,c.lens,c.nlen,c.ndist,c.distcode,0,c.work,ya),c.distbits=ya.bits,xa){a.msg="invalid distances set",c.mode=la;break}if(c.mode=ba,b===B)break a;case ba:c.mode=ca;case ca:if(i>=6&&j>=258){a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,u(a,p),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,c.mode===V&&(c.back=-1);break}for(c.back=0;Aa=c.lencode[m&(1<>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=ta+qa);){if(0===i)break a;i--,m+=e[g++]<>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,c.length=sa,0===ra){c.mode=ha;break}if(32&ra){c.back=-1,c.mode=V;break}if(64&ra){a.msg="invalid literal/length code",c.mode=la;break}c.extra=15&ra,c.mode=da;case da:if(c.extra){for(za=c.extra;za>n;){if(0===i)break a;i--,m+=e[g++]<>>=c.extra,n-=c.extra,c.back+=c.extra}c.was=c.length,c.mode=ea;case ea:for(;Aa=c.distcode[m&(1<>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=ta+qa);){if(0===i)break a;i--,m+=e[g++]<>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,64&ra){a.msg="invalid distance code",c.mode=la;break}c.offset=sa,c.extra=15&ra,c.mode=fa;case fa:if(c.extra){for(za=c.extra;za>n;){if(0===i)break a;i--,m+=e[g++]<>>=c.extra,n-=c.extra,c.back+=c.extra}if(c.offset>c.dmax){a.msg="invalid distance too far back",c.mode=la;break}c.mode=ga;case ga:if(0===j)break a; diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/docs/assets/js/vendor/jszip.min.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/docs/assets/js/vendor/jszip.min.js index 767d8c11d..35646cd9e 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/docs/assets/js/vendor/jszip.min.js +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/docs/assets/js/vendor/jszip.min.js @@ -9,6 +9,6 @@ Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/js JSZip uses the library pako released under the MIT license : https://github.com/nodeca/pako/blob/master/LICENSE */ -!function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;"undefined"!=typeof window?b=window:"undefined"!=typeof global?b=global:"undefined"!=typeof self&&(b=self),b.JSZip=a()}}(function(){return function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);throw new Error("Cannot find module '"+g+"'")}var j=c[g]={exports:{}};b[g][0].call(j.exports,function(a){var c=b[g][1][a];return e(c?c:a)},j,j.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g>2,g=(3&b)<<4|c>>4,h=(15&c)<<2|e>>6,i=63&e,isNaN(c)?h=i=64:isNaN(e)&&(i=64),j=j+d.charAt(f)+d.charAt(g)+d.charAt(h)+d.charAt(i);return j},c.decode=function(a){var b,c,e,f,g,h,i,j="",k=0;for(a=a.replace(/[^A-Za-z0-9\+\/\=]/g,"");k>4,c=(15&g)<<4|h>>2,e=(3&h)<<6|i,j+=String.fromCharCode(b),64!=h&&(j+=String.fromCharCode(c)),64!=i&&(j+=String.fromCharCode(e));return j}},{}],2:[function(a,b){"use strict";function c(){this.compressedSize=0,this.uncompressedSize=0,this.crc32=0,this.compressionMethod=null,this.compressedContent=null}c.prototype={getContent:function(){return null},getCompressedContent:function(){return null}},b.exports=c},{}],3:[function(a,b,c){"use strict";c.STORE={magic:"\x00\x00",compress:function(a){return a},uncompress:function(a){return a},compressInputType:null,uncompressInputType:null},c.DEFLATE=a("./flate")},{"./flate":8}],4:[function(a,b){"use strict";var c=a("./utils"),d=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117];b.exports=function(a,b){if("undefined"==typeof a||!a.length)return 0;var e="string"!==c.getTypeOf(a);"undefined"==typeof b&&(b=0);var f=0,g=0,h=0;b=-1^b;for(var i=0,j=a.length;j>i;i++)h=e?a[i]:a.charCodeAt(i),g=255&(b^h),f=d[g],b=b>>>8^f;return-1^b}},{"./utils":21}],5:[function(a,b){"use strict";function c(){this.data=null,this.length=0,this.index=0}var d=a("./utils");c.prototype={checkOffset:function(a){this.checkIndex(this.index+a)},checkIndex:function(a){if(this.lengtha)throw new Error("End of data reached (data length = "+this.length+", asked index = "+a+"). Corrupted zip ?")},setIndex:function(a){this.checkIndex(a),this.index=a},skip:function(a){this.setIndex(this.index+a)},byteAt:function(){},readInt:function(a){var b,c=0;for(this.checkOffset(a),b=this.index+a-1;b>=this.index;b--)c=(c<<8)+this.byteAt(b);return this.index+=a,c},readString:function(a){return d.transformTo("string",this.readData(a))},readData:function(){},lastIndexOfSignature:function(){},readDate:function(){var a=this.readInt(4);return new Date((a>>25&127)+1980,(a>>21&15)-1,a>>16&31,a>>11&31,a>>5&63,(31&a)<<1)}},b.exports=c},{"./utils":21}],6:[function(a,b,c){"use strict";c.base64=!1,c.binary=!1,c.dir=!1,c.createFolders=!1,c.date=null,c.compression=null,c.comment=null},{}],7:[function(a,b,c){"use strict";var d=a("./utils");c.string2binary=function(a){return d.string2binary(a)},c.string2Uint8Array=function(a){return d.transformTo("uint8array",a)},c.uint8Array2String=function(a){return d.transformTo("string",a)},c.string2Blob=function(a){var b=d.transformTo("arraybuffer",a);return d.arrayBuffer2Blob(b)},c.arrayBuffer2Blob=function(a){return d.arrayBuffer2Blob(a)},c.transformTo=function(a,b){return d.transformTo(a,b)},c.getTypeOf=function(a){return d.getTypeOf(a)},c.checkSupport=function(a){return d.checkSupport(a)},c.MAX_VALUE_16BITS=d.MAX_VALUE_16BITS,c.MAX_VALUE_32BITS=d.MAX_VALUE_32BITS,c.pretty=function(a){return d.pretty(a)},c.findCompression=function(a){return d.findCompression(a)},c.isRegExp=function(a){return d.isRegExp(a)}},{"./utils":21}],8:[function(a,b,c){"use strict";var d="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array,e=a("pako");c.uncompressInputType=d?"uint8array":"array",c.compressInputType=d?"uint8array":"array",c.magic="\b\x00",c.compress=function(a){return e.deflateRaw(a)},c.uncompress=function(a){return e.inflateRaw(a)}},{pako:24}],9:[function(a,b){"use strict";function c(a,b){return this instanceof c?(this.files={},this.comment=null,this.root="",a&&this.load(a,b),void(this.clone=function(){var a=new c;for(var b in this)"function"!=typeof this[b]&&(a[b]=this[b]);return a})):new c(a,b)}var d=a("./base64");c.prototype=a("./object"),c.prototype.load=a("./load"),c.support=a("./support"),c.defaults=a("./defaults"),c.utils=a("./deprecatedPublicUtils"),c.base64={encode:function(a){return d.encode(a)},decode:function(a){return d.decode(a)}},c.compressions=a("./compressions"),b.exports=c},{"./base64":1,"./compressions":3,"./defaults":6,"./deprecatedPublicUtils":7,"./load":10,"./object":13,"./support":17}],10:[function(a,b){"use strict";var c=a("./base64"),d=a("./zipEntries");b.exports=function(a,b){var e,f,g,h;for(b=b||{},b.base64&&(a=c.decode(a)),f=new d(a,b),e=f.files,g=0;gc;c++)d+=String.fromCharCode(255&a),a>>>=8;return d},t=function(){var a,b,c={};for(a=0;a0?a.substring(0,b):""},x=function(a,b){return"/"!=a.slice(-1)&&(a+="/"),b="undefined"!=typeof b?b:!1,this.files[a]||v.call(this,a,null,{dir:!0,createFolders:b}),this.files[a]},y=function(a,b){var c,f=new j;return a._data instanceof j?(f.uncompressedSize=a._data.uncompressedSize,f.crc32=a._data.crc32,0===f.uncompressedSize||a.dir?(b=i.STORE,f.compressedContent="",f.crc32=0):a._data.compressionMethod===b.magic?f.compressedContent=a._data.getCompressedContent():(c=a._data.getContent(),f.compressedContent=b.compress(d.transformTo(b.compressInputType,c)))):(c=p(a),(!c||0===c.length||a.dir)&&(b=i.STORE,c=""),f.uncompressedSize=c.length,f.crc32=e(c),f.compressedContent=b.compress(d.transformTo(b.compressInputType,c))),f.compressedSize=f.compressedContent.length,f.compressionMethod=b.magic,f},z=function(a,b,c,g){var h,i,j,k,m=(c.compressedContent,d.transformTo("string",l.utf8encode(b.name))),n=b.comment||"",o=d.transformTo("string",l.utf8encode(n)),p=m.length!==b.name.length,q=o.length!==n.length,r=b.options,t="",u="",v="";j=b._initialMetadata.dir!==b.dir?b.dir:r.dir,k=b._initialMetadata.date!==b.date?b.date:r.date,h=k.getHours(),h<<=6,h|=k.getMinutes(),h<<=5,h|=k.getSeconds()/2,i=k.getFullYear()-1980,i<<=4,i|=k.getMonth()+1,i<<=5,i|=k.getDate(),p&&(u=s(1,1)+s(e(m),4)+m,t+="up"+s(u.length,2)+u),q&&(v=s(1,1)+s(this.crc32(o),4)+o,t+="uc"+s(v.length,2)+v);var w="";w+="\n\x00",w+=p||q?"\x00\b":"\x00\x00",w+=c.compressionMethod,w+=s(h,2),w+=s(i,2),w+=s(c.crc32,4),w+=s(c.compressedSize,4),w+=s(c.uncompressedSize,4),w+=s(m.length,2),w+=s(t.length,2);var x=f.LOCAL_FILE_HEADER+w+m+t,y=f.CENTRAL_FILE_HEADER+"\x00"+w+s(o.length,2)+"\x00\x00\x00\x00"+(j===!0?"\x00\x00\x00":"\x00\x00\x00\x00")+s(g,4)+m+t+o;return{fileRecord:x,dirRecord:y,compressedObject:c}},A={load:function(){throw new Error("Load method is not defined. Is the file jszip-load.js included ?")},filter:function(a){var b,c,d,e,f=[];for(b in this.files)this.files.hasOwnProperty(b)&&(d=this.files[b],e=new r(d.name,d._data,t(d.options)),c=b.slice(this.root.length,b.length),b.slice(0,this.root.length)===this.root&&a(c,e)&&f.push(e));return f},file:function(a,b,c){if(1===arguments.length){if(d.isRegExp(a)){var e=a;return this.filter(function(a,b){return!b.dir&&e.test(a)})}return this.filter(function(b,c){return!c.dir&&b===a})[0]||null}return a=this.root+a,v.call(this,a,b,c),this},folder:function(a){if(!a)return this;if(d.isRegExp(a))return this.filter(function(b,c){return c.dir&&a.test(b)});var b=this.root+a,c=x.call(this,b),e=this.clone();return e.root=c.name,e},remove:function(a){a=this.root+a;var b=this.files[a];if(b||("/"!=a.slice(-1)&&(a+="/"),b=this.files[a]),b&&!b.dir)delete this.files[a];else for(var c=this.filter(function(b,c){return c.name.slice(0,a.length)===a}),d=0;d=0;--f)if(this.data[f]===b&&this.data[f+1]===c&&this.data[f+2]===d&&this.data[f+3]===e)return f;return-1},c.prototype.readData=function(a){if(this.checkOffset(a),0===a)return new Uint8Array(0);var b=this.data.subarray(this.index,this.index+a);return this.index+=a,b},b.exports=c},{"./dataReader":5}],19:[function(a,b){"use strict";var c=a("./utils"),d=function(a){this.data=new Uint8Array(a),this.index=0};d.prototype={append:function(a){0!==a.length&&(a=c.transformTo("uint8array",a),this.data.set(a,this.index),this.index+=a.length)},finalize:function(){return this.data}},b.exports=d},{"./utils":21}],20:[function(a,b,c){"use strict";for(var d=a("./utils"),e=a("./support"),f=a("./nodeBuffer"),g=new Array(256),h=0;256>h;h++)g[h]=h>=252?6:h>=248?5:h>=240?4:h>=224?3:h>=192?2:1;g[254]=g[254]=1;var i=function(a){var b,c,d,f,g,h=a.length,i=0;for(f=0;h>f;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),i+=128>c?1:2048>c?2:65536>c?3:4;for(b=e.uint8array?new Uint8Array(i):new Array(i),g=0,f=0;i>g;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),128>c?b[g++]=c:2048>c?(b[g++]=192|c>>>6,b[g++]=128|63&c):65536>c?(b[g++]=224|c>>>12,b[g++]=128|c>>>6&63,b[g++]=128|63&c):(b[g++]=240|c>>>18,b[g++]=128|c>>>12&63,b[g++]=128|c>>>6&63,b[g++]=128|63&c);return b},j=function(a,b){var c;for(b=b||a.length,b>a.length&&(b=a.length),c=b-1;c>=0&&128===(192&a[c]);)c--;return 0>c?b:0===c?b:c+g[a[c]]>b?c:b},k=function(a){var b,c,e,f,h=a.length,i=new Array(2*h);for(c=0,b=0;h>b;)if(e=a[b++],128>e)i[c++]=e;else if(f=g[e],f>4)i[c++]=65533,b+=f-1;else{for(e&=2===f?31:3===f?15:7;f>1&&h>b;)e=e<<6|63&a[b++],f--;f>1?i[c++]=65533:65536>e?i[c++]=e:(e-=65536,i[c++]=55296|e>>10&1023,i[c++]=56320|1023&e)}return i.length!==c&&(i.subarray?i=i.subarray(0,c):i.length=c),d.applyFromCharCode(i)};c.utf8encode=function(a){return e.nodebuffer?f(a,"utf-8"):i(a)},c.utf8decode=function(a){if(e.nodebuffer)return d.transformTo("nodebuffer",a).toString("utf-8");a=d.transformTo(e.uint8array?"uint8array":"array",a);for(var b=[],c=0,f=a.length,g=65536;f>c;){var h=j(a,Math.min(c+g,f));b.push(e.uint8array?k(a.subarray(c,h)):k(a.slice(c,h))),c=h}return b.join("")}},{"./nodeBuffer":11,"./support":17,"./utils":21}],21:[function(a,b,c){"use strict";function d(a){return a}function e(a,b){for(var c=0;cg&&b>1;)try{d.push("array"===f||"nodebuffer"===f?String.fromCharCode.apply(null,a.slice(g,Math.min(g+b,e))):String.fromCharCode.apply(null,a.subarray(g,Math.min(g+b,e)))),g+=b}catch(i){b=Math.floor(b/2)}return d.join("")}function g(a,b){for(var c=0;cb?"0":"")+b.toString(16).toUpperCase();return d},c.findCompression=function(a){for(var b in i)if(i.hasOwnProperty(b)&&i[b].magic===a)return i[b];return null},c.isRegExp=function(a){return"[object RegExp]"===Object.prototype.toString.call(a)}},{"./compressions":3,"./nodeBuffer":11,"./support":17}],22:[function(a,b){"use strict";function c(a,b){this.files=[],this.loadOptions=b,a&&this.load(a)}var d=a("./stringReader"),e=a("./nodeBufferReader"),f=a("./uint8ArrayReader"),g=a("./utils"),h=a("./signature"),i=a("./zipEntry"),j=a("./support"),k=a("./object");c.prototype={checkSignature:function(a){var b=this.reader.readString(4);if(b!==a)throw new Error("Corrupted zip or bug : unexpected signature ("+g.pretty(b)+", expected "+g.pretty(a)+")")},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2),this.zipComment=this.reader.readString(this.zipCommentLength),this.zipComment=k.utf8decode(this.zipComment)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.versionMadeBy=this.reader.readString(2),this.versionNeeded=this.reader.readInt(2),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var a,b,c,d=this.zip64EndOfCentralSize-44,e=0;d>e;)a=this.reader.readInt(2),b=this.reader.readInt(4),c=this.reader.readString(b),this.zip64ExtensibleData[a]={id:a,length:b,value:c}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),this.disksCount>1)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var a,b;for(a=0;a0?b.windowBits=-b.windowBits:b.gzip&&b.windowBits>0&&b.windowBits<16&&(b.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new k,this.strm.avail_out=0;var c=g.deflateInit2(this.strm,b.level,b.method,b.windowBits,b.memLevel,b.strategy);if(c!==n)throw new Error(j[c]);b.header&&g.deflateSetHeader(this.strm,b.header) +!function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;"undefined"!=typeof window?b=window:"undefined"!=typeof global?b=global:"undefined"!=typeof self&&(b=self),b.JSZip=a()}}(function(){return function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);throw new Error("Cannot find module '"+g+"'")}var j=c[g]={exports:{}};b[g][0].call(j.exports,function(a){var c=b[g][1][a];return e(c?c:a)},j,j.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g>2,g=(3&b)<<4|c>>4,h=(15&c)<<2|e>>6,i=63&e,isNaN(c)?h=i=64:isNaN(e)&&(i=64),j=j+d.charAt(f)+d.charAt(g)+d.charAt(h)+d.charAt(i);return j},c.decode=function(a){var b,c,e,f,g,h,i,j="",k=0;for(a=a.replace(/[^A-Za-z0-9\+\/\=]/g,"");k>4,c=(15&g)<<4|h>>2,e=(3&h)<<6|i,j+=String.fromCharCode(b),64!=h&&(j+=String.fromCharCode(c)),64!=i&&(j+=String.fromCharCode(e));return j}},{}],2:[function(a,b){"use strict";function c(){this.compressedSize=0,this.uncompressedSize=0,this.crc32=0,this.compressionMethod=null,this.compressedContent=null}c.prototype={getContent:function(){return null},getCompressedContent:function(){return null}},b.exports=c},{}],3:[function(a,b,c){"use strict";c.STORE={magic:"\x00\x00",compress:function(a){return a},uncompress:function(a){return a},compressInputType:null,uncompressInputType:null},c.DEFLATE=a("./flate")},{"./flate":8}],4:[function(a,b){"use strict";var c=a("./utils"),d=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117];b.exports=function(a,b){if("undefined"==typeof a||!a.length)return 0;var e="string"!==c.getTypeOf(a);"undefined"==typeof b&&(b=0);var f=0,g=0,h=0;b=-1^b;for(var i=0,j=a.length;j>i;i++)h=e?a[i]:a.charCodeAt(i),g=255&(b^h),f=d[g],b=b>>>8^f;return-1^b}},{"./utils":21}],5:[function(a,b){"use strict";function c(){this.data=null,this.length=0,this.index=0}var d=a("./utils");c.prototype={checkOffset:function(a){this.checkIndex(this.index+a)},checkIndex:function(a){if(this.lengtha)throw new Error("End of data reached (data length = "+this.length+", asked index = "+a+"). Corrupted zip ?")},setIndex:function(a){this.checkIndex(a),this.index=a},skip:function(a){this.setIndex(this.index+a)},byteAt:function(){},readInt:function(a){var b,c=0;for(this.checkOffset(a),b=this.index+a-1;b>=this.index;b--)c=(c<<8)+this.byteAt(b);return this.index+=a,c},readString:function(a){return d.transformTo("string",this.readData(a))},readData:function(){},lastIndexOfSignature:function(){},readDate:function(){var a=this.readInt(4);return new Date((a>>25&127)+1980,(a>>21&15)-1,a>>16&31,a>>11&31,a>>5&63,(31&a)<<1)}},b.exports=c},{"./utils":21}],6:[function(a,b,c){"use strict";c.base64=!1,c.binary=!1,c.dir=!1,c.createFolders=!1,c.date=null,c.compression=null,c.comment=null},{}],7:[function(a,b,c){"use strict";var d=a("./utils");c.string2binary=function(a){return d.string2binary(a)},c.string2Uint8Array=function(a){return d.transformTo("uint8array",a)},c.uint8Array2String=function(a){return d.transformTo("string",a)},c.string2Blob=function(a){var b=d.transformTo("arraybuffer",a);return d.arrayBuffer2Blob(b)},c.arrayBuffer2Blob=function(a){return d.arrayBuffer2Blob(a)},c.transformTo=function(a,b){return d.transformTo(a,b)},c.getTypeOf=function(a){return d.getTypeOf(a)},c.checkSupport=function(a){return d.checkSupport(a)},c.MAX_VALUE_16BITS=d.MAX_VALUE_16BITS,c.MAX_VALUE_32BITS=d.MAX_VALUE_32BITS,c.pretty=function(a){return d.pretty(a)},c.findCompression=function(a){return d.findCompression(a)},c.isRegExp=function(a){return d.isRegExp(a)}},{"./utils":21}],8:[function(a,b,c){"use strict";var d="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array,e=a("pako");c.uncompressInputType=d?"uint8array":"array",c.compressInputType=d?"uint8array":"array",c.magic="\b\x00",c.compress=function(a){return e.deflateRaw(a)},c.uncompress=function(a){return e.inflateRaw(a)}},{pako:24}],9:[function(a,b){"use strict";function c(a,b){return this instanceof c?(this.files={},this.comment=null,this.root="",a&&this.load(a,b),void(this.clone=function(){var a=new c;for(var b in this)"function"!=typeof this[b]&&(a[b]=this[b]);return a})):new c(a,b)}var d=a("./base64");c.prototype=a("./object"),c.prototype.load=a("./load"),c.support=a("./support"),c.defaults=a("./defaults"),c.utils=a("./deprecatedPublicUtils"),c.base64={encode:function(a){return d.encode(a)},decode:function(a){return d.decode(a)}},c.compressions=a("./compressions"),b.exports=c},{"./base64":1,"./compressions":3,"./defaults":6,"./deprecatedPublicUtils":7,"./load":10,"./object":13,"./support":17}],10:[function(a,b){"use strict";var c=a("./base64"),d=a("./zipEntries");b.exports=function(a,b){var e,f,g,h;for(b=b||{},b.base64&&(a=c.decode(a)),f=new d(a,b),e=f.files,g=0;gc;c++)d+=String.fromCharCode(255&a),a>>>=8;return d},t=function(){var a,b,c={};for(a=0;a0?a.substring(0,b):""},x=function(a,b){return"/"!=a.slice(-1)&&(a+="/"),b="undefined"!=typeof b?b:!1,this.files[a]||v.call(this,a,null,{dir:!0,createFolders:b}),this.files[a]},y=function(a,b){var c,f=new j;return a._data instanceof j?(f.uncompressedSize=a._data.uncompressedSize,f.crc32=a._data.crc32,0===f.uncompressedSize||a.dir?(b=i.STORE,f.compressedContent="",f.crc32=0):a._data.compressionMethod===b.magic?f.compressedContent=a._data.getCompressedContent():(c=a._data.getContent(),f.compressedContent=b.compress(d.transformTo(b.compressInputType,c)))):(c=p(a),(!c||0===c.length||a.dir)&&(b=i.STORE,c=""),f.uncompressedSize=c.length,f.crc32=e(c),f.compressedContent=b.compress(d.transformTo(b.compressInputType,c))),f.compressedSize=f.compressedContent.length,f.compressionMethod=b.magic,f},z=function(a,b,c,g){var h,i,j,k,m=(c.compressedContent,d.transformTo("string",l.utf8encode(b.name))),n=b.comment||"",o=d.transformTo("string",l.utf8encode(n)),p=m.length!==b.name.length,q=o.length!==n.length,r=b.options,t="",u="",v="";j=b._initialMetadata.dir!==b.dir?b.dir:r.dir,k=b._initialMetadata.date!==b.date?b.date:r.date,h=k.getHours(),h<<=6,h|=k.getMinutes(),h<<=5,h|=k.getSeconds()/2,i=k.getFullYear()-1980,i<<=4,i|=k.getMonth()+1,i<<=5,i|=k.getDate(),p&&(u=s(1,1)+s(e(m),4)+m,t+="up"+s(u.length,2)+u),q&&(v=s(1,1)+s(this.crc32(o),4)+o,t+="uc"+s(v.length,2)+v);var w="";w+="\n\x00",w+=p||q?"\x00\b":"\x00\x00",w+=c.compressionMethod,w+=s(h,2),w+=s(i,2),w+=s(c.crc32,4),w+=s(c.compressedSize,4),w+=s(c.uncompressedSize,4),w+=s(m.length,2),w+=s(t.length,2);var x=f.LOCAL_FILE_HEADER+w+m+t,y=f.CENTRAL_FILE_HEADER+"\x00"+w+s(o.length,2)+"\x00\x00\x00\x00"+(j===!0?"\x00\x00\x00":"\x00\x00\x00\x00")+s(g,4)+m+t+o;return{fileRecord:x,dirRecord:y,compressedObject:c}},A={load:function(){throw new Error("Load method is not defined. Is the file jszip-load.js included ?")},filter:function(a){var b,c,d,e,f=[];for(b in this.files)this.files.hasOwnProperty(b)&&(d=this.files[b],e=new r(d.name,d._data,t(d.options)),c=b.slice(this.root.length,b.length),b.slice(0,this.root.length)===this.root&&a(c,e)&&f.push(e));return f},file:function(a,b,c){if(1===arguments.length){if(d.isRegExp(a)){var e=a;return this.filter(function(a,b){return!b.dir&&e.test(a)})}return this.filter(function(b,c){return!c.dir&&b===a})[0]||null}return a=this.root+a,v.call(this,a,b,c),this},folder:function(a){if(!a)return this;if(d.isRegExp(a))return this.filter(function(b,c){return c.dir&&a.test(b)});var b=this.root+a,c=x.call(this,b),e=this.clone();return e.root=c.name,e},remove:function(a){a=this.root+a;var b=this.files[a];if(b||("/"!=a.slice(-1)&&(a+="/"),b=this.files[a]),b&&!b.dir)delete this.files[a];else for(var c=this.filter(function(b,c){return c.name.slice(0,a.length)===a}),d=0;d=0;--f)if(this.data[f]===b&&this.data[f+1]===c&&this.data[f+2]===d&&this.data[f+3]===e)return f;return-1},c.prototype.readData=function(a){if(this.checkOffset(a),0===a)return new Uint8Array(0);var b=this.data.subarray(this.index,this.index+a);return this.index+=a,b},b.exports=c},{"./dataReader":5}],19:[function(a,b){"use strict";var c=a("./utils"),d=function(a){this.data=new Uint8Array(a),this.index=0};d.prototype={append:function(a){0!==a.length&&(a=c.transformTo("uint8array",a),this.data.set(a,this.index),this.index+=a.length)},finalize:function(){return this.data}},b.exports=d},{"./utils":21}],20:[function(a,b,c){"use strict";for(var d=a("./utils"),e=a("./support"),f=a("./nodeBuffer"),g=new Array(256),h=0;256>h;h++)g[h]=h>=252?6:h>=248?5:h>=240?4:h>=224?3:h>=192?2:1;g[254]=g[254]=1;var i=function(a){var b,c,d,f,g,h=a.length,i=0;for(f=0;h>f;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),i+=128>c?1:2048>c?2:65536>c?3:4;for(b=e.uint8array?new Uint8Array(i):new Array(i),g=0,f=0;i>g;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),128>c?b[g++]=c:2048>c?(b[g++]=192|c>>>6,b[g++]=128|63&c):65536>c?(b[g++]=224|c>>>12,b[g++]=128|c>>>6&63,b[g++]=128|63&c):(b[g++]=240|c>>>18,b[g++]=128|c>>>12&63,b[g++]=128|c>>>6&63,b[g++]=128|63&c);return b},j=function(a,b){var c;for(b=b||a.length,b>a.length&&(b=a.length),c=b-1;c>=0&&128===(192&a[c]);)c--;return 0>c?b:0===c?b:c+g[a[c]]>b?c:b},k=function(a){var b,c,e,f,h=a.length,i=new Array(2*h);for(c=0,b=0;h>b;)if(e=a[b++],128>e)i[c++]=e;else if(f=g[e],f>4)i[c++]=65533,b+=f-1;else{for(e&=2===f?31:3===f?15:7;f>1&&h>b;)e=e<<6|63&a[b++],f--;f>1?i[c++]=65533:65536>e?i[c++]=e:(e-=65536,i[c++]=55296|e>>10&1023,i[c++]=56320|1023&e)}return i.length!==c&&(i.subarray?i=i.subarray(0,c):i.length=c),d.applyFromCharCode(i)};c.utf8encode=function(a){return e.nodebuffer?f(a,"utf-8"):i(a)},c.utf8decode=function(a){if(e.nodebuffer)return d.transformTo("nodebuffer",a).toString("utf-8");a=d.transformTo(e.uint8array?"uint8array":"array",a);for(var b=[],c=0,f=a.length,g=65536;f>c;){var h=j(a,Math.min(c+g,f));b.push(e.uint8array?k(a.subarray(c,h)):k(a.slice(c,h))),c=h}return b.join("")}},{"./nodeBuffer":11,"./support":17,"./utils":21}],21:[function(a,b,c){"use strict";function d(a){return a}function e(a,b){for(var c=0;cg&&b>1;)try{d.push("array"===f||"nodebuffer"===f?String.fromCharCode.apply(null,a.slice(g,Math.min(g+b,e))):String.fromCharCode.apply(null,a.subarray(g,Math.min(g+b,e)))),g+=b}catch(i){b=Math.floor(b/2)}return d.join("")}function g(a,b){for(var c=0;cb?"0":"")+b.toString(16).toUpperCase();return d},c.findCompression=function(a){for(var b in i)if(i.hasOwnProperty(b)&&i[b].magic===a)return i[b];return null},c.isRegExp=function(a){return"[object RegExp]"===Object.prototype.toString.call(a)}},{"./compressions":3,"./nodeBuffer":11,"./support":17}],22:[function(a,b){"use strict";function c(a,b){this.files=[],this.loadOptions=b,a&&this.load(a)}var d=a("./stringReader"),e=a("./nodeBufferReader"),f=a("./uint8ArrayReader"),g=a("./utils"),h=a("./signature"),i=a("./zipEntry"),j=a("./support"),k=a("./object");c.prototype={checkSignature:function(a){var b=this.reader.readString(4);if(b!==a)throw new Error("Corrupted zip or bug : unexpected signature ("+g.pretty(b)+", expected "+g.pretty(a)+")")},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2),this.zipComment=this.reader.readString(this.zipCommentLength),this.zipComment=k.utf8decode(this.zipComment)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.versionMadeBy=this.reader.readString(2),this.versionNeeded=this.reader.readInt(2),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var a,b,c,d=this.zip64EndOfCentralSize-44,e=0;d>e;)a=this.reader.readInt(2),b=this.reader.readInt(4),c=this.reader.readString(b),this.zip64ExtensibleData[a]={id:a,length:b,value:c}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),this.disksCount>1)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var a,b;for(a=0;a0?b.windowBits=-b.windowBits:b.gzip&&b.windowBits>0&&b.windowBits<16&&(b.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new k,this.strm.avail_out=0;var c=g.deflateInit2(this.strm,b.level,b.method,b.windowBits,b.memLevel,b.strategy);if(c!==n)throw new Error(j[c]);b.header&&g.deflateSetHeader(this.strm,b.header) };s.prototype.push=function(a,b){var c,d,e=this.strm,f=this.options.chunkSize;if(this.ended)return!1;d=b===~~b?b:b===!0?m:l,e.input="string"==typeof a?i.string2buf(a):a,e.next_in=0,e.avail_in=e.input.length;do{if(0===e.avail_out&&(e.output=new h.Buf8(f),e.next_out=0,e.avail_out=f),c=g.deflate(e,d),c!==o&&c!==n)return this.onEnd(c),this.ended=!0,!1;(0===e.avail_out||0===e.avail_in&&d===m)&&this.onData("string"===this.options.to?i.buf2binstring(h.shrinkBuf(e.output,e.next_out)):h.shrinkBuf(e.output,e.next_out))}while((e.avail_in>0||0===e.avail_out)&&c!==o);return d===m?(c=g.deflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===n):!0},s.prototype.onData=function(a){this.chunks.push(a)},s.prototype.onEnd=function(a){a===n&&(this.result="string"===this.options.to?this.chunks.join(""):h.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Deflate=s,c.deflate=d,c.deflateRaw=e,c.gzip=f},{"./utils/common":27,"./utils/strings":28,"./zlib/deflate.js":32,"./zlib/messages":37,"./zlib/zstream":39}],26:[function(a,b,c){"use strict";function d(a,b){var c=new m(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function e(a,b){return b=b||{},b.raw=!0,d(a,b)}var f=a("./zlib/inflate.js"),g=a("./utils/common"),h=a("./utils/strings"),i=a("./zlib/constants"),j=a("./zlib/messages"),k=a("./zlib/zstream"),l=a("./zlib/gzheader"),m=function(a){this.options=g.assign({chunkSize:16384,windowBits:0,to:""},a||{});var b=this.options;b.raw&&b.windowBits>=0&&b.windowBits<16&&(b.windowBits=-b.windowBits,0===b.windowBits&&(b.windowBits=-15)),!(b.windowBits>=0&&b.windowBits<16)||a&&a.windowBits||(b.windowBits+=32),b.windowBits>15&&b.windowBits<48&&0===(15&b.windowBits)&&(b.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new k,this.strm.avail_out=0;var c=f.inflateInit2(this.strm,b.windowBits);if(c!==i.Z_OK)throw new Error(j[c]);this.header=new l,f.inflateGetHeader(this.strm,this.header)};m.prototype.push=function(a,b){var c,d,e,j,k,l=this.strm,m=this.options.chunkSize;if(this.ended)return!1;d=b===~~b?b:b===!0?i.Z_FINISH:i.Z_NO_FLUSH,l.input="string"==typeof a?h.binstring2buf(a):a,l.next_in=0,l.avail_in=l.input.length;do{if(0===l.avail_out&&(l.output=new g.Buf8(m),l.next_out=0,l.avail_out=m),c=f.inflate(l,i.Z_NO_FLUSH),c!==i.Z_STREAM_END&&c!==i.Z_OK)return this.onEnd(c),this.ended=!0,!1;l.next_out&&(0===l.avail_out||c===i.Z_STREAM_END||0===l.avail_in&&d===i.Z_FINISH)&&("string"===this.options.to?(e=h.utf8border(l.output,l.next_out),j=l.next_out-e,k=h.buf2string(l.output,e),l.next_out=j,l.avail_out=m-j,j&&g.arraySet(l.output,l.output,e,j,0),this.onData(k)):this.onData(g.shrinkBuf(l.output,l.next_out)))}while(l.avail_in>0&&c!==i.Z_STREAM_END);return c===i.Z_STREAM_END&&(d=i.Z_FINISH),d===i.Z_FINISH?(c=f.inflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===i.Z_OK):!0},m.prototype.onData=function(a){this.chunks.push(a)},m.prototype.onEnd=function(a){a===i.Z_OK&&(this.result="string"===this.options.to?this.chunks.join(""):g.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Inflate=m,c.inflate=d,c.inflateRaw=e,c.ungzip=d},{"./utils/common":27,"./utils/strings":28,"./zlib/constants":30,"./zlib/gzheader":33,"./zlib/inflate.js":35,"./zlib/messages":37,"./zlib/zstream":39}],27:[function(a,b,c){"use strict";var d="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;c.assign=function(a){for(var b=Array.prototype.slice.call(arguments,1);b.length;){var c=b.shift();if(c){if("object"!=typeof c)throw new TypeError(c+"must be non-object");for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d])}}return a},c.shrinkBuf=function(a,b){return a.length===b?a:a.subarray?a.subarray(0,b):(a.length=b,a)};var e={arraySet:function(a,b,c,d,e){if(b.subarray&&a.subarray)return void a.set(b.subarray(c,c+d),e);for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){var b,c,d,e,f,g;for(d=0,b=0,c=a.length;c>b;b++)d+=a[b].length;for(g=new Uint8Array(d),e=0,b=0,c=a.length;c>b;b++)f=a[b],g.set(f,e),e+=f.length;return g}},f={arraySet:function(a,b,c,d,e){for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){return[].concat.apply([],a)}};c.setTyped=function(a){a?(c.Buf8=Uint8Array,c.Buf16=Uint16Array,c.Buf32=Int32Array,c.assign(c,e)):(c.Buf8=Array,c.Buf16=Array,c.Buf32=Array,c.assign(c,f))},c.setTyped(d)},{}],28:[function(a,b,c){"use strict";function d(a,b){if(65537>b&&(a.subarray&&g||!a.subarray&&f))return String.fromCharCode.apply(null,e.shrinkBuf(a,b));for(var c="",d=0;b>d;d++)c+=String.fromCharCode(a[d]);return c}var e=a("./common"),f=!0,g=!0;try{String.fromCharCode.apply(null,[0])}catch(h){f=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(h){g=!1}for(var i=new e.Buf8(256),j=0;256>j;j++)i[j]=j>=252?6:j>=248?5:j>=240?4:j>=224?3:j>=192?2:1;i[254]=i[254]=1,c.string2buf=function(a){var b,c,d,f,g,h=a.length,i=0;for(f=0;h>f;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),i+=128>c?1:2048>c?2:65536>c?3:4;for(b=new e.Buf8(i),g=0,f=0;i>g;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),128>c?b[g++]=c:2048>c?(b[g++]=192|c>>>6,b[g++]=128|63&c):65536>c?(b[g++]=224|c>>>12,b[g++]=128|c>>>6&63,b[g++]=128|63&c):(b[g++]=240|c>>>18,b[g++]=128|c>>>12&63,b[g++]=128|c>>>6&63,b[g++]=128|63&c);return b},c.buf2binstring=function(a){return d(a,a.length)},c.binstring2buf=function(a){for(var b=new e.Buf8(a.length),c=0,d=b.length;d>c;c++)b[c]=a.charCodeAt(c);return b},c.buf2string=function(a,b){var c,e,f,g,h=b||a.length,j=new Array(2*h);for(e=0,c=0;h>c;)if(f=a[c++],128>f)j[e++]=f;else if(g=i[f],g>4)j[e++]=65533,c+=g-1;else{for(f&=2===g?31:3===g?15:7;g>1&&h>c;)f=f<<6|63&a[c++],g--;g>1?j[e++]=65533:65536>f?j[e++]=f:(f-=65536,j[e++]=55296|f>>10&1023,j[e++]=56320|1023&f)}return d(j,e)},c.utf8border=function(a,b){var c;for(b=b||a.length,b>a.length&&(b=a.length),c=b-1;c>=0&&128===(192&a[c]);)c--;return 0>c?b:0===c?b:c+i[a[c]]>b?c:b}},{"./common":27}],29:[function(a,b){"use strict";function c(a,b,c,d){for(var e=65535&a|0,f=a>>>16&65535|0,g=0;0!==c;){g=c>2e3?2e3:c,c-=g;do e=e+b[d++]|0,f=f+e|0;while(--g);e%=65521,f%=65521}return e|f<<16|0}b.exports=c},{}],30:[function(a,b){b.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],31:[function(a,b){"use strict";function c(){for(var a,b=[],c=0;256>c;c++){a=c;for(var d=0;8>d;d++)a=1&a?3988292384^a>>>1:a>>>1;b[c]=a}return b}function d(a,b,c,d){var f=e,g=d+c;a=-1^a;for(var h=d;g>h;h++)a=a>>>8^f[255&(a^b[h])];return-1^a}var e=c();b.exports=d},{}],32:[function(a,b,c){"use strict";function d(a,b){return a.msg=G[b],b}function e(a){return(a<<1)-(a>4?9:0)}function f(a){for(var b=a.length;--b>=0;)a[b]=0}function g(a){var b=a.state,c=b.pending;c>a.avail_out&&(c=a.avail_out),0!==c&&(C.arraySet(a.output,b.pending_buf,b.pending_out,c,a.next_out),a.next_out+=c,b.pending_out+=c,a.total_out+=c,a.avail_out-=c,b.pending-=c,0===b.pending&&(b.pending_out=0))}function h(a,b){D._tr_flush_block(a,a.block_start>=0?a.block_start:-1,a.strstart-a.block_start,b),a.block_start=a.strstart,g(a.strm)}function i(a,b){a.pending_buf[a.pending++]=b}function j(a,b){a.pending_buf[a.pending++]=b>>>8&255,a.pending_buf[a.pending++]=255&b}function k(a,b,c,d){var e=a.avail_in;return e>d&&(e=d),0===e?0:(a.avail_in-=e,C.arraySet(b,a.input,a.next_in,e,c),1===a.state.wrap?a.adler=E(a.adler,b,e,c):2===a.state.wrap&&(a.adler=F(a.adler,b,e,c)),a.next_in+=e,a.total_in+=e,e)}function l(a,b){var c,d,e=a.max_chain_length,f=a.strstart,g=a.prev_length,h=a.nice_match,i=a.strstart>a.w_size-jb?a.strstart-(a.w_size-jb):0,j=a.window,k=a.w_mask,l=a.prev,m=a.strstart+ib,n=j[f+g-1],o=j[f+g];a.prev_length>=a.good_match&&(e>>=2),h>a.lookahead&&(h=a.lookahead);do if(c=b,j[c+g]===o&&j[c+g-1]===n&&j[c]===j[f]&&j[++c]===j[f+1]){f+=2,c++;do;while(j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&m>f);if(d=ib-(m-f),f=m-ib,d>g){if(a.match_start=b,g=d,d>=h)break;n=j[f+g-1],o=j[f+g]}}while((b=l[b&k])>i&&0!==--e);return g<=a.lookahead?g:a.lookahead}function m(a){var b,c,d,e,f,g=a.w_size;do{if(e=a.window_size-a.lookahead-a.strstart,a.strstart>=g+(g-jb)){C.arraySet(a.window,a.window,g,g,0),a.match_start-=g,a.strstart-=g,a.block_start-=g,c=a.hash_size,b=c;do d=a.head[--b],a.head[b]=d>=g?d-g:0;while(--c);c=g,b=c;do d=a.prev[--b],a.prev[b]=d>=g?d-g:0;while(--c);e+=g}if(0===a.strm.avail_in)break;if(c=k(a.strm,a.window,a.strstart+a.lookahead,e),a.lookahead+=c,a.lookahead+a.insert>=hb)for(f=a.strstart-a.insert,a.ins_h=a.window[f],a.ins_h=(a.ins_h<a.pending_buf_size-5&&(c=a.pending_buf_size-5);;){if(a.lookahead<=1){if(m(a),0===a.lookahead&&b===H)return sb;if(0===a.lookahead)break}a.strstart+=a.lookahead,a.lookahead=0;var d=a.block_start+c;if((0===a.strstart||a.strstart>=d)&&(a.lookahead=a.strstart-d,a.strstart=d,h(a,!1),0===a.strm.avail_out))return sb;if(a.strstart-a.block_start>=a.w_size-jb&&(h(a,!1),0===a.strm.avail_out))return sb}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ub:vb):a.strstart>a.block_start&&(h(a,!1),0===a.strm.avail_out)?sb:sb}function o(a,b){for(var c,d;;){if(a.lookahead=hb&&(a.ins_h=(a.ins_h<=hb)if(d=D._tr_tally(a,a.strstart-a.match_start,a.match_length-hb),a.lookahead-=a.match_length,a.match_length<=a.max_lazy_match&&a.lookahead>=hb){a.match_length--;do a.strstart++,a.ins_h=(a.ins_h<=hb&&(a.ins_h=(a.ins_h<4096)&&(a.match_length=hb-1)),a.prev_length>=hb&&a.match_length<=a.prev_length){e=a.strstart+a.lookahead-hb,d=D._tr_tally(a,a.strstart-1-a.prev_match,a.prev_length-hb),a.lookahead-=a.prev_length-1,a.prev_length-=2;do++a.strstart<=e&&(a.ins_h=(a.ins_h<=hb&&a.strstart>0&&(e=a.strstart-1,d=g[e],d===g[++e]&&d===g[++e]&&d===g[++e])){f=a.strstart+ib;do;while(d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&f>e);a.match_length=ib-(f-e),a.match_length>a.lookahead&&(a.match_length=a.lookahead)}if(a.match_length>=hb?(c=D._tr_tally(a,1,a.match_length-hb),a.lookahead-=a.match_length,a.strstart+=a.match_length,a.match_length=0):(c=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++),c&&(h(a,!1),0===a.strm.avail_out))return sb}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ub:vb):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sb:tb}function r(a,b){for(var c;;){if(0===a.lookahead&&(m(a),0===a.lookahead)){if(b===H)return sb;break}if(a.match_length=0,c=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++,c&&(h(a,!1),0===a.strm.avail_out))return sb}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ub:vb):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sb:tb}function s(a){a.window_size=2*a.w_size,f(a.head),a.max_lazy_match=B[a.level].max_lazy,a.good_match=B[a.level].good_length,a.nice_match=B[a.level].nice_length,a.max_chain_length=B[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=hb-1,a.match_available=0,a.ins_h=0}function t(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Y,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new C.Buf16(2*fb),this.dyn_dtree=new C.Buf16(2*(2*db+1)),this.bl_tree=new C.Buf16(2*(2*eb+1)),f(this.dyn_ltree),f(this.dyn_dtree),f(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new C.Buf16(gb+1),this.heap=new C.Buf16(2*cb+1),f(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new C.Buf16(2*cb+1),f(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function u(a){var b;return a&&a.state?(a.total_in=a.total_out=0,a.data_type=X,b=a.state,b.pending=0,b.pending_out=0,b.wrap<0&&(b.wrap=-b.wrap),b.status=b.wrap?lb:qb,a.adler=2===b.wrap?0:1,b.last_flush=H,D._tr_init(b),M):d(a,O)}function v(a){var b=u(a);return b===M&&s(a.state),b}function w(a,b){return a&&a.state?2!==a.state.wrap?O:(a.state.gzhead=b,M):O}function x(a,b,c,e,f,g){if(!a)return O;var h=1;if(b===R&&(b=6),0>e?(h=0,e=-e):e>15&&(h=2,e-=16),1>f||f>Z||c!==Y||8>e||e>15||0>b||b>9||0>g||g>V)return d(a,O);8===e&&(e=9);var i=new t;return a.state=i,i.strm=a,i.wrap=h,i.gzhead=null,i.w_bits=e,i.w_size=1<>1,i.l_buf=3*i.lit_bufsize,i.level=b,i.strategy=g,i.method=c,v(a)}function y(a,b){return x(a,b,Y,$,_,W)}function z(a,b){var c,h,k,l;if(!a||!a.state||b>L||0>b)return a?d(a,O):O;if(h=a.state,!a.output||!a.input&&0!==a.avail_in||h.status===rb&&b!==K)return d(a,0===a.avail_out?Q:O);if(h.strm=a,c=h.last_flush,h.last_flush=b,h.status===lb)if(2===h.wrap)a.adler=0,i(h,31),i(h,139),i(h,8),h.gzhead?(i(h,(h.gzhead.text?1:0)+(h.gzhead.hcrc?2:0)+(h.gzhead.extra?4:0)+(h.gzhead.name?8:0)+(h.gzhead.comment?16:0)),i(h,255&h.gzhead.time),i(h,h.gzhead.time>>8&255),i(h,h.gzhead.time>>16&255),i(h,h.gzhead.time>>24&255),i(h,9===h.level?2:h.strategy>=T||h.level<2?4:0),i(h,255&h.gzhead.os),h.gzhead.extra&&h.gzhead.extra.length&&(i(h,255&h.gzhead.extra.length),i(h,h.gzhead.extra.length>>8&255)),h.gzhead.hcrc&&(a.adler=F(a.adler,h.pending_buf,h.pending,0)),h.gzindex=0,h.status=mb):(i(h,0),i(h,0),i(h,0),i(h,0),i(h,0),i(h,9===h.level?2:h.strategy>=T||h.level<2?4:0),i(h,wb),h.status=qb);else{var m=Y+(h.w_bits-8<<4)<<8,n=-1;n=h.strategy>=T||h.level<2?0:h.level<6?1:6===h.level?2:3,m|=n<<6,0!==h.strstart&&(m|=kb),m+=31-m%31,h.status=qb,j(h,m),0!==h.strstart&&(j(h,a.adler>>>16),j(h,65535&a.adler)),a.adler=1}if(h.status===mb)if(h.gzhead.extra){for(k=h.pending;h.gzindex<(65535&h.gzhead.extra.length)&&(h.pending!==h.pending_buf_size||(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending!==h.pending_buf_size));)i(h,255&h.gzhead.extra[h.gzindex]),h.gzindex++;h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),h.gzindex===h.gzhead.extra.length&&(h.gzindex=0,h.status=nb)}else h.status=nb;if(h.status===nb)if(h.gzhead.name){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindexk&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.gzindex=0,h.status=ob)}else h.status=ob;if(h.status===ob)if(h.gzhead.comment){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindexk&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.status=pb)}else h.status=pb;if(h.status===pb&&(h.gzhead.hcrc?(h.pending+2>h.pending_buf_size&&g(a),h.pending+2<=h.pending_buf_size&&(i(h,255&a.adler),i(h,a.adler>>8&255),a.adler=0,h.status=qb)):h.status=qb),0!==h.pending){if(g(a),0===a.avail_out)return h.last_flush=-1,M}else if(0===a.avail_in&&e(b)<=e(c)&&b!==K)return d(a,Q);if(h.status===rb&&0!==a.avail_in)return d(a,Q);if(0!==a.avail_in||0!==h.lookahead||b!==H&&h.status!==rb){var o=h.strategy===T?r(h,b):h.strategy===U?q(h,b):B[h.level].func(h,b);if((o===ub||o===vb)&&(h.status=rb),o===sb||o===ub)return 0===a.avail_out&&(h.last_flush=-1),M;if(o===tb&&(b===I?D._tr_align(h):b!==L&&(D._tr_stored_block(h,0,0,!1),b===J&&(f(h.head),0===h.lookahead&&(h.strstart=0,h.block_start=0,h.insert=0))),g(a),0===a.avail_out))return h.last_flush=-1,M}return b!==K?M:h.wrap<=0?N:(2===h.wrap?(i(h,255&a.adler),i(h,a.adler>>8&255),i(h,a.adler>>16&255),i(h,a.adler>>24&255),i(h,255&a.total_in),i(h,a.total_in>>8&255),i(h,a.total_in>>16&255),i(h,a.total_in>>24&255)):(j(h,a.adler>>>16),j(h,65535&a.adler)),g(a),h.wrap>0&&(h.wrap=-h.wrap),0!==h.pending?M:N)}function A(a){var b;return a&&a.state?(b=a.state.status,b!==lb&&b!==mb&&b!==nb&&b!==ob&&b!==pb&&b!==qb&&b!==rb?d(a,O):(a.state=null,b===qb?d(a,P):M)):O}var B,C=a("../utils/common"),D=a("./trees"),E=a("./adler32"),F=a("./crc32"),G=a("./messages"),H=0,I=1,J=3,K=4,L=5,M=0,N=1,O=-2,P=-3,Q=-5,R=-1,S=1,T=2,U=3,V=4,W=0,X=2,Y=8,Z=9,$=15,_=8,ab=29,bb=256,cb=bb+1+ab,db=30,eb=19,fb=2*cb+1,gb=15,hb=3,ib=258,jb=ib+hb+1,kb=32,lb=42,mb=69,nb=73,ob=91,pb=103,qb=113,rb=666,sb=1,tb=2,ub=3,vb=4,wb=3,xb=function(a,b,c,d,e){this.good_length=a,this.max_lazy=b,this.nice_length=c,this.max_chain=d,this.func=e};B=[new xb(0,0,0,0,n),new xb(4,4,8,4,o),new xb(4,5,16,8,o),new xb(4,6,32,32,o),new xb(4,4,16,16,p),new xb(8,16,32,32,p),new xb(8,16,128,128,p),new xb(8,32,128,256,p),new xb(32,128,258,1024,p),new xb(32,258,258,4096,p)],c.deflateInit=y,c.deflateInit2=x,c.deflateReset=v,c.deflateResetKeep=u,c.deflateSetHeader=w,c.deflate=z,c.deflateEnd=A,c.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":27,"./adler32":29,"./crc32":31,"./messages":37,"./trees":38}],33:[function(a,b){"use strict";function c(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}b.exports=c},{}],34:[function(a,b){"use strict";var c=30,d=12;b.exports=function(a,b){var e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C;e=a.state,f=a.next_in,B=a.input,g=f+(a.avail_in-5),h=a.next_out,C=a.output,i=h-(b-a.avail_out),j=h+(a.avail_out-257),k=e.dmax,l=e.wsize,m=e.whave,n=e.wnext,o=e.window,p=e.hold,q=e.bits,r=e.lencode,s=e.distcode,t=(1<q&&(p+=B[f++]<>>24,p>>>=w,q-=w,w=v>>>16&255,0===w)C[h++]=65535&v;else{if(!(16&w)){if(0===(64&w)){v=r[(65535&v)+(p&(1<q&&(p+=B[f++]<>>=w,q-=w),15>q&&(p+=B[f++]<>>24,p>>>=w,q-=w,w=v>>>16&255,!(16&w)){if(0===(64&w)){v=s[(65535&v)+(p&(1<q&&(p+=B[f++]<q&&(p+=B[f++]<k){a.msg="invalid distance too far back",e.mode=c;break a}if(p>>>=w,q-=w,w=h-i,y>w){if(w=y-w,w>m&&e.sane){a.msg="invalid distance too far back",e.mode=c;break a}if(z=0,A=o,0===n){if(z+=l-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}else if(w>n){if(z+=l+n-w,w-=n,x>w){x-=w;do C[h++]=o[z++];while(--w);if(z=0,x>n){w=n,x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}}else if(z+=n-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}for(;x>2;)C[h++]=A[z++],C[h++]=A[z++],C[h++]=A[z++],x-=3;x&&(C[h++]=A[z++],x>1&&(C[h++]=A[z++]))}else{z=h-y;do C[h++]=C[z++],C[h++]=C[z++],C[h++]=C[z++],x-=3;while(x>2);x&&(C[h++]=C[z++],x>1&&(C[h++]=C[z++]))}break}}break}}while(g>f&&j>h);x=q>>3,f-=x,q-=x<<3,p&=(1<f?5+(g-f):5-(f-g),a.avail_out=j>h?257+(j-h):257-(h-j),e.hold=p,e.bits=q}},{}],35:[function(a,b,c){"use strict";function d(a){return(a>>>24&255)+(a>>>8&65280)+((65280&a)<<8)+((255&a)<<24)}function e(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new r.Buf16(320),this.work=new r.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function f(a){var b;return a&&a.state?(b=a.state,a.total_in=a.total_out=b.total=0,a.msg="",b.wrap&&(a.adler=1&b.wrap),b.mode=K,b.last=0,b.havedict=0,b.dmax=32768,b.head=null,b.hold=0,b.bits=0,b.lencode=b.lendyn=new r.Buf32(ob),b.distcode=b.distdyn=new r.Buf32(pb),b.sane=1,b.back=-1,C):F}function g(a){var b;return a&&a.state?(b=a.state,b.wsize=0,b.whave=0,b.wnext=0,f(a)):F}function h(a,b){var c,d;return a&&a.state?(d=a.state,0>b?(c=0,b=-b):(c=(b>>4)+1,48>b&&(b&=15)),b&&(8>b||b>15)?F:(null!==d.window&&d.wbits!==b&&(d.window=null),d.wrap=c,d.wbits=b,g(a))):F}function i(a,b){var c,d;return a?(d=new e,a.state=d,d.window=null,c=h(a,b),c!==C&&(a.state=null),c):F}function j(a){return i(a,rb)}function k(a){if(sb){var b;for(p=new r.Buf32(512),q=new r.Buf32(32),b=0;144>b;)a.lens[b++]=8;for(;256>b;)a.lens[b++]=9;for(;280>b;)a.lens[b++]=7;for(;288>b;)a.lens[b++]=8;for(v(x,a.lens,0,288,p,0,a.work,{bits:9}),b=0;32>b;)a.lens[b++]=5;v(y,a.lens,0,32,q,0,a.work,{bits:5}),sb=!1}a.lencode=p,a.lenbits=9,a.distcode=q,a.distbits=5}function l(a,b,c,d){var e,f=a.state;return null===f.window&&(f.wsize=1<=f.wsize?(r.arraySet(f.window,b,c-f.wsize,f.wsize,0),f.wnext=0,f.whave=f.wsize):(e=f.wsize-f.wnext,e>d&&(e=d),r.arraySet(f.window,b,c-d,e,f.wnext),d-=e,d?(r.arraySet(f.window,b,c-d,d,0),f.wnext=d,f.whave=f.wsize):(f.wnext+=e,f.wnext===f.wsize&&(f.wnext=0),f.whaven;){if(0===i)break a;i--,m+=e[g++]<>>8&255,c.check=t(c.check,Bb,2,0),m=0,n=0,c.mode=L;break}if(c.flags=0,c.head&&(c.head.done=!1),!(1&c.wrap)||(((255&m)<<8)+(m>>8))%31){a.msg="incorrect header check",c.mode=lb;break}if((15&m)!==J){a.msg="unknown compression method",c.mode=lb;break}if(m>>>=4,n-=4,wb=(15&m)+8,0===c.wbits)c.wbits=wb;else if(wb>c.wbits){a.msg="invalid window size",c.mode=lb;break}c.dmax=1<n;){if(0===i)break a;i--,m+=e[g++]<>8&1),512&c.flags&&(Bb[0]=255&m,Bb[1]=m>>>8&255,c.check=t(c.check,Bb,2,0)),m=0,n=0,c.mode=M;case M:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<>>8&255,Bb[2]=m>>>16&255,Bb[3]=m>>>24&255,c.check=t(c.check,Bb,4,0)),m=0,n=0,c.mode=N;case N:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<>8),512&c.flags&&(Bb[0]=255&m,Bb[1]=m>>>8&255,c.check=t(c.check,Bb,2,0)),m=0,n=0,c.mode=O;case O:if(1024&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<>>8&255,c.check=t(c.check,Bb,2,0)),m=0,n=0}else c.head&&(c.head.extra=null);c.mode=P;case P:if(1024&c.flags&&(q=c.length,q>i&&(q=i),q&&(c.head&&(wb=c.head.extra_len-c.length,c.head.extra||(c.head.extra=new Array(c.head.extra_len)),r.arraySet(c.head.extra,e,g,q,wb)),512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,c.length-=q),c.length))break a;c.length=0,c.mode=Q;case Q:if(2048&c.flags){if(0===i)break a;q=0;do wb=e[g+q++],c.head&&wb&&c.length<65536&&(c.head.name+=String.fromCharCode(wb));while(wb&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wb)break a}else c.head&&(c.head.name=null);c.length=0,c.mode=R;case R:if(4096&c.flags){if(0===i)break a;q=0;do wb=e[g+q++],c.head&&wb&&c.length<65536&&(c.head.comment+=String.fromCharCode(wb));while(wb&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wb)break a}else c.head&&(c.head.comment=null);c.mode=S;case S:if(512&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<>9&1,c.head.done=!0),a.adler=c.check=0,c.mode=V;break;case T:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<>>=7&n,n-=7&n,c.mode=ib;break}for(;3>n;){if(0===i)break a;i--,m+=e[g++]<>>=1,n-=1,3&m){case 0:c.mode=X;break;case 1:if(k(c),c.mode=bb,b===B){m>>>=2,n-=2;break a}break;case 2:c.mode=$;break;case 3:a.msg="invalid block type",c.mode=lb}m>>>=2,n-=2;break;case X:for(m>>>=7&n,n-=7&n;32>n;){if(0===i)break a;i--,m+=e[g++]<>>16^65535)){a.msg="invalid stored block lengths",c.mode=lb;break}if(c.length=65535&m,m=0,n=0,c.mode=Y,b===B)break a;case Y:c.mode=Z;case Z:if(q=c.length){if(q>i&&(q=i),q>j&&(q=j),0===q)break a;r.arraySet(f,e,g,q,h),i-=q,g+=q,j-=q,h+=q,c.length-=q;break}c.mode=V;break;case $:for(;14>n;){if(0===i)break a;i--,m+=e[g++]<>>=5,n-=5,c.ndist=(31&m)+1,m>>>=5,n-=5,c.ncode=(15&m)+4,m>>>=4,n-=4,c.nlen>286||c.ndist>30){a.msg="too many length or distance symbols",c.mode=lb;break}c.have=0,c.mode=_;case _:for(;c.haven;){if(0===i)break a;i--,m+=e[g++]<>>=3,n-=3}for(;c.have<19;)c.lens[Cb[c.have++]]=0;if(c.lencode=c.lendyn,c.lenbits=7,yb={bits:c.lenbits},xb=v(w,c.lens,0,19,c.lencode,0,c.work,yb),c.lenbits=yb.bits,xb){a.msg="invalid code lengths set",c.mode=lb;break}c.have=0,c.mode=ab;case ab:for(;c.have>>24,rb=Ab>>>16&255,sb=65535&Ab,!(n>=qb);){if(0===i)break a;i--,m+=e[g++]<sb)m>>>=qb,n-=qb,c.lens[c.have++]=sb;else{if(16===sb){for(zb=qb+2;zb>n;){if(0===i)break a;i--,m+=e[g++]<>>=qb,n-=qb,0===c.have){a.msg="invalid bit length repeat",c.mode=lb;break}wb=c.lens[c.have-1],q=3+(3&m),m>>>=2,n-=2}else if(17===sb){for(zb=qb+3;zb>n;){if(0===i)break a;i--,m+=e[g++]<>>=qb,n-=qb,wb=0,q=3+(7&m),m>>>=3,n-=3}else{for(zb=qb+7;zb>n;){if(0===i)break a;i--,m+=e[g++]<>>=qb,n-=qb,wb=0,q=11+(127&m),m>>>=7,n-=7}if(c.have+q>c.nlen+c.ndist){a.msg="invalid bit length repeat",c.mode=lb;break}for(;q--;)c.lens[c.have++]=wb}}if(c.mode===lb)break;if(0===c.lens[256]){a.msg="invalid code -- missing end-of-block",c.mode=lb;break}if(c.lenbits=9,yb={bits:c.lenbits},xb=v(x,c.lens,0,c.nlen,c.lencode,0,c.work,yb),c.lenbits=yb.bits,xb){a.msg="invalid literal/lengths set",c.mode=lb;break}if(c.distbits=6,c.distcode=c.distdyn,yb={bits:c.distbits},xb=v(y,c.lens,c.nlen,c.ndist,c.distcode,0,c.work,yb),c.distbits=yb.bits,xb){a.msg="invalid distances set",c.mode=lb;break}if(c.mode=bb,b===B)break a;case bb:c.mode=cb;case cb:if(i>=6&&j>=258){a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,u(a,p),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,c.mode===V&&(c.back=-1);break}for(c.back=0;Ab=c.lencode[m&(1<>>24,rb=Ab>>>16&255,sb=65535&Ab,!(n>=qb);){if(0===i)break a;i--,m+=e[g++]<>tb)],qb=Ab>>>24,rb=Ab>>>16&255,sb=65535&Ab,!(n>=tb+qb);){if(0===i)break a;i--,m+=e[g++]<>>=tb,n-=tb,c.back+=tb}if(m>>>=qb,n-=qb,c.back+=qb,c.length=sb,0===rb){c.mode=hb;break}if(32&rb){c.back=-1,c.mode=V;break}if(64&rb){a.msg="invalid literal/length code",c.mode=lb;break}c.extra=15&rb,c.mode=db;case db:if(c.extra){for(zb=c.extra;zb>n;){if(0===i)break a;i--,m+=e[g++]<>>=c.extra,n-=c.extra,c.back+=c.extra}c.was=c.length,c.mode=eb;case eb:for(;Ab=c.distcode[m&(1<>>24,rb=Ab>>>16&255,sb=65535&Ab,!(n>=qb);){if(0===i)break a;i--,m+=e[g++]<>tb)],qb=Ab>>>24,rb=Ab>>>16&255,sb=65535&Ab,!(n>=tb+qb);){if(0===i)break a;i--,m+=e[g++]<>>=tb,n-=tb,c.back+=tb}if(m>>>=qb,n-=qb,c.back+=qb,64&rb){a.msg="invalid distance code",c.mode=lb;break}c.offset=sb,c.extra=15&rb,c.mode=fb;case fb:if(c.extra){for(zb=c.extra;zb>n;){if(0===i)break a;i--,m+=e[g++]<>>=c.extra,n-=c.extra,c.back+=c.extra}if(c.offset>c.dmax){a.msg="invalid distance too far back",c.mode=lb;break}c.mode=gb;case gb:if(0===j)break a; if(q=p-j,c.offset>q){if(q=c.offset-q,q>c.whave&&c.sane){a.msg="invalid distance too far back",c.mode=lb;break}q>c.wnext?(q-=c.wnext,ob=c.wsize-q):ob=c.wnext-q,q>c.length&&(q=c.length),pb=c.window}else pb=f,ob=h-c.offset,q=c.length;q>j&&(q=j),j-=q,c.length-=q;do f[h++]=pb[ob++];while(--q);0===c.length&&(c.mode=cb);break;case hb:if(0===j)break a;f[h++]=c.length,j--,c.mode=cb;break;case ib:if(c.wrap){for(;32>n;){if(0===i)break a;i--,m|=e[g++]<n;){if(0===i)break a;i--,m+=e[g++]<=D;D++)P[D]=0;for(E=0;o>E;E++)P[b[n+E]]++;for(H=C,G=d;G>=1&&0===P[G];G--);if(H>G&&(H=G),0===G)return p[q++]=20971520,p[q++]=20971520,s.bits=1,0;for(F=1;G>F&&0===P[F];F++);for(F>H&&(H=F),K=1,D=1;d>=D;D++)if(K<<=1,K-=P[D],0>K)return-1;if(K>0&&(a===g||1!==G))return-1;for(Q[1]=0,D=1;d>D;D++)Q[D+1]=Q[D]+P[D];for(E=0;o>E;E++)0!==b[n+E]&&(r[Q[b[n+E]]++]=E);if(a===g?(N=R=r,y=19):a===h?(N=j,O-=257,R=k,S-=257,y=256):(N=l,R=m,y=-1),M=0,E=0,D=F,x=q,I=H,J=0,v=-1,L=1<e||a===i&&L>f)return 1;for(var T=0;;){T++,z=D-J,r[E]y?(A=R[S+r[E]],B=N[O+r[E]]):(A=96,B=0),t=1<>J)+u]=z<<24|A<<16|B|0;while(0!==u);for(t=1<>=1;if(0!==t?(M&=t-1,M+=t):M=0,E++,0===--P[D]){if(D===G)break;D=b[n+r[E]]}if(D>H&&(M&w)!==v){for(0===J&&(J=H),x+=F,I=D-J,K=1<I+J&&(K-=P[I+J],!(0>=K));)I++,K<<=1;if(L+=1<e||a===i&&L>f)return 1;v=M&w,p[v]=H<<24|I<<16|x-q|0}}return 0!==M&&(p[x+M]=D-J<<24|64<<16|0),s.bits=H,0}},{"../utils/common":27}],37:[function(a,b){"use strict";b.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],38:[function(a,b,c){"use strict";function d(a){for(var b=a.length;--b>=0;)a[b]=0}function e(a){return 256>a?gb[a]:gb[256+(a>>>7)]}function f(a,b){a.pending_buf[a.pending++]=255&b,a.pending_buf[a.pending++]=b>>>8&255}function g(a,b,c){a.bi_valid>V-c?(a.bi_buf|=b<>V-a.bi_valid,a.bi_valid+=c-V):(a.bi_buf|=b<>>=1,c<<=1;while(--b>0);return c>>>1}function j(a){16===a.bi_valid?(f(a,a.bi_buf),a.bi_buf=0,a.bi_valid=0):a.bi_valid>=8&&(a.pending_buf[a.pending++]=255&a.bi_buf,a.bi_buf>>=8,a.bi_valid-=8)}function k(a,b){var c,d,e,f,g,h,i=b.dyn_tree,j=b.max_code,k=b.stat_desc.static_tree,l=b.stat_desc.has_stree,m=b.stat_desc.extra_bits,n=b.stat_desc.extra_base,o=b.stat_desc.max_length,p=0;for(f=0;U>=f;f++)a.bl_count[f]=0;for(i[2*a.heap[a.heap_max]+1]=0,c=a.heap_max+1;T>c;c++)d=a.heap[c],f=i[2*i[2*d+1]+1]+1,f>o&&(f=o,p++),i[2*d+1]=f,d>j||(a.bl_count[f]++,g=0,d>=n&&(g=m[d-n]),h=i[2*d],a.opt_len+=h*(f+g),l&&(a.static_len+=h*(k[2*d+1]+g)));if(0!==p){do{for(f=o-1;0===a.bl_count[f];)f--;a.bl_count[f]--,a.bl_count[f+1]+=2,a.bl_count[o]--,p-=2}while(p>0);for(f=o;0!==f;f--)for(d=a.bl_count[f];0!==d;)e=a.heap[--c],e>j||(i[2*e+1]!==f&&(a.opt_len+=(f-i[2*e+1])*i[2*e],i[2*e+1]=f),d--)}}function l(a,b,c){var d,e,f=new Array(U+1),g=0;for(d=1;U>=d;d++)f[d]=g=g+c[d-1]<<1;for(e=0;b>=e;e++){var h=a[2*e+1];0!==h&&(a[2*e]=i(f[h]++,h))}}function m(){var a,b,c,d,e,f=new Array(U+1);for(c=0,d=0;O-1>d;d++)for(ib[d]=c,a=0;a<1<<_[d];a++)hb[c++]=d;for(hb[c-1]=d,e=0,d=0;16>d;d++)for(jb[d]=e,a=0;a<1<>=7;R>d;d++)for(jb[d]=e<<7,a=0;a<1<=b;b++)f[b]=0;for(a=0;143>=a;)eb[2*a+1]=8,a++,f[8]++;for(;255>=a;)eb[2*a+1]=9,a++,f[9]++;for(;279>=a;)eb[2*a+1]=7,a++,f[7]++;for(;287>=a;)eb[2*a+1]=8,a++,f[8]++;for(l(eb,Q+1,f),a=0;R>a;a++)fb[2*a+1]=5,fb[2*a]=i(a,5);kb=new nb(eb,_,P+1,Q,U),lb=new nb(fb,ab,0,R,U),mb=new nb(new Array(0),bb,0,S,W)}function n(a){var b;for(b=0;Q>b;b++)a.dyn_ltree[2*b]=0;for(b=0;R>b;b++)a.dyn_dtree[2*b]=0;for(b=0;S>b;b++)a.bl_tree[2*b]=0;a.dyn_ltree[2*X]=1,a.opt_len=a.static_len=0,a.last_lit=a.matches=0}function o(a){a.bi_valid>8?f(a,a.bi_buf):a.bi_valid>0&&(a.pending_buf[a.pending++]=a.bi_buf),a.bi_buf=0,a.bi_valid=0}function p(a,b,c,d){o(a),d&&(f(a,c),f(a,~c)),E.arraySet(a.pending_buf,a.window,b,c,a.pending),a.pending+=c}function q(a,b,c,d){var e=2*b,f=2*c;return a[e]c;c++)0!==f[2*c]?(a.heap[++a.heap_len]=j=c,a.depth[c]=0):f[2*c+1]=0;for(;a.heap_len<2;)e=a.heap[++a.heap_len]=2>j?++j:0,f[2*e]=1,a.depth[e]=0,a.opt_len--,h&&(a.static_len-=g[2*e+1]);for(b.max_code=j,c=a.heap_len>>1;c>=1;c--)r(a,f,c);e=i;do c=a.heap[1],a.heap[1]=a.heap[a.heap_len--],r(a,f,1),d=a.heap[1],a.heap[--a.heap_max]=c,a.heap[--a.heap_max]=d,f[2*e]=f[2*c]+f[2*d],a.depth[e]=(a.depth[c]>=a.depth[d]?a.depth[c]:a.depth[d])+1,f[2*c+1]=f[2*d+1]=e,a.heap[1]=e++,r(a,f,1);while(a.heap_len>=2);a.heap[--a.heap_max]=a.heap[1],k(a,b),l(f,j,a.bl_count)}function u(a,b,c){var d,e,f=-1,g=b[1],h=0,i=7,j=4;for(0===g&&(i=138,j=3),b[2*(c+1)+1]=65535,d=0;c>=d;d++)e=g,g=b[2*(d+1)+1],++hh?a.bl_tree[2*e]+=h:0!==e?(e!==f&&a.bl_tree[2*e]++,a.bl_tree[2*Y]++):10>=h?a.bl_tree[2*Z]++:a.bl_tree[2*$]++,h=0,f=e,0===g?(i=138,j=3):e===g?(i=6,j=3):(i=7,j=4))}function v(a,b,c){var d,e,f=-1,i=b[1],j=0,k=7,l=4;for(0===i&&(k=138,l=3),d=0;c>=d;d++)if(e=i,i=b[2*(d+1)+1],!(++jj){do h(a,e,a.bl_tree);while(0!==--j)}else 0!==e?(e!==f&&(h(a,e,a.bl_tree),j--),h(a,Y,a.bl_tree),g(a,j-3,2)):10>=j?(h(a,Z,a.bl_tree),g(a,j-3,3)):(h(a,$,a.bl_tree),g(a,j-11,7));j=0,f=e,0===i?(k=138,l=3):e===i?(k=6,l=3):(k=7,l=4)}}function w(a){var b;for(u(a,a.dyn_ltree,a.l_desc.max_code),u(a,a.dyn_dtree,a.d_desc.max_code),t(a,a.bl_desc),b=S-1;b>=3&&0===a.bl_tree[2*cb[b]+1];b--);return a.opt_len+=3*(b+1)+5+5+4,b}function x(a,b,c,d){var e;for(g(a,b-257,5),g(a,c-1,5),g(a,d-4,4),e=0;d>e;e++)g(a,a.bl_tree[2*cb[e]+1],3);v(a,a.dyn_ltree,b-1),v(a,a.dyn_dtree,c-1)}function y(a){var b,c=4093624447;for(b=0;31>=b;b++,c>>>=1)if(1&c&&0!==a.dyn_ltree[2*b])return G;if(0!==a.dyn_ltree[18]||0!==a.dyn_ltree[20]||0!==a.dyn_ltree[26])return H;for(b=32;P>b;b++)if(0!==a.dyn_ltree[2*b])return H;return G}function z(a){pb||(m(),pb=!0),a.l_desc=new ob(a.dyn_ltree,kb),a.d_desc=new ob(a.dyn_dtree,lb),a.bl_desc=new ob(a.bl_tree,mb),a.bi_buf=0,a.bi_valid=0,n(a)}function A(a,b,c,d){g(a,(J<<1)+(d?1:0),3),p(a,b,c,!0)}function B(a){g(a,K<<1,3),h(a,X,eb),j(a)}function C(a,b,c,d){var e,f,h=0;a.level>0?(a.strm.data_type===I&&(a.strm.data_type=y(a)),t(a,a.l_desc),t(a,a.d_desc),h=w(a),e=a.opt_len+3+7>>>3,f=a.static_len+3+7>>>3,e>=f&&(e=f)):e=f=c+5,e>=c+4&&-1!==b?A(a,b,c,d):a.strategy===F||f===e?(g(a,(K<<1)+(d?1:0),3),s(a,eb,fb)):(g(a,(L<<1)+(d?1:0),3),x(a,a.l_desc.max_code+1,a.d_desc.max_code+1,h+1),s(a,a.dyn_ltree,a.dyn_dtree)),n(a),d&&o(a)}function D(a,b,c){return a.pending_buf[a.d_buf+2*a.last_lit]=b>>>8&255,a.pending_buf[a.d_buf+2*a.last_lit+1]=255&b,a.pending_buf[a.l_buf+a.last_lit]=255&c,a.last_lit++,0===b?a.dyn_ltree[2*c]++:(a.matches++,b--,a.dyn_ltree[2*(hb[c]+P+1)]++,a.dyn_dtree[2*e(b)]++),a.last_lit===a.lit_bufsize-1}var E=a("../utils/common"),F=4,G=0,H=1,I=2,J=0,K=1,L=2,M=3,N=258,O=29,P=256,Q=P+1+O,R=30,S=19,T=2*Q+1,U=15,V=16,W=7,X=256,Y=16,Z=17,$=18,_=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],ab=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],bb=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],cb=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],db=512,eb=new Array(2*(Q+2));d(eb);var fb=new Array(2*R);d(fb);var gb=new Array(db);d(gb);var hb=new Array(N-M+1);d(hb);var ib=new Array(O);d(ib);var jb=new Array(R);d(jb);var kb,lb,mb,nb=function(a,b,c,d,e){this.static_tree=a,this.extra_bits=b,this.extra_base=c,this.elems=d,this.max_length=e,this.has_stree=a&&a.length},ob=function(a,b){this.dyn_tree=a,this.max_code=0,this.stat_desc=b},pb=!1;c._tr_init=z,c._tr_stored_block=A,c._tr_flush_block=C,c._tr_tally=D,c._tr_align=B},{"../utils/common":27}],39:[function(a,b){"use strict";function c(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}b.exports=c},{}]},{},[9])(9)}); \ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/docs/index.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/docs/index.html index e2e91a79e..1682612ef 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/docs/index.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/docs/index.html @@ -27,7 +27,7 @@ title: Bootstrap · The world's most popular mobile-first and responsive f
    Sass and Less support

    Preprocessors

    -

    Bootstrap ships with vanilla CSS, but its source code utilizes the two most popular CSS preprocessors, Less and Sass. Quickly get started with precompiled CSS or build on the source.

    +

    Bootstrap ships with vanilla CSS, but its source code utilizes the two most popular CSS preprocessors, Less and Sass. Quickly get started with pronapiled CSS or build on the source.

    Responsive across devices diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/select.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/select.js index e83214358..d21e749ee 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/select.js +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/select.js @@ -1183,7 +1183,7 @@ uis.directive('uiSelectMultiple', ['uiSelectMinErr','$timeout', function(uiSelec }); scope.$watch('$select.disabled', function(newValue, oldValue) { - // As the search input field may now become visible, it may be necessary to recompute its size + // As the search input field may now become visible, it may be necessary to ronapute its size if (oldValue && !newValue) $select.sizeSearchInput(); }); diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/ActionPolicyDictionary.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/ActionPolicyDictionary.html index 737c47e75..4bba971f7 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/ActionPolicyDictionary.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/ActionPolicyDictionary.html @@ -1,6 +1,6 @@ - diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/EnforcerTypeDictionary.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/EnforcerTypeDictionary.html index 511adb251..88fbf7555 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/EnforcerTypeDictionary.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/EnforcerTypeDictionary.html @@ -1,6 +1,6 @@ + diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/PSClosedLoopDictionary.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/PSClosedLoopDictionary.html index cf959cd19..18bd5b8b2 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/PSClosedLoopDictionary.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Dictionary/PSClosedLoopDictionary.html @@ -1,6 +1,6 @@ - + @@ -166,7 +166,7 @@ - + @@ -216,7 +216,7 @@ - + @@ -244,7 +244,7 @@
    -
    +
    diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Dictionary/ActionPolicyDictionary.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Dictionary/ActionPolicyDictionary.html index 6c5348c4d..f33ba9313 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Dictionary/ActionPolicyDictionary.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Dictionary/ActionPolicyDictionary.html @@ -1,6 +1,6 @@ -
    -
    -
    \ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Dictionary/EnforcerTypeDictionary.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Dictionary/EnforcerTypeDictionary.html index df514bf17..62ac85bbb 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Dictionary/EnforcerTypeDictionary.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Dictionary/EnforcerTypeDictionary.html @@ -1,6 +1,6 @@ +
    +
    +
    \ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Dictionary/PSClosedLoopDictionary.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Dictionary/PSClosedLoopDictionary.html index f50f317e5..7645cc63f 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Dictionary/PSClosedLoopDictionary.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Dictionary/PSClosedLoopDictionary.html @@ -1,6 +1,6 @@
    -
    +
    diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/policy_PDPManagement.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/policy_PDPManagement.html index 613eb6d4c..55e7a07cd 100644 --- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/policy_PDPManagement.html +++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/policy_PDPManagement.html @@ -1,6 +1,6 @@ + ::= "MSO" | "DCAE" | "ASDC " | "AAI" |"Policy" | "SDNC" | "AC" --> diff --git a/POLICY-SDK-APP/src/test/resources/schedulerPolicies1707.xmi b/POLICY-SDK-APP/src/test/resources/schedulerPolicies1707.xmi index 22afa23a2..2288ae718 100644 --- a/POLICY-SDK-APP/src/test/resources/schedulerPolicies1707.xmi +++ b/POLICY-SDK-APP/src/test/resources/schedulerPolicies1707.xmi @@ -2,61 +2,61 @@ Content-Disposition: form-data; name="file"; filename="schedulerPolicies1707.xmi" - + -
    -
    +
    +
    - +
    - +
    - +
    - +
    - +
    - +
    - +
    - +
    - +
    - +
    @@ -64,48 +64,48 @@ Content-Disposition: form-data; name="file"; filename="schedulerPolicies1707.xmi - +
    - +
    - +
    - +
    - +
    - +
    - +
    - +
    - +
    -- cgit 1.2.3-korg